diff --git a/.gitignore b/.gitignore index 8a80bcc2560..9511e9ede2f 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,9 @@ dist/ cloud-*.tar.bz2 *.log *.pyc +*.egginfo/ +*.egg-info/ +*.prefs build.number api.log.*.gz cloud.log.*.* @@ -45,6 +48,10 @@ deps/awsapi-lib/ git-remote-https.exe.stackdump *.swp tools/devcloud/devcloudbox/.vagrant +tools/cli/cloudmonkey/marvin/ +tools/cli/cloudmonkey/precache.py +tools/marvin/marvin/cloudstackAPI/ +tools/cli/build/ *.jar *.war *.mar @@ -59,3 +66,11 @@ awsapi/modules/* .settings.xml .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/CHANGES b/CHANGES new file mode 100644 index 00000000000..a745a467c3b --- /dev/null +++ b/CHANGES @@ -0,0 +1,37 @@ +Apache CloudStack (Incubating) CHANGES +====================================== + +Full release notes for each release are located in the project's documentation website: http://incubator.apache.org/cloudstack/docs + +Version 4.0.0-incubating +------------------------ + +This is the first release of CloudStack from within the Apache Software Foundation. + +Build Tool Changes: + + * The project now uses a combination of maven3 and ant for building + * License header auditing is now implemented via the Apache RAT Maven plugin + * Some integrations have been disabled in the default build, due to the license types of our dependencies (See README.md for details on how to build with the optional capabilities) + +New Features: + + * Inter-VLAN Routing (VPC) + * Site-to-Site VPN + * Local Storage Support for Data Volumes + * Virtual Resource Tagging + * Secure Console Access on XenServer + * Added the ability to create a VM without immediately starting it (via API) + * Upload an Existing Volume to a Virtual Machine + * Dedicated High-Availability Hosts + * Support for Amazon Web Services API (formerly a separate package) + * AWS API Extensions to include Tagging + * Support for Nicira NVP (L2) + * Ceph RBD Support for KVM + * Support for Caringo as Secondary Storage + * KVM Hypervisor support upgraded to work with Ubuntu 12.04 and RHEL 6.3 + +Security Fixes: + + * CVE-2012-4501: Apache CloudStack configuration vulnerability + diff --git a/INSTALL.md b/INSTALL.md index 54d02512ba2..61ebadfdc3d 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -1,19 +1,16 @@ -This document describes how to set up and configure a single server CloudStack -development environment. If you aren't looking for a development environment, -the easiest way to deploy CloudStack is by using RPM or DEB packages from: +This document describes how to develop, build, package and install Apache CloudStack +(Incubating). For more information please refer to the project's website: - - http://cloudstack.org/download.html - - http://jenkins.cloudstack.org (CI/Build server) - - http://cloudstack.apt-get.eu (Debian repository) + http://incubator.apache.org/cloudstack -CloudStack developers use various platforms for development, this guide will -focus on CentOS and was tested against a CentOS 6.2 x86_64 setup. +Apache CloudStack developers use various platforms for development, this guide +was tested against a CentOS 6.2 x86_64 setup. Refer to the [wiki](http://cwiki.apache.org/confluence/display/CLOUDSTACK/Index) for the latest information, especially: - - [Setting up development environment](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Setting+up+CloudStack+Development+Environment) for CloudStack. - - [Building](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Building+with+Maven) CloudStack. + - [Setting up development environment](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Setting+up+CloudStack+Development+Environment) for Apache CloudStack. + - [Building](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Building) Apache CloudStack. ## Setting up Development Environment @@ -32,7 +29,7 @@ Set up Maven (3.0.4): $ echo export M2_HOME=/usr/local/apache-maven-3.0.4 >> ~/.bashrc # or .zshrc or .profile $ echo export PATH=${M2_HOME}/bin:${PATH} >> ~/.bashrc # or .zshrc or .profile -Note: Tomcat 6.0.35 has some known issue with CloudStack, please use Tomcat +Note: Tomcat 6.0.35 has some known issue with Apache CloudStack, please use Tomcat 6.0.33 from http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.33/bin ### Configure Environment @@ -50,22 +47,22 @@ Generate you ssh keys, useful for ssh-ing to your hosts and vm etc.: $ ssh-keygen -t rsa -q -CloudStack uses some ports, make sure at least those used by the management +Apache CloudStack uses some ports, make sure at least those used by the management server are available and not blocked by any local firewall. Following ports are -used by CloudStack and its entities: +used by Apache CloudStack and its entities: -8787: CloudStack (Tomcat) debug socket -9090, 8250: CloudStack Management Server, User/Client API -8096: User/Client to CloudStack Management Server (unauthenticated) -3306: MySQL Server -3922, 8250, 80/443, 111/2049, 53: Secondary Storage VM -3922, 8250, 53: Console Proxy VM -3922, 8250, 53: Virtual Router -22, 80, 443: XenServer, XAPI -22: KVM -443: vCenter -DNS: 53 -NFS: 111/2049 + 8787: Apache CloudStack (Tomcat) debug socket + 9090, 8250: Apache CloudStack Management Server, User/Client API + 8096: User/Client to CloudStack Management Server (unauthenticated) + 3306: MySQL Server + 3922, 8250, 80/443, 111/2049, 53: Secondary Storage VM + 3922, 8250, 53: Console Proxy VM + 3922, 8250, 53: Virtual Router + 22, 80, 443: XenServer, XAPI + 22: KVM + 443: vCenter + DNS: 53 + NFS: 111/2049 ### Configuring MySQL Server @@ -92,33 +89,45 @@ For example, for master: ## Building -Populate the dependencies using Maven: - $ mvn -P deps - -Clean previous build, if needed: +Clean and build: $ mvn clean - $ ant clean-all - $ ant clean-tomcat + $ mvn install -Build all sub-modules: +In case you want support for VMWare, SRX and other non-Apache (referred to as nonoss) +compliant libs, you may download the following jar artifacts from respective vendors: - $ ant build-all + deps/cloud-iControl.jar + deps/cloud-manageontap.jar + deps/cloud-netscaler-sdx.jar + deps/cloud-netscaler.jar + deps/vmware-apputils.jar + deps/vmware-vim.jar + deps/vmware-vim25.jar -Deploy the built project on tomcat: +Install them to ~/.m2 so maven can get them as dependencies: - $ ant deploy-server + $ cd deps + $ ./install-non-oss.sh + +And build them with the nonoss flag: + + $ mvn install -Dnonoss Clear old database (if any) and deploy the database schema: - $ ant deploydb + $ mvn -P developer -pl developer -Ddeploydb -Start the management server in debug mode: +Export the following variable if you need to run and debug the management server: - $ ant debug + $ export MAVEN_OPTS="-Xmx1024m -Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n" -If this works, you've successfully setup a single server CloudStack installation. +Start the management server: + + $ mvn -pl :cloud-client-ui jetty:run + +If this works, you've successfully setup a single server Apache CloudStack installation. Open the following URL on your browser to access the Management Server UI: @@ -131,13 +140,87 @@ Or, The default credentials are; user: admin, password: password and the domain field should be left blank which is defaulted to the ROOT domain. -## Packaging +If you want to contribute your changes, send your [git formatted patch](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Git) to: +https://reviews.apache.org/groups/cloudstack or contact on the developer mailing list. -To create rpms: +## Packaging and Installation - $ mvn -P deps && ./waf rpm +Before packaging, please make sure you go through the "Building" section above. +This section describes packaging and installation. + +### Debian/Ubuntu To create debs: - $ mvn -P deps && dpkg-buildpackage + $ mvn -P deps # -D nonoss, for nonoss as described in the "Building" section above + $ dpkg-buildpackage +All the deb packages will be created in ../$PWD + +To create an apt repo: (assuming appropriate user privileges) + + $ path=/path/to/your/webserver/cloudstack + $ mv ../*.deb $path + $ dpkg-scanpackages $path /dev/null | gzip -9c > $path/Packages.gz + +Configure your system to use your new apt repo: + + $ echo "deb $path ./" >> /etc/apt/sources.list.d/cloudstack.list + +Installation: + +Install needed packages, apt-get upgrade for upgrading: + + $ apt-get update + $ apt-get install cloud-client # management server + $ apt-get install mysql-server # mysql server + $ apt-get install cloud-agent cloud-system-iso # agent (kvm) + $ apt-get install cloud-awsapi # awsapi server + $ apt-get install cloud-usage # usage server + +### RHEL/CentOS + +To create rpms: + + $ mvn -P deps # -D nonoss, for nonoss as described in the "Building" section above + $ ./waf rpm + +All the rpm packages will be create in artifacts/rpmbuild/RPMS/x86_64 + +To create a yum repo: (assuming appropriate user privileges) + + $ path=/path/to/your/webserver/cloudstack + $ cd artifacts/rpmbuild/RPMS/x86_64 + $ mv *.rpm $path + $ createrepo $path + +Configure your system to use your new yum repo, add the following to /etc/yum.repos.d/cloudstack.repo: + + [apache-cloudstack] + name=Apache CloudStack + baseurl=http://webserver.tld/path/to/repo + enabled=1 + gpgcheck=0 + +Installation: + +Install needed packages: + + $ yum update + $ yum install cloud-client # management server + $ yum install mysql-server # mysql server + $ yum install cloud-agent # agent (kvm) + $ yum install cloud-usage # usage server + +## Notes + +If you will be using Xen as your hypervisor, please download [vhd-util](http://download.cloud.com.s3.amazonaws.com/tools/vhd-util) + +If management server is installed on RHEL/CentOS, then copy vhd-util into: +/usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/ + +If management server is installed on Ubuntu, then put vhd-util into: +/usr/lib/cloud/common/scripts/vm/hypervisor/xenserver/vhd-util + +Once, you've successfully installed Apache CloudStack you may read the user manuals +and guides which contains technical documentation for Apache CloudStack. diff --git a/KEYS b/KEYS deleted file mode 100644 index b399d9cb662..00000000000 --- a/KEYS +++ /dev/null @@ -1,288 +0,0 @@ -This file contains the PGP keys of various developers. - -Users: pgp < KEYS - gpg --import KEYS -Developers: - pgp -kxa and append it to this file. - (pgpk -ll && pgpk -xa ) - >> this file. - (gpg --list-sigs - && gpg --armor --export ) >> - this file. -Type Bits/KeyID Date User ID -pub 4096R/CC56CEA8 2012-08-06 [expires: 2016-08-06] -uid Chip Childers -sig 3 CC56CEA8 2012-08-06 Chip Childers -sub 4096R/A99A5D58 2012-08-06 [expires: 2016-08-06] -sig CC56CEA8 2012-08-06 Chip Childers - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG/MacGPG2 v2.0.18 (Darwin) -Comment: GPGTools - http://gpgtools.org - -mQINBFAgC58BEADAGUUl5EP3pNsVbZMHejGbImIDvbNCkuGCmiVoC154k7FO7YjH -PnbB7kyzfyfsj8eA+mgHHvbzOTk/7dDeaudL561FfsTSxyeVt1ctzBYh9z2V2EMa -9mv48c226QXRf/GInzLS1iD1bOPq9H5RywW4h1u/JqT9KiuBuwowliDlHRornQRg -dhxnjITO6xOhQajqfVXQ1Kz3DcbU9OydfPLKshbfRJC6U5dhGk4AGWKsAJHJDlzj -SPswcJrkuDo0GB9o+nPYrKFRJZy5AyDtr7gmRz6EiGjlZWIf38KxfeNcE6oQPP+7 -9Exlx1ZnWT5Uv/8yU2lgtzhi7/zHw+uB6Ujh0+zCcVgS2Y9ldsA7T0b/Tvlp/Yz4 -hYUMVI6tPPSgehIzRMT4Ym4AcOG/0h5YtecSrOdHIl00htfr1Nj9vIAv8FurebVR -fnfaYbJNKgN3MJLdMSvmlaxvZipIZ6EbWU2BUl7mtZR8zsIoMJedxx9w38UBwdhp -jlxtH5ibZP/WKmIf2hqB4sYrwDioZailjRreNlC5drkljcOGoofXgu/Ahu6dZGHu -4sVH/g+8YhQt7zVs6ytaGLTud33NAELSn15DRrfxQm2sEFhHFKW8Lg0LvjB1RtiM -l2CmFCXk0MMi9IrU4/7q9E7teatztPBcF6Y+Afs16MqUfR81elyPF7YQlQARAQAB -tCdDaGlwIENoaWxkZXJzIDxjaGlwY2hpbGRlcnNAYXBhY2hlLm9yZz6JAj0EEwEC -ACcCGy8FCQeGH4ACHgECF4AFAlAgEF0FCwkIBwMFFQoJCAsFFgIDAQAACgkQw6OS -dcxWzqg0eBAAoHiNFFPNR0zdOELqz0luaTaNNUEit+LBHB1eA63hwY4PplfkOCg+ -UT2lojkZtsiNYuPi++Sub11+HQpVf4uDAGy5VtyIUl/tO3qRmULcJJwoXrYqHxd9 -xrrWYRhasKGNqPEB873UxMPgWVZYcKPRgwZKXUgLl7Dub5iCSVN/lCto5D45R8jA -RzeTjkNvyA+ZPUiblCuKZPSqd4WCN5MRG4muN3+5hwCL6xyrXIvsPkaZXQqhjw0Q -89PUSHhruoHzAi41lscXPF1ap93qvJ4QO12YM9GCQxLRyUOJStLj2OugOjVN/d0q -1ryuBo8ND/W/gYjzIPAQ2U5qkQEjQB/vfuIGl8Gn8s5XA9KtXHqVwz2hbGMpIoCM -0+27JEikrQOitfw86f0aWT1kaceMti7N2ECDEwjsnFf0Uz8dEJ2eInKZrlwgmM0S -/K2gf8/9pbhZ1X9LDYkATCqPzFRLyOuJeHNwcxSDPiWAALoPN57jLJ1702XjGcQt -NBf1p+ylXmdzZjcUz9mKHIEEX7unwp74AVEOyIXuLlyScDR9qTSHhVzCpWQntl6u -0WQmbaoLdAfhu5b80raMdnAbyGQIVtNV4RU0dP8IowkE7cHekHb3NE12K7n3Yx+d -msIXAMsvWx5scfS0HAqIauaA/Sg26lXwj6w60KB+wE1xA2VAWGunSP25Ag0EUCAL -nwEQAOQptLWHnr8uzTZlaRr1N6Aabvz3cLFXf4HCJdWMx9vShPuwWZqrJw4CAnVj -hZA/7NgyBXfBVfcW4Yno0KkHkpKsYy1pYUXIeBDX1FTLZ5H4o7Yv79RaHNl3kgX8 -OodIMGvAee2z4twkniO/u9mnjy1i56hoeQLRVfZZ25Rnlr5PnRdFcqBjMC91i6nr -XdS47Lb1Ttln0yPYtN9j5sD09HZiuCY/b685nB/UlxKhTsE2XfPjZFuBznnOl01/ -FLX8Nn/SeEySdI0gOlzLXU3EAnp0k1OLDXMXC8/EQ/bB4VIwuS4Vu3RmKA0kikgm -nKeuPOTfCpBzzyo/NXCop1Ik/iKgVkp12wRwMp/K5fDg88ib+A8Naxdu25dQCUxH -pJJJ+KwhNf/UKVGpUZOMDAYmUCfisNbulOeS0RMKNzwMXaZzQSvquO8GSlnQ0aal -7Jjl/X/x1boS1dfMAlEeC7jQOm4O4HqSGPEIdoyNbUKupFjytYq3HZ/WMF79kyFh -Xx7khOjiCtopc/sAasFCMa+55/OBN6FThQ4f97UdlyEVxnMADnqOH5uQH5oJ5Vck -k35JOAXWY2fbZSkvKLj7hUZhIx5ja7l4uEnAkM2SxXS+mW9oRfX+pxRAEziUMSaZ -VuGcHkiO/E8viWxtKWbkQw5Ii6OpNLy9wF7YiVSXr7b27lm5ABEBAAGJBEQEGAEC -AA8FAlAgC58CGy4FCQeGH4ACKQkQw6OSdcxWzqjBXSAEGQECAAYFAlAgC58ACgkQ -lD2YH6maXVgyUhAAhWGhG52edHVMELz4wWaqiMKKNPM6GKsI0ZvmaroF0EWt1n9U -TGDyXK+VX/7WXIhqWPdsT390zmwV0bAdXdziPoeQ7DlEz74IRzMBsyEZwMtZ5Q83 -JGDmhjCr3NBVgckzZOl0JXtzyQovtLvCN88WCUIuNaZ2GI6VG8wS3prsKOL9hRNx -y4NNPpCW/QB1/N4A3QlBdKSGyTKCg9VsMwvtZmBdupRipzj2X2DsTOr16TGU4OVW -GNkZ8rUIC6vG7iQctLO8efml3heQU06HJoT+uTZMfXyd7wxHc6SOAENy4ezF62Fd -O9+rtZkE3u0oiW5HUEO4DcE+ufA+Rz/pK6RV65AArb3j6yeX7/VefTGev4SyV+dU -9gplLiXgNEgTfr70uBg+cGV5nxUp0O7ooHMn1g2CnVIkBdPts2rU0wwI5JipsJJ0 -DpK+1x51D7cpUcQ4u/oWtUGHPMVIxXjDWVfwzs9QGy4H0/lqD8LOStuWkeY2IC08 -1ErnY/1TWhmXX7pieh0Zjn1uxi49nxJ9qW0u70CTSzJzz+/17G+f1n9rauKJqVOy -HIGU1TgJ7DjPiwvmMllfQFpRNf/5SV0/tjvsnjzN5YCjN4YaEbVajc9H/Wi8bVNg -ANb5v5FLuhAi04DO0k3bWewd9KE3H7I2uQNaNck/iuYEL6ImAPMA0GUzIbbkxA/+ -Mp4fBbo/i4JpDXEvg8Umeg0wx+otI2ogYFREZjYBWH8txMfGXKVjIfBsFclCm47v -H9wDJ7ISeOR1atWDjHYBE4J2JNqJJREIecztFPQBTo+YUgP6/zDO2RxeZRGYP1rO -+Eld5++kbFEWgi1kWxTKwMlomcoP6hdabA8v8KNZLxRGrKYfE+JMU+PHrfBvO2Ql -4BZ1kmmTaWmGXrgQgpJeWiirF8Ptg2Mq8rCfXnFbOp89ZRNyFDV2Fgyw3BPbPPXE -aygCwpRgHgUrp32gBAGdsdghNn8kN0DFygZKE0kRc6hR7ALiQWoTbA/G/BJjpJQt -RhR4k58e2kWh1uuyFaxcB+Vp/6HXYIe6o8fhX8jwVM47WbINFGbvaz1gGpGzJCY1 -HJBwTMu5IgQ8n69Gs7DCDTVqBOqiDKtdQyZBheWCsIJUkvBHtxkUb7K0kcIA3Fet -46k2GFOEkHCxbKpjeFhcW4atmEShOViiGKVR+g689feVQB6+mI9O4fXmsGO4Zq/k -mEku0Eg95q3+ugVpz8DLctnlvIHVdf6RPieojBKbqPu/34iJqenHmeQUy1TkRKIx -ZEX2mjtW/Tz5VnUX/MUFA67sGIpGJMsvr2sk3Zyovl7GVfsq5K2UqK5pRc2rO8zt -QHVJ58ybqkmx2NgDgmi1gvsoV51mn6TTVs1S/stCtW4= -=eCNG ------END PGP PUBLIC KEY BLOCK----- - -Type Bits/KeyID Date User ID -pub 4096R/DB3ECA42 2012-08-07 [expires: 2017-08-06] -uid Wido den Hollander -sig 3 DB3ECA42 2012-08-07 Wido den Hollander -sub 4096R/50E9D98F 2012-08-07 -sig DB3ECA42 2012-08-07 Wido den Hollander - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.11 (GNU/Linux) - -mQINBFAg4ogBEADPUAOmj/KdLjp5Wz8oW5+fnx3gnhVABh1Xg5Uf36tDCLogSMya -Y9S8lZb8PgvtkK6fOqUCoViUvXAWM5/k7JbIv70cWGc+M4XgZTnI6GWlz08EkzNT -/DX4Y+OAks602KYLXVepI4SdpCKaZJK14Az48cfzFEZDmzMuNtS/sQhXQZSXe7pu -7pBPpQ2GP1aYqGRBYTkMD9fjQAM2U3qJ/5K0AzeIciOI6QxD+h2fIBMnu+XV0g0C -2SG6UVy1RBVYzylWZ1p63brFtskjDnPoXrjXOx3iUxV/pEH7nKziHDolMShp+bni -Cnw5QcrqkBQls84d+cdteJ40ZzoyiWg0isIsxLMA2L71WkziJZkigqqQ8O/HI4Dl -3/mz1I5R2hphorkBPVc5ZAirhB38FqLgW1eH0rd/TJR428APYkbh6QnWRCLfGl7C -UsdYmpUaNjFZFrHCBoyA9p8pNzsJuZBVIBa+xheJk71HT5zeAk+uDPuNJH0Tc5qc -E7XRxaaj0QQxBlmkgdW0kMIO93jjrCTuzmgJMAEym1KSPiQTJmr0fUuxLEL7gTy3 -a0I9sEnhbyn+yl6KZp0Ey/pZ8UOLD4TBwx1r1kXWXD7evTs0CCoPeyP0GRyjlhqH -WLlhEH2MtSWn+0SQIHiGh8XNh7ToySCquk1jslV89aX/sezRLJuly0k2hwARAQAB -tCNXaWRvIGRlbiBIb2xsYW5kZXIgPHdpZG9Ad2lkb2RoLm5sPokCPgQTAQIAKAIb -AwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AFAlAg6F4FCQlmrtgACgkQAZtYLds+ -ykLICxAAlSVW5i3yIuBhnjIpCPPkOtABJEz2zImyl3VNJ/JuRT1nOmcvsu39MALj -m93qsVvZOulyiYHMKg61QWHRXHimqdJe7wUH64Fm/Gf85jqzf6Db0HFCyR4ADHKH -8XFNNiGctutPAwDeUaUGFYE3RtDEU105z/SovfzFrLOSLQ9o1+48T0Dm5iCezHr1 -3AF7HJpbQ9D0ng5CTEK2YhYHAS6rPf48MJ949WQoSrLt1X3WEu62Bgcuwa8Ph9AM -7Y4K+uVNWNft+xK+SJml0pkYBTwc+tIXhT6tirnFa731g5wKDLIpTc5OWYvirO3w -EO+G0kuZsDRyQTqCo1DBax30xVazNKQ1/OTDZpVAkkejCqrh7UY4tc2C2FL+9V0b -I6oeysYZpO23CC92Qe5NESavWOUGl9v3rzRCON2rkkDEi8jFCKGsJIoL8S6LjeDn -b0JASbXhYhZMmZY1QwSKvlbnhQkxPb0Ww3jALQV31AWTwN9ACS0/gwh1+gCE+zvm -paoD3yGyZZbTOUx4jQq0diMpDRsxboqsKzPpUMCL7w1YNQpPH4KHNiFGJzLsL1LF -+kwXVLq0hJjblKr0H5hfbBLODG1ZgOC5GkkcMcM73PDq4zOKgGW8O+yrkPc2Rx0/ -ZAP117yP5RlgL2LLA1H0EgS2TKZanM9MxwBhS+YAV/e+hWEPpCa5Ag0EUCDiiAEQ -AKnpED7QljHFLNrzftOF67EOcCeu/tew+gaok135taDgsKW7FMfjF+uQje0nloM8 -482TSFRJAp74fFiKjNUPXcGNaUU2XwDiSDsnuzqRStzJ58jxVcGbnV8nHCw4X+0w -BQVo+PCaj5f8HAFdiZ4EHRC/P3BuH9QLNEY9zziPw0LG5vn+0Lr0DTsdWQl2vWWc -SIUNd+QnQ0icnSY3FLdxyscqHkUCOtu7NxI5WzdjtaFvgxZbPYJQHfm7B3OAJmg7 -/Gn4YSbN2p78sYLKfKu7YoYG1+wP8cJMHgYM03b7WQgHqII/v6RCNRDtT1k1Hfw2 -Dxid3IWkd8JUlwJFvnAL2sBgHqAt4xtooRkHcAnbcH9cO88ULgqWIfIEYosd/3/v -qvWTKZb/9B0p61gq6yOGOs1swAEWDdkkAAZJK6O0O5x/7J005uX3W9H8J2DqJQYK -jvp8Fph1sv0HVb+AfxhEtS/wfw34iaebNANMy5e369kt9oBXISubksQwgKFqPcsE -xteeyEhZ3qZUBmcTjl9PjrgFn2fMXoMRF9DB19dDFXISvg3tyJ+FCe+/Kppn6u+a -X7e0AltGLMBmfs1rcTPkmAFJglL5zi994iIXDv7/KWxX9QQC5BRICm5pSL8inWoO -6mU0cD5F9FrmkrfEVV+Ajmy/cH9UIiOJijdK7e/ImxShABEBAAGJAh8EGAECAAkF -AlAg4ogCGwwACgkQAZtYLds+ykI73Q//fYNKhEAvrFyF2d8OwVqHhzifIqsRycOg -D0Ib3tOkeNgwZYI+x6QIiYFHQalcMUFhwUea7RKYkW17Rhpj6W5hj7ie5x6cvtzI -5CeArcvoBj0KIRGUvsRl9XplXdaBhmBGibvEQBac2oCIVCBtTbsjkQlXPs+Q2SaJ -kyL8rbdmt06Tsc3iwN+ZjPGIluifaacvurJH8tntCWdhnFKwSwfsa3ZfJwuf3O2Q -J1q7JwYOwQbTR3K5CAyZ0HVYksiIoUqy6IzYvNmilAx2hkVCm2HjWXEvTwjSd709 -yXBbm7X9JkB0RYSzpHEBqL1aB7GMe/pCeGLgcGRoA0ZyYXMoM7/gnE/ZCDG2fWGm -JZZ0LJ8QVlZq4nG4lkco7mZqDOycyA68nfbpGaSXhJ7iKbdk4DT0OMr//RlHsiif -AZFM2ppJ5cOmJ9USMkgyHziS6zexM0bYzzPJsLgoq2rjelmzE0pu7NoIcOu3KlkS -HCLDLqIZEYg7EySBVgqJ67FlnpAMY1IaUJN4rYQ4LQEq0uUfmmhZnlp4qQQnZjFR -MrkLZNjHiv8v6JGklVurAQstvZBQXrUUH+/JhJM0U6gsPzgsn4DlpxFyr3nM1aaJ -uHR4OoUFg2G1Hbm7k4eb1SFT1jPEe3is4Oc8t1ORRfSBIH0FfLF1ylLFpSma5q+3 -HpWraBFdP78= -=I9dG ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/2908DED2 2012-06-29 -uid John Kinsella -sig 3 2908DED2 2012-08-07 John Kinsella -sub 4096R/26F845B7 2012-06-29 -sig 2908DED2 2012-08-07 John Kinsella - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG/MacGPG2 v2.0.17 (Darwin) -Comment: GPGTools - http://gpgtools.org - -mQINBE/uBAgBEAC9f6Cjh4vS1eY8g5O9rX1P6qhUWfoh8e1stAuKWVUsNfR3C4w3 -BZef4dDTMMHaXfJnZ7oFsMUghjzKI1/Fy2rhJ99ZEf8NgxYyy5nR4TUfHdlXAat0 -tF3amfGzruJoVorybFEiGVIsYcuDPVxC7jVXGgkaMZ9PD1pyD4cSGYafObDuVr5z -MM0P6X1C4dT/pShiKOBhuX4XJdGk910uEtniWHWaIHIN3KBCQL7xgw0GxRPAmoTY -GPmt1Ee2N8E+o2UzgvqAc+iQH6z1iqHakCCkH/707XscpUrr00bPHk92lgQrzGOw -kmXUdTipAM9wqzPZ6EmtT3WV9uT8HV608VTEvZSHuuYpZdFW4IwWXziZUqx6z8EX -miKlFChHIkeARZgmxdIB3m4r05yU2MG/A4VaixcNGOXAjSaV+EyWXqecMlGJXLbF -rnaGfRshOo3mLG2UE/LI/y/4S0RYVlky0LzWZqihcfL/sT2Tc4OLAN8wKOXhlwd2 -s/68wmzOq+67KT84YTxsixUbS2yBg8nfS6SMz5irWvlELQyeiPkDttuzDxSC8Koz -jR28az1VVkqT88VrRtb3oVyV2T7Za/yYHO/IsrjimgvIA1BKnq6E+0uXZbI5HKkA -/FGTP9N9J3YwW4eFBilXIt47OIkuBgHUwZsBMpLZfWNktLgB2nAIcz2VFQARAQAB -tCBKb2huIEtpbnNlbGxhIDxqbGtAc3RyYXRvc2VjLmNvPokCNwQTAQIAIQIbAwIe -AQIXgAULCQgHAwUVCgkICwUWAgMBAAUCUCCB1QAKCRDqJvTdKQje0hoMD/9Ssbjf -XF3V6of8563Ro961TrU38E7CLjrA8mrwVHllz9ikoXDhXgMfFg7WrtzEs/EHw7xW -iYwJxS2R1mKyu4zP4Qx38TnH++DsLx6n8m5L2uhaMlZCdqaaXm0nWgu1L4ZQv6OR -6BmVnEged98rsIuOfdXqxbe+vxx7kmXxQnBnRIGOfCKce5kqr/uLKFCBTQdKo0Va -WxXwa/2b0MpN7XEollY1O20185wQXxpe7/6k55wi6ZDUiIw7pollMnSNAj/Ic4Cr -CGj5MGzc4uLnRpIjjbfUif0CRfQ8x3s++IR4KDGZbLfLkUAcHrKGV720TEmf3Ym5 -EvSg20M6mbyOGNUlXdZ69aQAkhCTVwbYNC0E83KsV0K48o538SyhnYzQvSnyqHNv -AMYwRXu+9m3lRmO9FqZ69Qm+fap+QUWlEmYZFNzmhH8F5WWC6EqN0e6JDt4RwDlc -taHF9mSpQYLipsD3yfr5tzd4J9AIWItfEcuaKG2r5kVTyUZMp1yu2+ByvnfGna2R -dHJLwCKGvowlTfrcQ/+ic56YEQrIe4Sy7zbsFbKlOzVNoQyk9814kF4My7nzDPwg -M9qwfcW84kQZzh47uYFVz6BDNcDcIUlo6ODGMHs2MM6Oqxo+NfruXwfKZeHIWsvw -CDuqPNRN5oIUK6txqrYr7nj0GUj04W5LltztvbkCDQRP7gQIARAAykm2inv3OUIX -/3KnGeQYluoYa8cWv4lBV/F1x19qcCgpn2GtZFrwm8/1lLUIRHBsxardE36sMCme -bGilXSyH/Him8gHTn3t/i4jy0EWNcBU5B6C0hfG0DZBGvYjxWA22wRxr0x5CReoa -nZYq3lfLSzHjRbbAlZo9hYp2PpOrsPGGYSMWasANIODQ5Ium97TEWm8NyVBX8tdO -jYz3SCR27I1UTPII7iOhrDuWVqV2orBgDcOlMrIdHN1vg5YKWTU4VqTn0gr2Py02 -iB+bW2eENnG8BYNeL+CBrG7guwsvFvNWlN3KbiSdN360qzYmLly5jmIH6baLIGS/ -nCgKPo91r5YY59fM9OxiT8hi/5nidfyy/HrqAp5IO5E9WdjTrBrMpDAm/oWfy/He -8gHjbcuX2bUp0UFgA4bo7ElTEN7clCU6AjX+g+mvGAvzJZOZ/t6jf8bfsd8G1FgU -ND47WPCCKfJyrnbaqAh4chnzsuh2L5Ujrk8l4Y8X50zstybwpPqk60Rednw0N2kh -tcLnMkvNqy6Vmvi0uBkxVonVJi3S/FOc+DJreQwqkc/+vrY+zW0+F3qrtTeP+uWQ -IyeW0wMuZPqXrnfRkoui5BVDzI/CEoWyyTKa2j6CtDGWnUqtIig2BHk0Ux80L0Gy -fBqqeuE5qVnjmPHBagOUsX1qwJ45/+8AEQEAAYkCHwQYAQIACQIbDAUCUCCELgAK -CRDqJvTdKQje0rfmEACqzADegNqY3ds2yyWz2SO/3Ihwsq8UX7n2WHPJdVhcAyzw -Xn463n+5iXYdIGhSeNd14hIHVyab3nZVY2C4Cd1IAK5QUSVkK8tcwKlPM8gHUVSu -ZUx1FBjjDBz5/EThV/f7N9bBrKtJN0DkzzqnGoNbpSsoP+CTk7kxeRmhXlK8lrr/ -ekVt6gtqi2y+sqwWfJXN955oy5aT2c+bQFsBOoKMt/bpLEDD7giVXgKfKJ6+X/Qe -3jW36aPxtW26TTXUBZr6FmhBwmXyCt6tv+/5VeP5R68CK8q10EYDGgjcWmsa8wrr -Xe2ILFA3oUMytXGp3+WbT1MUXDaHUhE+PCugGwyMPw+pXf+ADZMIjESa2lk+mmE4 -Worss4fFHIpXICMkJKRo7P9NAPUMC6u34EMuNEv4XfBd/zalTpAq/vvy6cMPaeAa -Iik1ML6E8YZ3TeKbQoZ++ZQT/MEwSOjrsx61a4yf/bzLvcqppKBxVdtCBsePPgHA -bOXIAKv3iqD9Cq5GxLpSAH9E+KlQpJmVDsR1b15G6jceGyZ20NP2Mf6O8pqY1qfC -p7S7eSiSwAZT56oHx9ULzBAKYvwyyoIVOnc0ddwhLeGq2flP7xSo54oDw4KRlFuu -rHMalutU5/Bc0tFZtdm6DnSnwtg3fBnwgFBeINJCc31xuX474+071mfaQUVO7g== -=BzOC ------END PGP PUBLIC KEY BLOCK----- -pub 4096R/6FE50F1C 2012-05-11 [expires: 2017-05-10] -uid David Nalley (Code signing key) -sig 3 6FE50F1C 2012-05-11 David Nalley (Code signing key) -sig F2EFD0F0 2012-05-21 Christopher David Schultz (Christopher David Schultz) -sig A67F707E 2012-05-21 Christopher Schultz -sig 4C75EA05 2012-05-31 Kevin A. McGrail (CODE SIGNING KEY) -sig E70D2357 2012-08-09 David Nalley -sub 4096R/1E5F6D9D 2012-05-11 [expires: 2017-05-10] -sig 6FE50F1C 2012-05-11 David Nalley (Code signing key) - ------BEGIN PGP PUBLIC KEY BLOCK----- -Version: GnuPG v1.4.12 (GNU/Linux) - -mQINBE+tml4BEADjjxemcIdmFj4CuJYCpHBldoot3oF0Dqvez8ok7KnmNc/jrbgH -rZ6/DYq8SzebTbQSel4bCkLLnaI4Yu3C4Rd2uYPF6EHjs+kM4etKJLOiwfv5/EA9 -l0TYwNldkZaE7Y/B+XDrzQIxCWiWeH8O01EKJxZhjtcmeZYS3n1/gozQmDxNcbaW -QJJn6Vktqek6n30fPGsQl7tZyfnoSTvjDblze/dFSmyJaCeGDfljlwhXfNBFhJct -LxjmbiD21kRZvs9dWJZRFDQhw6g2HZIQ8MXAC6PUhoJgvqeBDUGUr6B7lb1IfTrl -CKBQLKAURZXKmLlRzh3IMTEyKpmV2D80erRf39S3CiRNEYlnn1fHovmnkiV9QLvG -rgjwDcvuw3Y2lBNaQRuSLm55sBmPBVDSU3aABbZfupOntlnV/oIyl32fiF7MAHT9 -8mV4c58urjbJKkq9R/0U/pZxqWOQfnnt/t66hdOe1p5O29c7nW5V0rlNDFAm2GXL -OKhvS/crBfz4gpI7U7KAq5aMA1F0ZgGJwGVs7Lv6uvl9O/4M7/3g5b390yuRzJzw -ZXF41wJC8Zwlw+KJcrcTkzbUjpGoNoblfAOV/YV3WNnJGOs3hL12vktsgADcjl2R -T6x7QAayZQyfaSD1UwXSHBHi7Lh6ABj6zQnlcan/8/j0mEVMe+q/5CkGPQARAQAB -tDNEYXZpZCBOYWxsZXkgKENvZGUgc2lnbmluZyBrZXkpIDxrZTRxcXFAYXBhY2hl -Lm9yZz6JAj4EEwECACgFAk+tml4CGwMFCQlmAYAGCwkIBwMCBhUIAgkKCwQWAgMB -Ah4BAheAAAoJEExw8Ghv5Q8c2kEP/RhSY6cuypHNTFsVWYm6eaxHR5z1duPvwAhf -7LG4QoqaEJwGJSlrDScQA/sAJZli0eswsIDho8e9iywrREWCrsUKnNcZNaw1y36q -vCTwuAvtfW1H6/fNFwErzYHSIOUxYwRoylxVhYSW5renheeHmxsLtKqLavo+MDV+ -Shr/CGcnVypbW8MrcL0q6OWb+eCJUsB0JIotXRitTGrCV6ulyOWSnq0CXT3EkrT4 -rkXf9dINoAKzqoF5UE+9oGFJxQFFEY3ppgh9p1qaDHTzoKwrVxp+ssBNm7N1CAff -JIb4b2MoWeNuK6lZPR24dGhsxBIZPn9Nlxzczuvbb+lUDvvA8gedYcSTOe5x/7k8 -J3Niu7S50HP7Y2II2RS5zqTMbJJRVu7nZKQYXjM8pItuTiZqaEwl1QyIfuSfXTbf -i35IWO+ZHpMYqUGeAlugIquFRmF50YBMnqm104Gft1DUm92eb5si3gXRNxrH2t0Z -+yHb1iD2873WrhMatgSmpcRYZyWsYTUEUhGT2P2+oo3c7YjfqyJ1rx6ilIhvRLao -ooJ83iobbaDGy0C+jQMvIh9jgJ8Ca9Fy6m3jPjxDke9DlSh4P4o0yct8JGHF334Y -6AMk84+FvFh5AiZHqnP/sXdp8NW59sNJPUWSunjrQ1iRSJv0goMso6sjks6w1Hfs -JxpmWXjJiEYEEBEIAAYFAk+6TxgACgkQ9CaO5/Lv0PAGTQCgjR9jnKgClMp5lhY+ -vmeOWrAmTlEAn3aJ/RWKj9OfO98ERRJ/HGcKL010iQIcBBABCAAGBQJPuk86AAoJ -EPOtXJSmf3B+p3MP+wSU/CeCdXuvKTEBj6JtB+GAi7zSFNrBkuu5s7wCnEhr1BQ8 -u6LcP9beLFZstMbouyz6EZU0CdSkxURXZtsVJrDR1hJYuZ8uPSA+gldCmvoU6ECj -xIUIsq2W2fTG5UTSwQ3JXa+mZS+bRByFeCBCSrMxgqlRooRJ9PDOfJyZ6N/RUTpZ -SzhhgSKFs/Uv8xu/as4b2Ec32jpOmZcF5RiKMkp3zYenW01l/E1KM1PRfKTZRv4j -tTqqJELVqoBRM1Z/H/in7VIdSBDoI4K3W9BbDyvaUh5GgzLgwRkc94PTJ2mMEgA/ -EBsKi2VDWU4AZ/CLjlqunqqLfEzdekHF9HC4iZsqjuodWOYzc/ECLE07w1/WAxOG -wR0Kevyf+GdQ6Nq4DfhwGRzNwhsGJBoqLu785kUZ9w9wbv6aGq9/AYtGVAt7g3IA -S/5H6QQZLic3MswAZHDg1dtBgO6Q32UTl0AcZ7qRBRfnhrhqC71rhMAhlGdzld82 -MzFPQbCqAM8dUqIY67Hoyn0c0P+kw73QGcG/MDyIvYrBuu7fmCEq8V4fHaY38awJ -ydlIyhZhrrpW+o10BlbEuoBgDgFkDeynK0lUbusqrhCE/oAUHXfqXfzZ0Chx5EKK -jAcM1Q2/t3WnIPkXn3CAJRTnz7WJ0dN/OETJEvlDAhulUVzRbGCPXJBaxBKMiQIc -BBABAgAGBQJPx/i4AAoJECFN/YxMdeoFCywP/3AmFE+8tDj0VGrosKO7oRXCP6Dk -krfhezVQjDHAuvTMCJpYc71uvBOLOf6jSrSWcmJJXz89LBWRjLl5QpuHpYOLgn7j -90NXmW5tJY3lladQovMhmbnJehgK6POj8glq8jn8fAeKMM3npHxNcvoQ2ivXB0IL -1B0foM/RdyBgFjjFiISZwkDQRXcfaK9lQgQlIWu5Wts+YCMTR5aBrvVYchZAdKaB -q/gtmFjeCGy/d8Pch/hgevQLngap3X4pkldpHy1NtRNg/MqzTP7FjiinNJYUBga8 -rTSeBLhk+X8bfL6FttiruVNTr8oX5RBNJlceV4l06vvvczJtTH/ROj8Vr/Lw4xTB -RKCWmAEzEYwITjpVDK/4U6NeZbIp1Srbi8IHPKHq9IYWiSZLP/fbtBSK418AiECw -A88CS3MA64f3X5i8AkDHV9fMccftTSzt4ovkTm3wrbDiqjfNzi6tfl9wt1Mc1fYh -krIO+OMZoQrI3+7kw52HHoXWs2w28CGYlH16foo/PdylSVTf09MV1uLmYOS/6A8l -1AYAxI6DDORz9qMIvj+jlHeJKDsUrIs2n2OEWnbe1jCJFsVlEHUWLqqBbfdIne8P -T9NX+mJzWhrxfm8XVHQpK8KxITej8Uuigj8W3Od1J/OJ3FfQ2Xzm8pOn0764cSKB -Deu05Hw2S4WgZ82DiEYEEBECAAYFAlAjB7oACgkQkZOYj+cNI1eTIgCfSPvYLhnh -CQXpYDeWn5QsUKO44eEAni3xVhrnCOrpBGWHu5QUX9cJx0yduQINBE+tml4BEADV -omhZSUujC2B/e6ghmTM7p9W4xVkP/OQVWzrNe7JaCkw1KOHeU5pWyQsxYV20jA6g -LZLIDbH3Wf2wWpyOMrvRR8T2ChxLe3IuFY3qMTGeldU5cYDrBRgQ8XDeVGp5qHee -2cbqWTxmSCgf+ux8vdAfw+d1LtyFQT08E7Q3fLLlZ5t1MxfwCl58SqwjyF7IwMvh -vLqDkqS0lcAj7uK8CspUQur7xnfZhB77mjAayPZyZxkZXcJ6ujJzwH1VRoslzQw0 -RjSEOCewQ082PdEcZ/TxRMKKbheKsIRlMmJlP5bQd+bICivGR6JDOyRXNhx8BPhX -jeSiaYjdgLx+LqVzRFkMhQzzD4TdB6EuBgAUo+Qz8hMvXqw64NH2kXA9OsEq2yQn -+RLRTX3Eo9KwNMIwlmqRip+l6MUH+7zHILFohkBDgFAKyL6ExMbNOKts/kmsVQlk -5pznm3+ofZ1zDGeF5072JMLPJQn0cyg3UfGR+raSnn1+Zal6yGwqgZkfm5aGvEzG -jC2hj+Jfl1oGy5cnCk5Jia1wboG3wkxwNRN8sNLjSmv7sdJ87LyHYollvNGUayzt -PwdAlDHQqPEurzO0uy2WSjdEc6ZdBNYNJzDBJhHIy4kET1TxPWpfaHt35slT6tTK -7hvQ7VC1VwwSnqlDcw5VJTjIb9ue5KM5c4XhUgPXsQARAQABiQIlBBgBAgAPBQJP -rZpeAhsMBQkJZgGAAAoJEExw8Ghv5Q8cIAMP/jzbOVGNz/Uuzf/GKCQ4CudS5Ada -RjNHI4ATAcdGqXCKMzPGVVFDdxJF6yGPyq3wQD0FIwmpJGppjNuHk5eJ8UafqAHe -oynr7izB80o2CdYVMoMVa9Um0lALdCigAJQbu6sjQm5mN3qDVBpEcRzffchb/de8 -GcbH2I/iEZ7L+Og73bw3yFXKwGS/vZ/8ZLEh20cqHzwB/4JjnnCLASgpPsaCGrXF -y0NW+Yo0HrN5deEMexYADDGPE2MQAWC5QjEvxm24yiO2q//xAtUUNVrKDXXbnwaN -BvlNzqNc1iCKcXghV8euwNyTF++UwDCT1x5bcAntl3wYHSHKasae3omvmja+Wdfs -iFZHQtzZXgFjPm0C1Y5v1uG+YmzLa0gDX3Lol0n+ANzZNKFSw/zXacyl9wavnUjh -ITiT9WbmXiEc575jUIlkqxP0Sqg8Afpk/tB5PGyan8GbsTVX7EE/l6724ZLyvH4/ -Zuvhhqa4HA6hYwiNuXxoUBmabiMULIBZYdsn9znjRKeh6oeoqRa2C2El46o05sy+ -woXtbjtbPIeSV1o7KUax0tkg2VqeKBW/qXBkyzLbRSC+vsYVpnO5pPqjaBPoqgIw -vWtDEroKvHDVC+T76U+BlKTooOU0sdWGS8x25HbFVUaxOOFEybkZiFZ2cOlADgcj -R5fTvoVeebaUFoTe -=d4EI ------END PGP PUBLIC KEY BLOCK----- diff --git a/LICENSE b/LICENSE index d43769fbf4b..afb662a77e2 100644 --- a/LICENSE +++ b/LICENSE @@ -309,2049 +309,8 @@ Within the deps directory XenServerJava http://community.citrix.com/cdn/xs/sdks/ -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 - individual or company may do whatever they wish with source code distributed - with ANTLR or the code generated by ANTLR, including the incorporation of ANTLR, - or its output, into commerical software. We encourage users to develop software - with ANTLR. However, we do ask that credit is given to us for developing ANTLR. - By "credit", we mean that if you use ANTLR or incorporate any source code into - one of your programs (commercial product, research project, or otherwise) that - you acknowledge this fact somewhere in the documentation, research report, - etc... If you like ANTLR and have developed a nice tool with the output, please - mention that you developed it using ANTLR. In addition, we ask that the headers - 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 - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2004-2008 The Apache Software Foundation - from The Apache Software Foundation http://www.apache.org/ - XmlSchema-1.4.3.jar - - licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) - Copyright (c) 2004-2012 The Apache Software Foundation - from The Apache Software Foundation http://www.apache.org/ - apache-log4j-extras-1.0.jar http://logging.apache.org/log4j/companions/extras/ - axiom-api-1.2.8.jar http://ws.apache.org/axiom/source-repository.html - axiom-impl-1.2.8.jar http://ws.apache.org/axiom/source-repository.html - axis2-1.5.1.jar http://axis.apache.org/axis/ - axis2-adb-1.5.1.jar http://axis.apache.org/axis/ - axis2-ant-plugin-1.5.1.jar http://axis.apache.org/axis/ - axis2-jaxbri-1.5.1.jar http://axis.apache.org/axis/ - axis2-jaxws-1.5.1.jar http://axis.apache.org/axis/ - axis2-jibx-1.5.1.jar http://axis.apache.org/axis/ - axis2-json-1.5.1.jar http://axis.apache.org/axis/ - axis2-kernel-1.5.1.jar http://axis.apache.org/axis/ - axis2-transport-http-1.5.1.jar http://axis.apache.org/axis/ - axis2-transport-local-1.5.1.jar http://axis.apache.org/axis/ - axis2-webapp-1.5.1.war http://axis.apache.org/axis/ - commons-codec-1.4.jar http://commons.apache.org/codec/ - commons-collections-3.1.jar http://commons.apache.org/collections/ - commons-fileupload-1.2.jar http://commons.apache.org/fileupload/ - commons-httpclient-3.1.jar http://hc.apache.org/httpclient-3.x/ - commons-io-1.4.jar http://commons.apache.org/io/ - commons-logging-1.1.1.jar http://commons.apache.org/logging/ - httpcore-4.0.jar http://hc.apache.org/httpcomponents-core-ga/ - log4j-1.2.15.jar http://logging.apache.org/log4j/ - neethi-2.0.4.jar http://svn.apache.org/viewvc/webservices/commons/tags/neethi/2.0.4/ - rampart-lib http://axis.apache.org/axis2/java/rampart/download/1.5/download.cgi - woden-api-1.0M8.jar http://svn.apache.org/viewvc/webservices/woden/tags/1.0M8_20080423/ - woden-impl-dom-1.0M8.jar http://svn.apache.org/viewvc/webservices/woden/tags/1.0M8_20080423/ - xercesImpl.jar http://xerces.apache.org/xerces2-j/source-repository.html - xml-apis.jar http://repo1.maven.org/maven2/xml-apis/xml-apis/1.3.04/xml-apis-1.3.04-sources.jar - - 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-gson.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 Json.simple Project http://code.google.com/p/json-simple/ - json_simple-1.1.jar http://code.google.com/p/json-simple/source/checkout - - 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/ - jsch-0.1.42.jar http://www.jcraft.com/jsch/ - - 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 - jaxb-api-2.1.jar http://repo1.maven.org/maven2/javax/xml/bind/jaxb-api/2.1/jaxb-api-2.1-sources.jar - jaxb-impl-2.1.7.jar http://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-impl/2.1.7/jaxb-impl-2.1.7-sources.jar - jaxb-xjc-2.1.7.jar http://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-xjc/2.1.7/jaxb-xjc-2.1.7-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/ - jta-1.1.jar http://repo1.maven.org/maven2/javax/transaction/jta/1.1/jta-1.1-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) 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 - mail-1.4.jar http://kenai.com/projects/javamail - - 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/ - junit-4.8.1.jar http://kentbeck.github.com/junit/ - - licensed under the Dom4J License http://dom4j.cvs.sourceforge.net/viewvc/dom4j/dom4j/LICENSE.txt (as follows) - - - Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. - - Redistribution and use of this software and associated documentation - ("Software"), with or without modification, are permitted provided - that the following conditions are met: - - 1. Redistributions of source code must retain copyright - statements and notices. Redistributions must also contain a - copy of this document. - - 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 name "DOM4J" must not be used to endorse or promote - products derived from this Software without prior written - permission of MetaStuff, Ltd. For written permission, - please contact dom4j-info@metastuff.com. - - 4. Products derived from this Software may not be called "DOM4J" - nor may "DOM4J" appear in their names without prior written - permission of MetaStuff, Ltd. DOM4J is a registered - trademark of MetaStuff, Ltd. - - 5. Due credit should be given to the DOM4J Project - - http://www.dom4j.org - - THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS - ``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 - METASTUFF, LTD. 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. - - from DOM4J Project http://dom4j.sourceforge.net/ - dom4j-1.6.1.jar http://dom4j.sourceforge.net/source-repository.html - - licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) - - Copyright (c) 2004-2011 QOS.ch - - 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 QOS.ch http://www.qos.ch/ - slf4j-api-1.5.11.jar https://github.com/qos-ch/slf4j - slf4j-jdk14-1.5.11.jar https://github.com/qos-ch/slf4j - - licensed under the Mozilla Public License, Version 1.0 http://www.mozilla.org/MPL/1.1/ (as follows) - - - MOZILLA PUBLIC LICENSE - Version 1.1 - - --------------- - - 1. Definitions. - - 1.0.1. "Commercial Use" means distribution or otherwise making the - Covered Code available to a third party. - - 1.1. "Contributor" means each entity that creates or contributes to - the creation of Modifications. - - 1.2. "Contributor Version" means the combination of the Original - Code, prior Modifications used by a Contributor, and the Modifications - made by that particular Contributor. - - 1.3. "Covered Code" means the Original Code or Modifications or the - combination of the Original Code and Modifications, in each case - including portions thereof. - - 1.4. "Electronic Distribution Mechanism" means a mechanism generally - accepted in the software development community for the electronic - transfer of data. - - 1.5. "Executable" means Covered Code in any form other than Source - Code. - - 1.6. "Initial Developer" means the individual or entity identified - as the Initial Developer in the Source Code notice required by Exhibit - A. - - 1.7. "Larger Work" means a work which combines Covered Code or - portions thereof with code not governed by the terms of this License. - - 1.8. "License" means this document. - - 1.8.1. "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 any addition to or deletion from the - substance or structure of either the Original Code or any previous - Modifications. When Covered Code is released as a series of files, a - Modification is: - A. Any addition to or deletion from the contents of a file - containing Original Code or previous Modifications. - - B. Any new file that contains any part of the Original Code or - previous Modifications. - - 1.10. "Original Code" means Source Code of computer software code - which is described in the Source Code notice required by Exhibit A as - Original Code, and which, at the time of its release under this - License is not already Covered Code governed by this License. - - 1.10.1. "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.11. "Source Code" means the preferred form of the Covered Code for - making modifications to it, including all modules it contains, plus - any associated interface definition files, scripts used to control - compilation and installation of an Executable, or source code - differential comparisons against either the Original Code or another - well known, available Covered Code of the Contributor's choice. The - Source Code can be in a compressed or archival form, provided the - appropriate decompression or de-archiving software is widely available - for no charge. - - 1.12. "You" (or "Your") means an individual or a legal entity - exercising rights under, and complying with all of the terms of, this - License or a future version of this License issued under Section 6.1. - 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. Source Code License. - - 2.1. The Initial Developer Grant. - The Initial Developer hereby grants You a world-wide, royalty-free, - non-exclusive license, subject to third party intellectual property - claims: - (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 - Code (or portions thereof) with or without Modifications, and/or - as part of a Larger Work; and - - (b) under Patents Claims infringed by the making, using or - selling of Original Code, to make, have made, use, practice, - sell, and offer for sale, and/or otherwise dispose of the - Original Code (or portions thereof). - - (c) the licenses granted in this Section 2.1(a) and (b) are - effective on the date Initial Developer first distributes - Original Code 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 Code; 2) - separate from the Original Code; or 3) for infringements caused - by: i) the modification of the Original Code or ii) the - combination of the Original Code with other software or devices. - - 2.2. Contributor Grant. - 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 Code - 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 makes Commercial Use of - the Covered Code. - - (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) separate from the Contributor Version; - 3) 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 4) under Patent Claims - infringed by Covered Code in the absence of Modifications made by - that Contributor. - - 3. Distribution Obligations. - - 3.1. Application of License. - The Modifications which You create or to which You contribute are - governed by the terms of this License, including without limitation - Section 2.2. The Source Code version of Covered Code may be - distributed only under the terms of this License or a future version - of this License released under Section 6.1, and You must include a - copy of this License with every copy of the Source Code You - distribute. You may not offer or impose any terms on any Source Code - version that alters or restricts the applicable version of this - License or the recipients' rights hereunder. However, You may include - an additional document offering the additional rights described in - Section 3.5. - - 3.2. Availability of Source Code. - Any Modification which You create or to which You contribute must be - made available in Source Code form under the terms of this License - either on the same media as an Executable version or via an accepted - Electronic Distribution Mechanism to anyone to whom you made an - Executable version available; and if made available via Electronic - Distribution Mechanism, must remain available for at least twelve (12) - months after the date it initially became available, or at least six - (6) months after a subsequent version of that particular Modification - has been made available to such recipients. You are responsible for - ensuring that the Source Code version remains available even if the - Electronic Distribution Mechanism is maintained by a third party. - - 3.3. Description of Modifications. - You must cause all Covered Code to which You contribute to contain a - file documenting the changes You made to create that Covered Code and - the date of any change. You must include a prominent statement that - the Modification is derived, directly or indirectly, from Original - Code provided by the Initial Developer and including the name of the - Initial Developer in (a) the Source Code, and (b) in any notice in an - Executable version or related documentation in which You describe the - origin or ownership of the Covered Code. - - 3.4. Intellectual Property Matters - (a) Third Party Claims. - If Contributor has knowledge that a license under a third party's - intellectual property rights is required to exercise the rights - granted by such Contributor under Sections 2.1 or 2.2, - Contributor must include a text file with the Source Code - distribution titled "LEGAL" which describes the claim and the - party making the claim in sufficient detail that a recipient will - know whom to contact. If Contributor obtains such knowledge after - the Modification is made available as described in Section 3.2, - Contributor shall promptly modify the LEGAL file in all copies - Contributor makes available thereafter and shall take other steps - (such as notifying appropriate mailing lists or newsgroups) - reasonably calculated to inform those who received the Covered - Code that new knowledge has been obtained. - - (b) Contributor APIs. - If Contributor's Modifications include an application programming - interface and Contributor has knowledge of patent licenses which - are reasonably necessary to implement that API, Contributor must - also include this information in the LEGAL file. - - (c) Representations. - Contributor represents that, except as disclosed pursuant to - Section 3.4(a) above, Contributor believes that Contributor's - Modifications are Contributor's original creation(s) and/or - Contributor has sufficient rights to grant the rights conveyed by - this License. - - 3.5. Required Notices. - You must duplicate the notice in Exhibit A in each file of the Source - Code. If it is not possible to put such notice in a particular Source - Code file due to its structure, then You must include such notice in a - location (such as a relevant directory) where a user would be likely - to look for such a notice. If You created one or more Modification(s) - You may add your name as a Contributor to the notice described in - Exhibit A. You must also duplicate this License in any documentation - for the Source Code where You describe recipients' rights or ownership - rights relating to Covered Code. You may choose to offer, and to - charge a fee for, warranty, support, indemnity or liability - obligations to one or more recipients of Covered Code. 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 than - 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.6. Distribution of Executable Versions. - You may distribute Covered Code in Executable form only if the - requirements of Section 3.1-3.5 have been met for that Covered Code, - and if You include a notice stating that the Source Code version of - the Covered Code is available under the terms of this License, - including a description of how and where You have fulfilled the - obligations of Section 3.2. The notice must be conspicuously included - in any notice in an Executable version, related documentation or - collateral in which You describe recipients' rights relating to the - Covered Code. You may distribute the Executable version of Covered - Code or ownership rights under 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 version does not attempt to limit or alter the recipient's - rights in the Source Code version from the rights set forth in this - License. If You distribute the Executable version 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 any 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.7. Larger Works. - You may create a Larger Work by combining Covered Code 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 Code. - - 4. Inability to Comply Due to Statute or Regulation. - - If it is impossible for You to comply with any of the terms of this - License with respect to some or all of the Covered Code due to - statute, judicial order, or regulation then You must: (a) comply with - the terms of this License to the maximum extent possible; and (b) - describe the limitations and the code they affect. Such description - must be included in the LEGAL file described in Section 3.4 and must - be included with all distributions of the Source Code. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - - 5. Application of this License. - - This License applies to code to which the Initial Developer has - attached the notice in Exhibit A and to related Covered Code. - - 6. Versions of the License. - - 6.1. New Versions. - Netscape Communications Corporation ("Netscape") may publish revised - and/or new versions of the License from time to time. Each version - will be given a distinguishing version number. - - 6.2. Effect of New Versions. - Once Covered Code has been published under a particular version of the - License, You may always continue to use it under the terms of that - version. You may also choose to use such Covered Code under the terms - of any subsequent version of the License published by Netscape. No one - other than Netscape has the right to modify the terms applicable to - Covered Code created under this License. - - 6.3. Derivative Works. - If You create or use a modified version of this License (which you may - only do in order to apply it to code which is not already Covered Code - governed by this License), You must (a) rename Your license so that - the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", - "MPL", "NPL" or any confusingly similar phrase do not appear in your - license (except to note that your license differs from this License) - and (b) otherwise make it clear that Your version of the license - contains terms which differ from the Mozilla Public License and - Netscape Public License. (Filling in the name of the Initial - Developer, Original Code or Contributor in the notice described in - Exhibit A shall not of themselves be deemed to be modifications of - this License.) - - 7. DISCLAIMER OF WARRANTY. - - COVERED CODE 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 CODE 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 CODE - IS WITH YOU. SHOULD ANY COVERED CODE 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 CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. - - 8. TERMINATION. - - 8.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. All - sublicenses to the Covered Code which are properly granted shall - survive any termination of this License. Provisions which, by their - nature, must remain in effect beyond the termination of this License - shall survive. - - 8.2. If You initiate litigation by asserting a patent infringement - claim (excluding declatory judgment actions) against Initial Developer - or a Contributor (the Initial Developer or Contributor against whom - You file such action is referred to as "Participant") alleging that: - - (a) such Participant's Contributor Version directly or indirectly - infringes any patent, then any and all rights granted by such - Participant to You under Sections 2.1 and/or 2.2 of this License - shall, upon 60 days notice from Participant terminate prospectively, - unless if within 60 days after receipt of notice You either: (i) - agree in writing to pay Participant a mutually agreeable reasonable - royalty for Your past and future use of Modifications made by such - Participant, or (ii) withdraw Your litigation claim with respect to - the Contributor Version against such Participant. If within 60 days - of notice, a reasonable royalty and payment arrangement are not - mutually agreed upon in writing by the parties or the litigation claim - is not withdrawn, the rights granted by Participant to You under - Sections 2.1 and/or 2.2 automatically terminate at the expiration of - the 60 day notice period specified above. - - (b) any software, hardware, or device, other than such Participant's - Contributor Version, directly or indirectly infringes any patent, then - any rights granted to You by such Participant under Sections 2.1(b) - and 2.2(b) are revoked effective as of the date You first made, used, - sold, distributed, or had made, Modifications made by that - Participant. - - 8.3. If You assert a patent infringement claim against Participant - alleging that such Participant's Contributor Version directly or - indirectly infringes any patent where such claim is resolved (such as - by license or settlement) prior to the initiation of patent - infringement litigation, then the reasonable value of the licenses - granted by such Participant under Sections 2.1 or 2.2 shall be taken - into account in determining the amount or value of any payment or - license. - - 8.4. In the event of termination under Sections 8.1 or 8.2 above, - all end user license agreements (excluding distributors and resellers) - which have been validly granted by You or any distributor hereunder - prior to termination shall survive termination. - - 9. 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 CODE, - 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 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. - - 10. U.S. GOVERNMENT END USERS. - - The Covered Code is a "commercial item," as that term is defined in - 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer - software" 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 Code with only those - rights set forth herein. - - 11. 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 - California law provisions (except to the extent applicable law, if - any, provides otherwise), excluding its conflict-of-law provisions. - With respect to disputes in which at least one party is a citizen of, - or an entity chartered or registered to do business in the United - States of America, any litigation relating to this License shall be - subject to the jurisdiction of the Federal Courts of the Northern - District of California, with venue lying in Santa Clara County, - California, 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. - - 12. 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. - - 13. MULTIPLE-LICENSED CODE. - - Initial Developer may designate portions of the Covered Code as - "Multiple-Licensed". "Multiple-Licensed" means that the Initial - Developer permits you to utilize portions of the Covered Code under - Your choice of the NPL or the alternative licenses, if any, specified - by the Initial Developer in the file described in Exhibit A. - - EXHIBIT A -Mozilla Public License. - - ``The contents of this file are subject to the Mozilla Public License - Version 1.1 (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.mozilla.org/MPL/ - - Software distributed under the License is distributed on an "AS IS" - basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the - License for the specific language governing rights and limitations - under the License. - - The Original Code is Javassist. - - The Initial Developer of the Original Code is Shigeru Chiba. - Portions created by Shigeru Chiba are Copyright (C) - 1999-2008 Shigeru Chiba. All Rights Reserved. - - Contributor(s): . - - Alternatively, the contents of this file may be used under the terms - of the GNU Lesser General Public License Version 2.1 or later license (the "[LGPL] License"), in which case the - provisions of [LGPL] License are applicable instead of those - above. If you wish to allow use of your version of this file only - under the terms of the [LGPL] License and not to allow others to use - your version of this file under the MPL, indicate your decision by - deleting the provisions above and replace them with the notice and - other provisions required by the [LGPL] License. If you do not delete - the provisions above, a recipient may use your version of this file - under either the MPL or the [LGPL] License." - - [NOTE: The text of this Exhibit A may differ slightly from the text of - the notices in the Source Code files of the Original Code. You should - 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 @@ -2420,6 +379,313 @@ Within the scripts/vm/hypervisor/xenserver directory 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/ @@ -3903,34 +2169,6 @@ Within the target/jar directory 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) @@ -3967,298 +2205,2043 @@ Within the target/jar directory 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 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) +Within the deps/awsapi-lib directory + licensed under the ANTLR 2 License http://www.antlr2.org/license.html (as follows) + + ANTLR 2 License - 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 + We reserve no legal rights to the ANTLR--it is fully in the public domain. An + individual or company may do whatever they wish with source code distributed + with ANTLR or the code generated by ANTLR, including the incorporation of ANTLR, + or its output, into commerical software. We encourage users to develop software + with ANTLR. However, we do ask that credit is given to us for developing ANTLR. + By "credit", we mean that if you use ANTLR or incorporate any source code into + one of your programs (commercial product, research project, or otherwise) that + you acknowledge this fact somewhere in the documentation, research report, + etc... If you like ANTLR and have developed a nice tool with the output, please + mention that you developed it using ANTLR. In addition, we ask that the headers + 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 - -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/ + Copyright (c) 2004-2008 The Apache Software Foundation + from The Apache Software Foundation http://www.apache.org/ + XmlSchema-1.4.3.jar + + licensed under the Apache License, Version 2 http://www.apache.org/licenses/LICENSE-2.0.txt (as above) + Copyright (c) 2004-2012 The Apache Software Foundation + from The Apache Software Foundation http://www.apache.org/ + apache-log4j-extras-1.0.jar http://logging.apache.org/log4j/companions/extras/ + axiom-api-1.2.8.jar http://ws.apache.org/axiom/source-repository.html + axiom-impl-1.2.8.jar http://ws.apache.org/axiom/source-repository.html + axis2-1.5.1.jar http://axis.apache.org/axis/ + axis2-adb-1.5.1.jar http://axis.apache.org/axis/ + axis2-ant-plugin-1.5.1.jar http://axis.apache.org/axis/ + axis2-codegen-1.4.1.jar http://axis.apache.org/axis/ + axis2-jaxbri-1.5.1.jar http://axis.apache.org/axis/ + axis2-jaxws-1.5.1.jar http://axis.apache.org/axis/ + axis2-jibx-1.5.1.jar http://axis.apache.org/axis/ + axis2-json-1.5.1.jar http://axis.apache.org/axis/ + axis2-kernel-1.5.1.jar http://axis.apache.org/axis/ + axis2-transport-http-1.5.1.jar http://axis.apache.org/axis/ + axis2-transport-local-1.5.1.jar http://axis.apache.org/axis/ + axis2-webapp-1.5.1.war http://axis.apache.org/axis/ + commons-codec-1.4.jar http://commons.apache.org/codec/ + commons-collections-3.1.jar http://commons.apache.org/collections/ + commons-fileupload-1.2.jar http://commons.apache.org/fileupload/ + commons-httpclient-3.1.jar http://hc.apache.org/httpclient-3.x/ + commons-io-1.4.jar http://commons.apache.org/io/ + commons-logging-1.1.1.jar http://commons.apache.org/logging/ + httpcore-4.0.jar http://hc.apache.org/httpcomponents-core-ga/ + log4j-1.2.15.jar http://logging.apache.org/log4j/ + neethi-2.0.4.jar http://svn.apache.org/viewvc/webservices/commons/tags/neethi/2.0.4/ + rampart-lib http://axis.apache.org/axis2/java/rampart/download/1.5/download.cgi + woden-api-1.0M8.jar http://svn.apache.org/viewvc/webservices/woden/tags/1.0M8_20080423/ + woden-impl-dom-1.0M8.jar http://svn.apache.org/viewvc/webservices/woden/tags/1.0M8_20080423/ + wss4j-1.5.8.jar http://ws.apache.org/wss4j/source-repository.html + xercesImpl.jar http://xerces.apache.org/xerces2-j/source-repository.html + xml-apis.jar http://repo1.maven.org/maven2/xml-apis/xml-apis/1.3.04/xml-apis-1.3.04-sources.jar + + 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-gson.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 Json.simple Project http://code.google.com/p/json-simple/ + json_simple-1.1.jar http://code.google.com/p/json-simple/source/checkout + + 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/ + jsch-0.1.42.jar http://www.jcraft.com/jsch/ + + 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 + jaxb-api-2.1.jar http://repo1.maven.org/maven2/javax/xml/bind/jaxb-api/2.1/jaxb-api-2.1-sources.jar + jaxb-impl-2.1.7.jar http://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-impl/2.1.7/jaxb-impl-2.1.7-sources.jar + jaxb-xjc-2.1.7.jar http://repo1.maven.org/maven2/com/sun/xml/bind/jaxb-xjc/2.1.7/jaxb-xjc-2.1.7-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/ + jta-1.1.jar http://repo1.maven.org/maven2/javax/transaction/jta/1.1/jta-1.1-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) 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 + mail-1.4.jar http://kenai.com/projects/javamail + + 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/ + junit-4.8.1.jar http://kentbeck.github.com/junit/ + + licensed under the Dom4J License http://dom4j.cvs.sourceforge.net/viewvc/dom4j/dom4j/LICENSE.txt (as follows) + + + Copyright 2001-2005 (C) MetaStuff, Ltd. All Rights Reserved. + + Redistribution and use of this software and associated documentation + ("Software"), with or without modification, are permitted provided + that the following conditions are met: + + 1. Redistributions of source code must retain copyright + statements and notices. Redistributions must also contain a + copy of this document. + + 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 name "DOM4J" must not be used to endorse or promote + products derived from this Software without prior written + permission of MetaStuff, Ltd. For written permission, + please contact dom4j-info@metastuff.com. + + 4. Products derived from this Software may not be called "DOM4J" + nor may "DOM4J" appear in their names without prior written + permission of MetaStuff, Ltd. DOM4J is a registered + trademark of MetaStuff, Ltd. + + 5. Due credit should be given to the DOM4J Project - + http://www.dom4j.org + + THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS + ``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 + METASTUFF, LTD. 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. + + from DOM4J Project http://dom4j.sourceforge.net/ + dom4j-1.6.1.jar http://dom4j.sourceforge.net/source-repository.html + + licensed under the MIT License http://www.opensource.org/licenses/mit-license.php (as follows) + + Copyright (c) 2004-2011 QOS.ch + + 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 QOS.ch http://www.qos.ch/ + slf4j-api-1.5.11.jar https://github.com/qos-ch/slf4j + slf4j-jdk14-1.5.11.jar https://github.com/qos-ch/slf4j + + licensed under the Mozilla Public License, Version 1.0 http://www.mozilla.org/MPL/1.1/ (as follows) + + + MOZILLA PUBLIC LICENSE + Version 1.1 + + --------------- + + 1. Definitions. + + 1.0.1. "Commercial Use" means distribution or otherwise making the + Covered Code available to a third party. + + 1.1. "Contributor" means each entity that creates or contributes to + the creation of Modifications. + + 1.2. "Contributor Version" means the combination of the Original + Code, prior Modifications used by a Contributor, and the Modifications + made by that particular Contributor. + + 1.3. "Covered Code" means the Original Code or Modifications or the + combination of the Original Code and Modifications, in each case + including portions thereof. + + 1.4. "Electronic Distribution Mechanism" means a mechanism generally + accepted in the software development community for the electronic + transfer of data. + + 1.5. "Executable" means Covered Code in any form other than Source + Code. + + 1.6. "Initial Developer" means the individual or entity identified + as the Initial Developer in the Source Code notice required by Exhibit + A. + + 1.7. "Larger Work" means a work which combines Covered Code or + portions thereof with code not governed by the terms of this License. + + 1.8. "License" means this document. + + 1.8.1. "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 any addition to or deletion from the + substance or structure of either the Original Code or any previous + Modifications. When Covered Code is released as a series of files, a + Modification is: + A. Any addition to or deletion from the contents of a file + containing Original Code or previous Modifications. + + B. Any new file that contains any part of the Original Code or + previous Modifications. + + 1.10. "Original Code" means Source Code of computer software code + which is described in the Source Code notice required by Exhibit A as + Original Code, and which, at the time of its release under this + License is not already Covered Code governed by this License. + + 1.10.1. "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.11. "Source Code" means the preferred form of the Covered Code for + making modifications to it, including all modules it contains, plus + any associated interface definition files, scripts used to control + compilation and installation of an Executable, or source code + differential comparisons against either the Original Code or another + well known, available Covered Code of the Contributor's choice. The + Source Code can be in a compressed or archival form, provided the + appropriate decompression or de-archiving software is widely available + for no charge. + + 1.12. "You" (or "Your") means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License or a future version of this License issued under Section 6.1. + 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. Source Code License. + + 2.1. The Initial Developer Grant. + The Initial Developer hereby grants You a world-wide, royalty-free, + non-exclusive license, subject to third party intellectual property + claims: + (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 + Code (or portions thereof) with or without Modifications, and/or + as part of a Larger Work; and + + (b) under Patents Claims infringed by the making, using or + selling of Original Code, to make, have made, use, practice, + sell, and offer for sale, and/or otherwise dispose of the + Original Code (or portions thereof). + + (c) the licenses granted in this Section 2.1(a) and (b) are + effective on the date Initial Developer first distributes + Original Code 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 Code; 2) + separate from the Original Code; or 3) for infringements caused + by: i) the modification of the Original Code or ii) the + combination of the Original Code with other software or devices. + + 2.2. Contributor Grant. + 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 Code + 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 makes Commercial Use of + the Covered Code. + + (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) separate from the Contributor Version; + 3) 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 4) under Patent Claims + infringed by Covered Code in the absence of Modifications made by + that Contributor. + + 3. Distribution Obligations. + + 3.1. Application of License. + The Modifications which You create or to which You contribute are + governed by the terms of this License, including without limitation + Section 2.2. The Source Code version of Covered Code may be + distributed only under the terms of this License or a future version + of this License released under Section 6.1, and You must include a + copy of this License with every copy of the Source Code You + distribute. You may not offer or impose any terms on any Source Code + version that alters or restricts the applicable version of this + License or the recipients' rights hereunder. However, You may include + an additional document offering the additional rights described in + Section 3.5. + + 3.2. Availability of Source Code. + Any Modification which You create or to which You contribute must be + made available in Source Code form under the terms of this License + either on the same media as an Executable version or via an accepted + Electronic Distribution Mechanism to anyone to whom you made an + Executable version available; and if made available via Electronic + Distribution Mechanism, must remain available for at least twelve (12) + months after the date it initially became available, or at least six + (6) months after a subsequent version of that particular Modification + has been made available to such recipients. You are responsible for + ensuring that the Source Code version remains available even if the + Electronic Distribution Mechanism is maintained by a third party. + + 3.3. Description of Modifications. + You must cause all Covered Code to which You contribute to contain a + file documenting the changes You made to create that Covered Code and + the date of any change. You must include a prominent statement that + the Modification is derived, directly or indirectly, from Original + Code provided by the Initial Developer and including the name of the + Initial Developer in (a) the Source Code, and (b) in any notice in an + Executable version or related documentation in which You describe the + origin or ownership of the Covered Code. + + 3.4. Intellectual Property Matters + (a) Third Party Claims. + If Contributor has knowledge that a license under a third party's + intellectual property rights is required to exercise the rights + granted by such Contributor under Sections 2.1 or 2.2, + Contributor must include a text file with the Source Code + distribution titled "LEGAL" which describes the claim and the + party making the claim in sufficient detail that a recipient will + know whom to contact. If Contributor obtains such knowledge after + the Modification is made available as described in Section 3.2, + Contributor shall promptly modify the LEGAL file in all copies + Contributor makes available thereafter and shall take other steps + (such as notifying appropriate mailing lists or newsgroups) + reasonably calculated to inform those who received the Covered + Code that new knowledge has been obtained. + + (b) Contributor APIs. + If Contributor's Modifications include an application programming + interface and Contributor has knowledge of patent licenses which + are reasonably necessary to implement that API, Contributor must + also include this information in the LEGAL file. + + (c) Representations. + Contributor represents that, except as disclosed pursuant to + Section 3.4(a) above, Contributor believes that Contributor's + Modifications are Contributor's original creation(s) and/or + Contributor has sufficient rights to grant the rights conveyed by + this License. + + 3.5. Required Notices. + You must duplicate the notice in Exhibit A in each file of the Source + Code. If it is not possible to put such notice in a particular Source + Code file due to its structure, then You must include such notice in a + location (such as a relevant directory) where a user would be likely + to look for such a notice. If You created one or more Modification(s) + You may add your name as a Contributor to the notice described in + Exhibit A. You must also duplicate this License in any documentation + for the Source Code where You describe recipients' rights or ownership + rights relating to Covered Code. You may choose to offer, and to + charge a fee for, warranty, support, indemnity or liability + obligations to one or more recipients of Covered Code. 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 than + 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.6. Distribution of Executable Versions. + You may distribute Covered Code in Executable form only if the + requirements of Section 3.1-3.5 have been met for that Covered Code, + and if You include a notice stating that the Source Code version of + the Covered Code is available under the terms of this License, + including a description of how and where You have fulfilled the + obligations of Section 3.2. The notice must be conspicuously included + in any notice in an Executable version, related documentation or + collateral in which You describe recipients' rights relating to the + Covered Code. You may distribute the Executable version of Covered + Code or ownership rights under 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 version does not attempt to limit or alter the recipient's + rights in the Source Code version from the rights set forth in this + License. If You distribute the Executable version 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 any 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.7. Larger Works. + You may create a Larger Work by combining Covered Code 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 Code. + + 4. Inability to Comply Due to Statute or Regulation. + + If it is impossible for You to comply with any of the terms of this + License with respect to some or all of the Covered Code due to + statute, judicial order, or regulation then You must: (a) comply with + the terms of this License to the maximum extent possible; and (b) + describe the limitations and the code they affect. Such description + must be included in the LEGAL file described in Section 3.4 and must + be included with all distributions of the Source Code. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + + 5. Application of this License. + + This License applies to code to which the Initial Developer has + attached the notice in Exhibit A and to related Covered Code. + + 6. Versions of the License. + + 6.1. New Versions. + Netscape Communications Corporation ("Netscape") may publish revised + and/or new versions of the License from time to time. Each version + will be given a distinguishing version number. + + 6.2. Effect of New Versions. + Once Covered Code has been published under a particular version of the + License, You may always continue to use it under the terms of that + version. You may also choose to use such Covered Code under the terms + of any subsequent version of the License published by Netscape. No one + other than Netscape has the right to modify the terms applicable to + Covered Code created under this License. + + 6.3. Derivative Works. + If You create or use a modified version of this License (which you may + only do in order to apply it to code which is not already Covered Code + governed by this License), You must (a) rename Your license so that + the phrases "Mozilla", "MOZILLAPL", "MOZPL", "Netscape", + "MPL", "NPL" or any confusingly similar phrase do not appear in your + license (except to note that your license differs from this License) + and (b) otherwise make it clear that Your version of the license + contains terms which differ from the Mozilla Public License and + Netscape Public License. (Filling in the name of the Initial + Developer, Original Code or Contributor in the notice described in + Exhibit A shall not of themselves be deemed to be modifications of + this License.) + + 7. DISCLAIMER OF WARRANTY. + + COVERED CODE 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 CODE 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 CODE + IS WITH YOU. SHOULD ANY COVERED CODE 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 CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + + 8. TERMINATION. + + 8.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. All + sublicenses to the Covered Code which are properly granted shall + survive any termination of this License. Provisions which, by their + nature, must remain in effect beyond the termination of this License + shall survive. + + 8.2. If You initiate litigation by asserting a patent infringement + claim (excluding declatory judgment actions) against Initial Developer + or a Contributor (the Initial Developer or Contributor against whom + You file such action is referred to as "Participant") alleging that: + + (a) such Participant's Contributor Version directly or indirectly + infringes any patent, then any and all rights granted by such + Participant to You under Sections 2.1 and/or 2.2 of this License + shall, upon 60 days notice from Participant terminate prospectively, + unless if within 60 days after receipt of notice You either: (i) + agree in writing to pay Participant a mutually agreeable reasonable + royalty for Your past and future use of Modifications made by such + Participant, or (ii) withdraw Your litigation claim with respect to + the Contributor Version against such Participant. If within 60 days + of notice, a reasonable royalty and payment arrangement are not + mutually agreed upon in writing by the parties or the litigation claim + is not withdrawn, the rights granted by Participant to You under + Sections 2.1 and/or 2.2 automatically terminate at the expiration of + the 60 day notice period specified above. + + (b) any software, hardware, or device, other than such Participant's + Contributor Version, directly or indirectly infringes any patent, then + any rights granted to You by such Participant under Sections 2.1(b) + and 2.2(b) are revoked effective as of the date You first made, used, + sold, distributed, or had made, Modifications made by that + Participant. + + 8.3. If You assert a patent infringement claim against Participant + alleging that such Participant's Contributor Version directly or + indirectly infringes any patent where such claim is resolved (such as + by license or settlement) prior to the initiation of patent + infringement litigation, then the reasonable value of the licenses + granted by such Participant under Sections 2.1 or 2.2 shall be taken + into account in determining the amount or value of any payment or + license. + + 8.4. In the event of termination under Sections 8.1 or 8.2 above, + all end user license agreements (excluding distributors and resellers) + which have been validly granted by You or any distributor hereunder + prior to termination shall survive termination. + + 9. 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 CODE, + 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 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. + + 10. U.S. GOVERNMENT END USERS. + + The Covered Code is a "commercial item," as that term is defined in + 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial computer + software" 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 Code with only those + rights set forth herein. + + 11. 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 + California law provisions (except to the extent applicable law, if + any, provides otherwise), excluding its conflict-of-law provisions. + With respect to disputes in which at least one party is a citizen of, + or an entity chartered or registered to do business in the United + States of America, any litigation relating to this License shall be + subject to the jurisdiction of the Federal Courts of the Northern + District of California, with venue lying in Santa Clara County, + California, 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. + + 12. 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. + + 13. MULTIPLE-LICENSED CODE. + + Initial Developer may designate portions of the Covered Code as + "Multiple-Licensed". "Multiple-Licensed" means that the Initial + Developer permits you to utilize portions of the Covered Code under + Your choice of the NPL or the alternative licenses, if any, specified + by the Initial Developer in the file described in Exhibit A. + + EXHIBIT A -Mozilla Public License. + + ``The contents of this file are subject to the Mozilla Public License + Version 1.1 (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.mozilla.org/MPL/ + + Software distributed under the License is distributed on an "AS IS" + basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the + License for the specific language governing rights and limitations + under the License. + + The Original Code is Javassist. + + The Initial Developer of the Original Code is Shigeru Chiba. + Portions created by Shigeru Chiba are Copyright (C) + 1999-2008 Shigeru Chiba. All Rights Reserved. + + Contributor(s): . + + Alternatively, the contents of this file may be used under the terms + of the GNU Lesser General Public License Version 2.1 or later license (the "[LGPL] License"), in which case the + provisions of [LGPL] License are applicable instead of those + above. If you wish to allow use of your version of this file only + under the terms of the [LGPL] License and not to allow others to use + your version of this file under the MPL, indicate your decision by + deleting the provisions above and replace them with the notice and + other provisions required by the [LGPL] License. If you do not delete + the provisions above, a recipient may use your version of this file + under either the MPL or the [LGPL] License." + + [NOTE: The text of this Exhibit A may differ slightly from the text of + the notices in the Source Code files of the Original Code. You should + 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/ diff --git a/NOTICE b/NOTICE index cecb580925e..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,25 +483,11 @@ 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 axis2-ant-plugin-1.5.1.jar + axis2-codegen-1.4.1.jar axis2-jaxbri-1.5.1.jar axis2-jaxws-1.5.1.jar axis2-jibx-1.5.1.jar @@ -531,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 @@ -587,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 @@ -672,3 +679,17 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ + + + For + wss4j-1.5.8.jar + + + Apache WebServices - WSS4J + Copyright 2004-2011 The Apache Software Foundation + + This product includes software developed at + The Apache Software Foundation (http://www.apache.org/). + + This product includes software Copyright University of Southampton IT + Innovation Centre, 2006 (http://www.it-innovation.soton.ac.uk). diff --git a/README.md b/README.md index c565de6a0ae..7b4d973666e 100644 --- a/README.md +++ b/README.md @@ -45,67 +45,7 @@ under the License. # Building CloudStack -By default, CloudStack will only build with supporting packages -that are appropved by the ASF as being compatible with the Apache -Software License Version 2. - -## Default build - -To build the default build target, use maven3 and execute: - -mvn install - -## Including optional third party libraries in your build - -If you want to build this software against one of the optional -third party libraries, follow the instructions below: - -These third parties jars are non available in Maven central, and -need to be located and downloaded by the developer themselves. -The libraries to download are listed below, by the feature that -they support. - -For F5 load balancing support: -cloud-iControl.jar - -For Netscaler support: -cloud-netscaler.jar -cloud-netscaler-sdx.jar - -For NetApp Storage Support: -cloud-manageontap.jar - -For VMware Support: -vmware-vim.jar -vmware-vim25.jar -vmware-apputils.jar - -Once downloaded (and named the same as listed above), they can be -installed into your local maven repository with the following command: - -cd deps&&sh ./install-non-oss.sh - -To perform the build, run the following command: - -mvn -Dnonoss install - -## Running a developer environment - -To run the webapp client: - -mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.0-beta-1:run -pl :cloud-client-ui -am -Pclient - -Then hit: http://localhost:8080/cloud-client-ui/ - -or add in your ~/.m2/settings.xml - - org.apache.tomcat.maven - -and save your fingers with mvn tomcat7:run -pl :cloud-client-ui -am -Pclient - -Optionally add -Dnonoss to either of the commands above. - -If you want to use ide debug: replace mvn with mvnDebug and attach your ide debugger to port 8000 +See the INSTALL file. # Notice of Cryptographic Software @@ -126,5 +66,15 @@ Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Sec The following provides more details on the included cryptographic software: -TODO + CloudStack makes use of JaSypt cryptographic libraries + CloudStack has a system requirement of MySQL, and uses native database encryption + functionality. + + CloudStack makes use of the Bouncy Castle general-purpose encryption library. + + CloudStack can optionally interacts with and controls OpenSwan-based VPNs. + + CloudStack has a dependency on Apache WSS4J as part of the AWSAPI implementation. + + CloudStack has a dependency on and makes use of JSch - a java SSH2 implementation. diff --git a/README.tools.md b/README.tools.md new file mode 100644 index 00000000000..f743c8927c6 --- /dev/null +++ b/README.tools.md @@ -0,0 +1,260 @@ +> 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. + + +--------------------------------------------------------------------------- +This README describes the various tools available with Apache Cloudstack - +for compiling, deploying, building and testing the project +--------------------------------------------------------------------------- + +DevCloud +========================================================= +Under tools/devcloud + +NOTE - DevCloud (tools/devcloud) 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. + +#### Contents: #### + +Under tools/devcloud are various scripts used to build the devcloud image. +devcloudsetup.sh - the origional devcloud build script (assumes an Ubuntu 12.04 +VM image) + + $ cd tools/devcloud + +* build_vagrant_basebox.sh - a script that uses VirtualBox, VeeWee, Vagrant +(patched) and puppet to create a devcloud basebox +* veewee - configuration files used to build a basic Ubuntu 12.04 vagrant box +via VeeWee +* basebuild - The Vagrantfile and puppet module that gets applied to the basic +Ubuntu 12.04 box +* devcloudbox - The Vagrantfile and puppet module that is used with the +[hopefully] distributed devcloud base box + +#### Instructions: #### + +To build a "devcloud base box", run you need a system with VirtualBox and rvm +installed (use ruby 1.9.2). Run build_vagrant_basebox.sh to build the base +box. + +To use the "devcloud base box" that is created in the previous step, you need +to have installed a forked version of Vagrant (until we make the changes +plugins instead of direct source patches) that can be found here: + +Once installed per the Vagrant installation process, run: + + $ vagrant box add devcloud [path to devcloud.box] + +Then, either go into the devcloudbox folder of your checked out version of the +CloudStack code (incubator-cloudstack/tools/devcloud/devcloudbox), or copy the +contents of that folder to another location. + +Assuming the patched Vagrant installation is working, you then +simply run "vagrant up" from within that directory. + +#### Installation #### + +Install DevCloud Base system: + +1. get code from https://github.com/jedi4ever/veewee, and install +2. veewee vbox define devcloud ubuntu-12.04-server-i386 +3. put these two files(definition.rb and preseed.cfg) under ./definition/devcloud/ +3. veewee vbox build devcloud + + +Marvin +========================================================= +Under tools/marvin + +Marvin is the functional testing framework for CloudStack written in python. +Writing of unittests and functional tests with Marvin makes testing with +cloudstack easier + +Visit the +[wiki](https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python) +for the most updated information + +#### Dependencies #### +Marvin will require the following dependencies, these will be automatically +downloaded from the python cheeseshop when you install Marvin. + +- mysql-connector-python, +- paramiko, +- nose, +- unittest-xml-reporting, + +#### Installation #### + + $ untar Marvin-0.1.0.tar.gz + $ cd Marvin-0.1.0 + $ python setup.py install + +#### Features #### + +1. very handy cloudstack API python wrapper +2. support async job executing in parallel +3. remote ssh login/execute command +4. mysql query + +#### Examples #### + +Examples on how to develop your own configuration can be found in the marvin sandbox. +Under tools/marvin/marvin/sandbox + +To generate the config for a deployment. Alter the .properties file in the sandbox. For example the +simualtordemo.properties after modification can generate the config file as +shown below + + $ python simulator_setup.py -i simulatordemo.properties -o simulatordemo.cfg + +To deploy the environment and run the tests + + $ python -m marvin.deployAndRun -c simulatordemo.cfg -t /tmp/t.log -r /tmp/r.log -d testcase + +#### Tests #### + +Functional Tests written using marvin can be found under test/integration +folder. These are tests that are written to be run against a live deployed +system. + +To run the tests - you should have marvin installed and correctly importable. +The tests are long running and are best monitored by external hudson jobs. + +Also you will have to point marvin to the right configuration file that has +details about your cloudstack deployment. For more help on how to write the +config file and run tests check the tutorial at : + +[] (https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python) + +#### Build Verification Testing (BVT) #### + +These test cases are the core functionality tests that ensure the application +is stable and can be tested thoroughly. These BVT cases definitions are +located at : +[] (https://docs.google.com/a/cloud.com/spreadsheet/ccc?key=0Ak8acbfxQG8ndEppOGZSLV9mUF9idjVkTkZkajhTZkE&invite=CPij0K0L) + +##### Guidelines on tests ##### + +BVT test cases are being developed using Python unittests2. Following are +certain guidelines being followed + +1. Tests exercised for the same resource should ideally be present under a +single suite or file. + +2. Time-consuming operations that create new cloud resources like server +creation, volume creation etc should not necessarily be exercised per unit +test. The resources can be shared by creating them at the class-level using +setUpClass and shared across all instances during a single run. + +3. Certain tests pertaining to NAT, Firewall and Load Balancing warrant fresh +resources per test. Hence a call should be taken by the stakeholders regarding +sharing resources. + +4. Ensure that the tearDown/tearDownClass functions clean up all the resources +created during the test run. + +For more information about unittests: [] (http://docs.python.org/library/unittest.html) + +##### BVT Tests ##### +Under test/integration/smoke + +The following files contain these BVT cases: + +1. test_vm_life_cycle.py - VM Life Cycle tests +2. test_volumes.py - Volumes related tests +3. test_snapshots.py - Snapshots related tests +4. test_disk_offerings.py - Disk Offerings related tests +5. test_service_offerings.py - Service Offerings related tests +6. test_hosts.py - Hosts and Clusters related tests +7. test_iso.py - ISO related tests +8. test_network.py - Network related tests +9. test_primary_storage.py - Primary storage related tests +10. test_secondary_storage.py - Secondary storage related tests +11. test_ssvm.py - SSVM & CPVM related tests +12. test_templates.py - Templates related tests +13. test_routers.py - Router related tests + + +##### P1 Tests ##### +Under test/integration/component + +These test cases are the core functionality tests that ensure the application +is stable and can be tested thoroughly. These P1 cases definitions are located +at : +[] (https://docs.google.com/a/clogeny.com/spreadsheet/ccc?key=0Aq5M2ldK6eyedDJBa0EzM0RPNmdVNVZOWnFnOVJJcHc&hl=en_US) + +The following files contain these P1 cases: + +1. test_snapshots.py - Snapshots related tests +2. test_routers.py - Router related tests +3. test_usage.py - Usage realted tests +4. test_account.py - Account related tests +5. test_resource_limits.py - Resource limits tests +6. test_security_groups.py - Security groups related tests +7. test_templates.py - templates related tests +8. test_volumes.py - Volumes related tests +9. test_blocker_bugs.py - Blocker bugs tests +10. test_project_configs.py - Project global configuration related tests +11. test_project_limits.py - Project resource limits related tests +12. test_project_resources.py - Project resource creation related tests +13. test_project_usage.py - Project usage related tests +14. test_projects - Projects functionality tests + +Marvin Sandbox +========================================================= +In: tools/marvin/marvin/sandbox + +In here you should find a few common deployment models of CloudStack that you +can configure with properties files to suit your own deployment. One deployment +model for each of - advanced zone, basic zone and a simulator demo are given. + +$ ls - +basic/ +advanced/ +simulator/ + +Each property file is divided into logical sections and should be familiar to +those who have deployed CloudStack before. Once you have your properties file +you will have to create a JSON configuration of your deployment using the +python script provided in the respective folder. + +The demo files are from the tutorial for testing with python that can be found at + https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python + +A common deployment model of a simulator.cfg that can be used for debugging is +included. This will configure an advanced zone with simulators that can be used +for debugging purposes when you do not have hardware to debug with. + +To do this: +$ cd cloudstack-oss/ +$ ant run-simulator #This will start up the mgmt server with the simulator seeded + +## In another shell +$ ant run-simulator + +test/conf - EC2 script +========================================================= + +To run submitCertEC2 and deleteCertEC2 scripts, update parameters in conf/tool.properties file: + +* host - ip address of the host where cloud-bridge software is installed +* port - port cloud-bridge software is listening to +* accesspoint - access point for cloud-bridge REST request +* version - Amazon EC2 api version supported by cloud-bridge +* signaturemethod - HmacSHA1 or HmacSHA256 +* expires - the date when certificate expires diff --git a/client/tomcatconf/simulator.properties.in b/agent/bindir/cloud-ssh.in similarity index 72% rename from client/tomcatconf/simulator.properties.in rename to agent/bindir/cloud-ssh.in index 24e5e627c71..e4b3c141a97 100644 --- a/client/tomcatconf/simulator.properties.in +++ b/agent/bindir/cloud-ssh.in @@ -1,3 +1,4 @@ +#!/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 @@ -15,17 +16,4 @@ # specific language governing permissions and limitations # under the License. -host=127.0.0.1 -port=8250 -workers=3 -zone=1 -pod=1 -run=13 -sequence=r -agent.save.path=/tmp/agents -latency=2 -latency.start.range=2 -latency.end.range=2 -delay.distribution={(5,10); (5,10); (5,10); (5,10); (5,10); (5,10); (5,10); (5,10); (5,10); (10,120)} -property.scan.enabled=1 -property.scan.interval=300 +ssh -i /root/.ssh/id_rsa.cloud -p 3922 root@$1 diff --git a/agent/pom.xml b/agent/pom.xml index 458d97ce4df..810f33fc572 100644 --- a/agent/pom.xml +++ b/agent/pom.xml @@ -31,11 +31,6 @@ cloud-core ${project.version} - - org.mortbay.jetty - jetty - 6.1.26 - org.apache.cloudstack cloud-utils @@ -60,6 +55,57 @@ + + maven-antrun-plugin + 1.7 + + + generate-resource + generate-resources + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/agent/src/com/cloud/agent/Agent.java b/agent/src/com/cloud/agent/Agent.java index 4bfd0765161..84b0db62684 100755 --- a/agent/src/com/cloud/agent/Agent.java +++ b/agent/src/com/cloud/agent/Agent.java @@ -27,7 +27,6 @@ import java.util.List; import java.util.Map; import java.util.Timer; import java.util.TimerTask; - import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; @@ -48,6 +47,7 @@ import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.PingCommand; +import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.ShutdownCommand; import com.cloud.agent.api.StartupAnswer; import com.cloud.agent.api.StartupCommand; @@ -491,6 +491,10 @@ public class Agent implements HandlerFactory, IAgentControl { cancelTasks(); _reconnectAllowed = false; answer = new Answer(cmd, true, null); + } else if (cmd instanceof ReadyCommand && ((ReadyCommand)cmd).getDetails() != null) { + s_logger.debug("Not ready to connect to mgt server: " + ((ReadyCommand)cmd).getDetails()); + System.exit(1); + return; } else if (cmd instanceof MaintainCommand) { s_logger.debug("Received maintainCommand" ); cancelTasks(); @@ -513,6 +517,9 @@ public class Agent implements HandlerFactory, IAgentControl { } } else { + if (cmd instanceof ReadyCommand) { + processReadyCommand((ReadyCommand)cmd); + } _inProgress.incrementAndGet(); try { answer = _resource.executeRequest(cmd); @@ -576,6 +583,19 @@ public class Agent implements HandlerFactory, IAgentControl { setLastPingResponseTime(); } } + + + public void processReadyCommand(Command cmd) { + + final ReadyCommand ready = (ReadyCommand) cmd; + + s_logger.info("Proccess agent ready command, agent id = " + ready.getHostId()); + if (ready.getHostId() != null) { + setId(ready.getHostId()); + } + s_logger.info("Ready command is processed: agent id = " + getId()); + + } public void processOtherTask(Task task) { final Object obj = task.get(); @@ -601,6 +621,7 @@ public class Agent implements HandlerFactory, IAgentControl { } catch (final ClosedChannelException e) { s_logger.warn("Unable to send request: " + request.toString()); } + } else if (obj instanceof Request) { final Request req = (Request) obj; final Command command = req.getCommand(); diff --git a/agent/src/com/cloud/agent/AgentShell.java b/agent/src/com/cloud/agent/AgentShell.java index 5d6a88c488a..eac3e50d92c 100644 --- a/agent/src/com/cloud/agent/AgentShell.java +++ b/agent/src/com/cloud/agent/AgentShell.java @@ -39,6 +39,7 @@ import java.util.UUID; import javax.naming.ConfigurationException; import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.log4j.Logger; @@ -61,6 +62,7 @@ import com.cloud.utils.script.Script; public class AgentShell implements IAgentShell { private static final Logger s_logger = Logger.getLogger(AgentShell.class .getName()); + private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private final Properties _properties = new Properties(); private final Map _cmdLineProperties = new HashMap(); @@ -224,11 +226,12 @@ public class AgentShell implements IAgentShell { } public static void wget(String url, File file) throws IOException { - final HttpClient client = new HttpClient(); + final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); 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 @@ -251,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/pom.xml b/api/pom.xml index f25a6bcbf74..7461c67aaa2 100644 --- a/api/pom.xml +++ b/api/pom.xml @@ -40,5 +40,6 @@ install src + test diff --git a/api/src/com/cloud/agent/api/AgentControlAnswer.java b/api/src/com/cloud/agent/api/AgentControlAnswer.java index 1cdcc1e8322..7dbf7b509eb 100644 --- a/api/src/com/cloud/agent/api/AgentControlAnswer.java +++ b/api/src/com/cloud/agent/api/AgentControlAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class AgentControlAnswer extends Answer { public AgentControlAnswer() { } - + public AgentControlAnswer(Command command) { super(command); } - + public AgentControlAnswer(Command command, boolean success, String details) { super(command, success, details); } diff --git a/api/src/com/cloud/agent/api/AgentControlCommand.java b/api/src/com/cloud/agent/api/AgentControlCommand.java index 6cc8e6fde9b..da187ac4ca8 100644 --- a/api/src/com/cloud/agent/api/AgentControlCommand.java +++ b/api/src/com/cloud/agent/api/AgentControlCommand.java @@ -17,10 +17,10 @@ package com.cloud.agent.api; public class AgentControlCommand extends Command { - + public AgentControlCommand() { } - + public boolean executeInSequence() { return false; } diff --git a/api/src/com/cloud/agent/api/Answer.java b/api/src/com/cloud/agent/api/Answer.java index 932da233a05..655f4470097 100755 --- a/api/src/com/cloud/agent/api/Answer.java +++ b/api/src/com/cloud/agent/api/Answer.java @@ -21,40 +21,40 @@ import com.cloud.utils.exception.ExceptionUtil; public class Answer extends Command { protected boolean result; protected String details; - + protected Answer() { } - + public Answer(Command command) { this(command, true, null); } - + public Answer(Command command, boolean success, String details) { result = success; this.details = details; } - + public Answer(Command command, Exception e) { this(command, false, ExceptionUtil.toString(e)); } - + public boolean getResult() { return result; } - + public String getDetails() { return details; } - + @Override public boolean executeInSequence() { return false; } - + public static UnsupportedAnswer createUnsupportedCommandAnswer(Command cmd) { return new UnsupportedAnswer(cmd, "Unsupported command issued:" + cmd.toString() + ". Are you sure you got the right type of server?"); } - + public static UnsupportedAnswer createUnsupportedVersionAnswer(Command cmd) { return new UnsupportedAnswer(cmd, "Unsuppored Version."); } diff --git a/api/src/com/cloud/agent/api/AttachIsoCommand.java b/api/src/com/cloud/agent/api/AttachIsoCommand.java index ff9da83669e..c6f0b6124b7 100644 --- a/api/src/com/cloud/agent/api/AttachIsoCommand.java +++ b/api/src/com/cloud/agent/api/AttachIsoCommand.java @@ -48,11 +48,11 @@ public class AttachIsoCommand extends Command { public boolean isAttach() { return attach; } - + public String getStoreUrl() { return storeUrl; } - + public void setStoreUrl(String url) { storeUrl = url; } diff --git a/api/src/com/cloud/agent/api/AttachVolumeAnswer.java b/api/src/com/cloud/agent/api/AttachVolumeAnswer.java index 253b4445667..b377b7c1386 100644 --- a/api/src/com/cloud/agent/api/AttachVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/AttachVolumeAnswer.java @@ -20,38 +20,38 @@ package com.cloud.agent.api; public class AttachVolumeAnswer extends Answer { private Long deviceId; private String chainInfo; - + protected AttachVolumeAnswer() { - + } - + public AttachVolumeAnswer(AttachVolumeCommand cmd, String result) { super(cmd, false, result); this.deviceId = null; } - + public AttachVolumeAnswer(AttachVolumeCommand cmd, Long deviceId) { super(cmd); this.deviceId = deviceId; } - + public AttachVolumeAnswer(AttachVolumeCommand cmd) { super(cmd); this.deviceId = null; } - + /** * @return the deviceId */ public Long getDeviceId() { return deviceId; } - + public void setChainInfo(String chainInfo) { this.chainInfo = chainInfo; } - + public String getChainInfo() { return chainInfo; } diff --git a/api/src/com/cloud/agent/api/AttachVolumeCommand.java b/api/src/com/cloud/agent/api/AttachVolumeCommand.java index 98bfb2e485e..302b8f80af3 100644 --- a/api/src/com/cloud/agent/api/AttachVolumeCommand.java +++ b/api/src/com/cloud/agent/api/AttachVolumeCommand.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.storage.Storage.StoragePoolType; public class AttachVolumeCommand extends Command { - + boolean attach; String vmName; StoragePoolType pooltype; @@ -29,10 +29,10 @@ public class AttachVolumeCommand extends Command { String volumeName; Long deviceId; String chainInfo; - + protected AttachVolumeCommand() { } - + public AttachVolumeCommand(boolean attach, String vmName, StoragePoolType pooltype, String volumeFolder, String volumePath, String volumeName, Long deviceId, String chainInfo) { this.attach = attach; this.vmName = vmName; @@ -43,20 +43,20 @@ public class AttachVolumeCommand extends Command { this.deviceId = deviceId; this.chainInfo = chainInfo; } - + @Override public boolean executeInSequence() { return true; } - + public boolean getAttach() { return attach; } - + public String getVmName() { return vmName; } - + public StoragePoolType getPooltype() { return pooltype; } @@ -68,11 +68,11 @@ public class AttachVolumeCommand extends Command { public String getVolumeFolder() { return volumeFolder; } - + public String getVolumePath() { return volumePath; } - + public String getVolumeName() { return volumeName; } @@ -84,15 +84,15 @@ public class AttachVolumeCommand extends Command { public void setDeviceId(Long deviceId) { this.deviceId = deviceId; } - + public String getPoolUuid() { return poolUuid; } - + public void setPoolUuid(String poolUuid) { this.poolUuid = poolUuid; } - + public String getChainInfo() { return chainInfo; } diff --git a/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java b/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java index 707092fff07..9e35db66f57 100644 --- a/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/BackupSnapshotAnswer.java @@ -20,11 +20,11 @@ package com.cloud.agent.api; public class BackupSnapshotAnswer extends Answer { private String backupSnapshotName; private boolean full; - + protected BackupSnapshotAnswer() { - + } - + public BackupSnapshotAnswer(BackupSnapshotCommand cmd, boolean success, String result, String backupSnapshotName, boolean full) { super(cmd, success, result); this.backupSnapshotName = backupSnapshotName; @@ -37,7 +37,7 @@ public class BackupSnapshotAnswer extends Answer { public String getBackupSnapshotName() { return backupSnapshotName; } - + public boolean isFull() { return full; } diff --git a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java index 9476d7d7065..a0ac8d7ad71 100644 --- a/api/src/com/cloud/agent/api/BackupSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/BackupSnapshotCommand.java @@ -17,12 +17,13 @@ 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; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class BackupSnapshotCommand extends SnapshotCommand { private String prevSnapshotUuid; @@ -32,24 +33,24 @@ public class BackupSnapshotCommand extends SnapshotCommand { private Long snapshotId; @LogLevel(Log4jLevel.Off) private SwiftTO swift; + private S3TO s3; StorageFilerTO pool; protected BackupSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The UUID of the primary storage Pool * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * @param snapshotUuid The UUID of the snapshot which is going to be backed up * @param prevSnapshotUuid The UUID of the previous snapshot for this volume. This will be destroyed on the primary storage. * @param prevBackupUuid This is the UUID of the vhd file which was last backed up on secondary storage. - * @param firstBackupUuid This is the backup of the first ever snapshot taken by the volume. + * @param firstBackupUuid This is the backup of the first ever snapshot taken by the volume. * @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. + * @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, @@ -62,19 +63,18 @@ public class BackupSnapshotCommand extends SnapshotCommand { String prevBackupUuid, boolean isVolumeInactive, String vmName, - int wait) + 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); } - + public String getPrevSnapshotUuid() { return prevSnapshotUuid; } @@ -82,13 +82,13 @@ public class BackupSnapshotCommand extends SnapshotCommand { public String getPrevBackupUuid() { return prevBackupUuid; } - + public boolean isVolumeInactive() { return isVolumeInactive; } - + public String getVmName() { - return vmName; + return vmName; } public SwiftTO getSwift() { @@ -99,11 +99,16 @@ 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; } - public StorageFilerTO getPool() { - return pool; - } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/CancelCommand.java b/api/src/com/cloud/agent/api/CancelCommand.java index 76382736148..0692055ae5a 100644 --- a/api/src/com/cloud/agent/api/CancelCommand.java +++ b/api/src/com/cloud/agent/api/CancelCommand.java @@ -21,19 +21,19 @@ package com.cloud.agent.api; public class CancelCommand extends Command { protected long sequence; protected String reason; - + protected CancelCommand() { } - + public CancelCommand(long sequence, String reason) { this.sequence = sequence; this.reason = reason; } - + public long getSequence() { return sequence; } - + public String getReason() { return reason; } diff --git a/api/src/com/cloud/agent/api/ChangeAgentAnswer.java b/api/src/com/cloud/agent/api/ChangeAgentAnswer.java index 4b3f103a8e2..537eabef2b0 100644 --- a/api/src/com/cloud/agent/api/ChangeAgentAnswer.java +++ b/api/src/com/cloud/agent/api/ChangeAgentAnswer.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; public class ChangeAgentAnswer extends Answer { protected ChangeAgentAnswer() { } - + public ChangeAgentAnswer(ChangeAgentCommand cmd, boolean result) { super(cmd, result, null); } diff --git a/api/src/com/cloud/agent/api/ChangeAgentCommand.java b/api/src/com/cloud/agent/api/ChangeAgentCommand.java index 1b7f8c8507c..abdb60a619e 100644 --- a/api/src/com/cloud/agent/api/ChangeAgentCommand.java +++ b/api/src/com/cloud/agent/api/ChangeAgentCommand.java @@ -21,19 +21,19 @@ import com.cloud.host.Status.Event; public class ChangeAgentCommand extends Command { long agentId; Event event; - + protected ChangeAgentCommand() { } - + public ChangeAgentCommand(long agentId, Event event) { this.agentId = agentId; this.event = event; } - + public long getAgentId() { return agentId; } - + public Event getEvent() { return event; } diff --git a/api/src/com/cloud/agent/api/CheckHealthCommand.java b/api/src/com/cloud/agent/api/CheckHealthCommand.java index 5298f5a76c8..ff4227678a9 100644 --- a/api/src/com/cloud/agent/api/CheckHealthCommand.java +++ b/api/src/com/cloud/agent/api/CheckHealthCommand.java @@ -22,7 +22,7 @@ public class CheckHealthCommand extends Command { setWait(50); } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/CheckNetworkAnswer.java b/api/src/com/cloud/agent/api/CheckNetworkAnswer.java index 2188fa632d9..52825fd1140 100644 --- a/api/src/com/cloud/agent/api/CheckNetworkAnswer.java +++ b/api/src/com/cloud/agent/api/CheckNetworkAnswer.java @@ -20,7 +20,7 @@ public class CheckNetworkAnswer extends Answer { // indicate if agent reconnect is needed after setupNetworkNames command private boolean _reconnect; public CheckNetworkAnswer() {} - + public CheckNetworkAnswer(CheckNetworkCommand cmd, boolean result, String details, boolean reconnect) { super(cmd, result, details); @@ -34,5 +34,5 @@ public class CheckNetworkAnswer extends Answer { public boolean needReconnect() { return _reconnect; } - + } diff --git a/api/src/com/cloud/agent/api/CheckNetworkCommand.java b/api/src/com/cloud/agent/api/CheckNetworkCommand.java index b994614bc4c..8e1be56587c 100644 --- a/api/src/com/cloud/agent/api/CheckNetworkCommand.java +++ b/api/src/com/cloud/agent/api/CheckNetworkCommand.java @@ -23,18 +23,18 @@ import com.cloud.network.PhysicalNetworkSetupInfo; public class CheckNetworkCommand extends Command { List networkInfoList; - + public CheckNetworkCommand(List networkInfoList) { this.networkInfoList = networkInfoList; } - + public List getPhysicalNetworkInfoList() { return networkInfoList; } - + protected CheckNetworkCommand() { } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/CheckOnHostAnswer.java b/api/src/com/cloud/agent/api/CheckOnHostAnswer.java index 2a053fdad1b..e5325e3e9dd 100644 --- a/api/src/com/cloud/agent/api/CheckOnHostAnswer.java +++ b/api/src/com/cloud/agent/api/CheckOnHostAnswer.java @@ -19,10 +19,10 @@ package com.cloud.agent.api; public class CheckOnHostAnswer extends Answer { boolean determined; boolean alive; - + protected CheckOnHostAnswer() { } - + public CheckOnHostAnswer(CheckOnHostCommand cmd, Boolean alive, String details) { super(cmd, true, details); if (alive == null) { @@ -32,7 +32,7 @@ public class CheckOnHostAnswer extends Answer { this.alive = alive; } } - + public CheckOnHostAnswer(CheckOnHostCommand cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/CheckOnHostCommand.java b/api/src/com/cloud/agent/api/CheckOnHostCommand.java index 3aadebd464d..596a53299a8 100644 --- a/api/src/com/cloud/agent/api/CheckOnHostCommand.java +++ b/api/src/com/cloud/agent/api/CheckOnHostCommand.java @@ -24,17 +24,17 @@ public class CheckOnHostCommand extends Command { protected CheckOnHostCommand() { } - - + + public CheckOnHostCommand(Host host) { this.host = new HostTO(host); setWait(20); } - + public HostTO getHost() { return host; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/CheckRouterAnswer.java b/api/src/com/cloud/agent/api/CheckRouterAnswer.java index 7240ba10cd5..da8189f552b 100644 --- a/api/src/com/cloud/agent/api/CheckRouterAnswer.java +++ b/api/src/com/cloud/agent/api/CheckRouterAnswer.java @@ -23,10 +23,10 @@ public class CheckRouterAnswer extends Answer { public static final String ROUTER_IP = "router.ip"; RedundantState state; boolean isBumped; - + protected CheckRouterAnswer() { } - + public CheckRouterAnswer(CheckRouterCommand cmd, String details, boolean parse) { super(cmd, true, details); if (parse) { @@ -35,7 +35,7 @@ public class CheckRouterAnswer extends Answer { } } } - + public CheckRouterAnswer(CheckRouterCommand cmd, String details) { super(cmd, false, details); } @@ -61,11 +61,11 @@ public class CheckRouterAnswer extends Answer { } return true; } - + public void setState(RedundantState state) { this.state = state; } - + public RedundantState getState() { return state; } @@ -73,9 +73,9 @@ public class CheckRouterAnswer extends Answer { public boolean isBumped() { return isBumped; } - + public void setIsBumped(boolean isBumped) { this.isBumped = isBumped; } - + } diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java index ef3be811870..0e9db96fb36 100644 --- a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsAnswer.java @@ -5,7 +5,7 @@ // 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, @@ -23,12 +23,12 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { Map ipToConnected; Map ipToDetail; String details; - + protected CheckS2SVpnConnectionsAnswer() { ipToConnected = new HashMap(); ipToDetail = new HashMap(); } - + public CheckS2SVpnConnectionsAnswer(CheckS2SVpnConnectionsCommand cmd, boolean result, String details) { super(cmd, result, details); ipToConnected = new HashMap(); @@ -38,7 +38,7 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { parseDetails(details); } } - + protected void parseDetails(String details) { String[] lines = details.split("&"); for (String line : lines) { @@ -54,14 +54,14 @@ public class CheckS2SVpnConnectionsAnswer extends Answer { ipToDetail.put(ip, detail); } } - + public boolean isConnected(String ip) { if (this.getResult()) { return ipToConnected.get(ip); } return false; } - + public String getDetail(String ip) { if (this.getResult()) { return ipToDetail.get(ip); diff --git a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java index a736eab35ea..9cfb53b0828 100644 --- a/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java +++ b/api/src/com/cloud/agent/api/CheckS2SVpnConnectionsCommand.java @@ -5,7 +5,7 @@ // 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, @@ -22,17 +22,17 @@ import com.cloud.agent.api.routing.NetworkElementCommand; public class CheckS2SVpnConnectionsCommand extends NetworkElementCommand { List vpnIps; - + @Override public boolean executeInSequence() { return true; } - + public CheckS2SVpnConnectionsCommand(List vpnIps) { super(); this.vpnIps = vpnIps; } - + public List getVpnIps() { return vpnIps; } diff --git a/api/src/com/cloud/agent/api/CheckStateAnswer.java b/api/src/com/cloud/agent/api/CheckStateAnswer.java index 4864e390201..bf8ae0f330c 100755 --- a/api/src/com/cloud/agent/api/CheckStateAnswer.java +++ b/api/src/com/cloud/agent/api/CheckStateAnswer.java @@ -28,17 +28,17 @@ public class CheckStateAnswer extends Answer { public CheckStateAnswer(CheckStateCommand cmd, State state) { this(cmd, state, null); } - + public CheckStateAnswer(CheckStateCommand cmd, String details) { super(cmd, false, details); this.state = null; } - + public CheckStateAnswer(CheckStateCommand cmd, State state, String details) { super(cmd, true, details); this.state = state; } - + public State getState() { return state; } diff --git a/api/src/com/cloud/agent/api/CheckStateCommand.java b/api/src/com/cloud/agent/api/CheckStateCommand.java index 31c341db448..89fc7731f01 100755 --- a/api/src/com/cloud/agent/api/CheckStateCommand.java +++ b/api/src/com/cloud/agent/api/CheckStateCommand.java @@ -17,7 +17,7 @@ package com.cloud.agent.api; /** - * + * * */ public class CheckStateCommand extends Command { @@ -28,12 +28,12 @@ public class CheckStateCommand extends Command { public CheckStateCommand(String vmName) { this.vmName = vmName; } - + @Override public boolean executeInSequence() { return true; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java b/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java index 555b0ff79ed..3f0ffdbcea1 100644 --- a/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java +++ b/api/src/com/cloud/agent/api/CheckVirtualMachineAnswer.java @@ -19,33 +19,33 @@ package com.cloud.agent.api; import com.cloud.vm.VirtualMachine.State; public class CheckVirtualMachineAnswer extends Answer { - + Integer vncPort; State state; - - + + protected CheckVirtualMachineAnswer() { } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, State state, Integer vncPort, String detail) { super(cmd, true, detail); this.state = state; this.vncPort = vncPort; } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, State state, Integer vncPort) { this(cmd, state, vncPort, null); } - + public CheckVirtualMachineAnswer(CheckVirtualMachineCommand cmd, String detail) { super(cmd, false, detail); } - + public Integer getVncPort() { return vncPort; } - + public State getState() { return state; } diff --git a/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java b/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java index 9e63a935af1..62f4420a586 100644 --- a/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java +++ b/api/src/com/cloud/agent/api/CheckVirtualMachineCommand.java @@ -17,18 +17,18 @@ package com.cloud.agent.api; public class CheckVirtualMachineCommand extends Command { - + private String vmName; - + protected CheckVirtualMachineCommand() { - + } - + public CheckVirtualMachineCommand(String vmName) { this.vmName = vmName; setWait(20); } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java b/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java index 6302443b011..8b5172dfe2d 100644 --- a/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java +++ b/api/src/com/cloud/agent/api/CleanupNetworkRulesCmd.java @@ -20,22 +20,22 @@ package com.cloud.agent.api; public class CleanupNetworkRulesCmd extends Command implements CronCommand { private int interval = 10*60; - + @Override public boolean executeInSequence() { return false; } - - + + public CleanupNetworkRulesCmd(int intervalSecs) { super(); interval = intervalSecs; } - + public CleanupNetworkRulesCmd() { - + } diff --git a/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java b/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java index aa85c3d2ec7..ae65a529c52 100644 --- a/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java +++ b/api/src/com/cloud/agent/api/CleanupSnapshotBackupCommand.java @@ -26,20 +26,20 @@ public class CleanupSnapshotBackupCommand extends Command { private List validBackupUUIDs; protected CleanupSnapshotBackupCommand() { - + } - - /* - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + + /* + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field - * If you have better ideas on how to get it, you are welcome. - * @param validBackupUUID The VHD which are valid + * If you have better ideas on how to get it, you are welcome. + * @param validBackupUUID The VHD which are valid */ public CleanupSnapshotBackupCommand(String secondaryStoragePoolURL, Long dcId, Long accountId, Long volumeId, - List validBackupUUIDs) + List validBackupUUIDs) { this.secondaryStoragePoolURL = secondaryStoragePoolURL; this.dcId = dcId; @@ -67,9 +67,9 @@ public class CleanupSnapshotBackupCommand extends Command { public List getValidBackupUUIDs() { return validBackupUUIDs; } - + @Override public boolean executeInSequence() { return false; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/ClusterSyncAnswer.java b/api/src/com/cloud/agent/api/ClusterSyncAnswer.java index ea83109fbcb..99fee2a9dd1 100644 --- a/api/src/com/cloud/agent/api/ClusterSyncAnswer.java +++ b/api/src/com/cloud/agent/api/ClusterSyncAnswer.java @@ -25,31 +25,31 @@ public class ClusterSyncAnswer extends Answer { private long _clusterId; private HashMap> _newStates; private boolean _isExecuted=false; - + // this is here because a cron command answer is being sent twice // AgentAttache.processAnswers // AgentManagerImpl.notifyAnswersToMonitors public boolean isExceuted(){ return _isExecuted; } - + public void setExecuted(){ _isExecuted = true; } - + public ClusterSyncAnswer(long clusterId, HashMap> newStates){ _clusterId = clusterId; _newStates = newStates; result = true; } - + public long getClusterId() { return _clusterId; } - + public HashMap> getNewStates() { return _newStates; - } + } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/ClusterSyncCommand.java b/api/src/com/cloud/agent/api/ClusterSyncCommand.java index e3a0da57669..17dbbd8dd7b 100644 --- a/api/src/com/cloud/agent/api/ClusterSyncCommand.java +++ b/api/src/com/cloud/agent/api/ClusterSyncCommand.java @@ -21,10 +21,10 @@ public class ClusterSyncCommand extends Command implements CronCommand { int _interval; long _clusterId; - + public ClusterSyncCommand() { } - + public ClusterSyncCommand(int interval, long clusterId){ _interval = interval; _clusterId = clusterId; @@ -34,7 +34,7 @@ public class ClusterSyncCommand extends Command implements CronCommand { public int getInterval() { return _interval; } - + public long getClusterId() { return _clusterId; } @@ -43,5 +43,5 @@ public class ClusterSyncCommand extends Command implements CronCommand { public boolean executeInSequence() { return false; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/Command.java b/api/src/com/cloud/agent/api/Command.java index 4c3810ef2dd..9cd67495e04 100755 --- a/api/src/com/cloud/agent/api/Command.java +++ b/api/src/com/cloud/agent/api/Command.java @@ -23,9 +23,9 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; /** * implemented by classes that extends the Command class. Command specifies - * + * */ -public abstract class Command { +public abstract class Command { // allow command to carry over hypervisor or other environment related context info @LogLevel(Log4jLevel.Trace) @@ -63,7 +63,7 @@ public abstract class Command { public String getContextParam(String name) { return contextMap.get(name); } - + public boolean allowCaching() { return true; } diff --git a/api/src/com/cloud/agent/api/ComputeChecksumCommand.java b/api/src/com/cloud/agent/api/ComputeChecksumCommand.java index f0771a89de4..a2c88c440a8 100755 --- a/api/src/com/cloud/agent/api/ComputeChecksumCommand.java +++ b/api/src/com/cloud/agent/api/ComputeChecksumCommand.java @@ -26,12 +26,12 @@ public class ComputeChecksumCommand extends ssCommand { public ComputeChecksumCommand() { super(); } - + public ComputeChecksumCommand(String secUrl, String templatePath) { super(secUrl); this.templatePath = templatePath; - } - + } + public String getTemplatePath() { return templatePath; } diff --git a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java index 53a975f4874..9f50a2f3b53 100644 --- a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java +++ b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationAnswer.java @@ -14,75 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api; - -public class ConsoleAccessAuthenticationAnswer extends AgentControlAnswer { - +package com.cloud.agent.api; + +public class ConsoleAccessAuthenticationAnswer extends AgentControlAnswer { + private boolean _success; - + private boolean _isReauthenticating; private String _host; private int _port; - + private String _tunnelUrl; private String _tunnelSession; - + public ConsoleAccessAuthenticationAnswer() { _success = false; _isReauthenticating = false; - _port = 0; - } - - public ConsoleAccessAuthenticationAnswer(Command cmd, boolean success) { - super(cmd); - _success = success; - } - - public boolean succeeded() { - return _success; + _port = 0; } - + + public ConsoleAccessAuthenticationAnswer(Command cmd, boolean success) { + super(cmd); + _success = success; + } + + public boolean succeeded() { + return _success; + } + public void setSuccess(boolean value) { _success = value; } - + public boolean isReauthenticating() { return _isReauthenticating; } - + public void setReauthenticating(boolean value) { _isReauthenticating = value; } - + public String getHost() { return _host; } - + public void setHost(String host) { _host = host; } - + public int getPort() { return _port; } - + public void setPort(int port) { _port = port; } - + public String getTunnelUrl() { return _tunnelUrl; } - + public void setTunnelUrl(String tunnelUrl) { - _tunnelUrl = tunnelUrl; + _tunnelUrl = tunnelUrl; } - + public String getTunnelSession() { return _tunnelSession; } - + public void setTunnelSession(String tunnelSession) { _tunnelSession = tunnelSession; - } -} + } +} diff --git a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java index acbc181c5b1..bd8093c7e7b 100644 --- a/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java +++ b/api/src/com/cloud/agent/api/ConsoleAccessAuthenticationCommand.java @@ -17,19 +17,19 @@ package com.cloud.agent.api; public class ConsoleAccessAuthenticationCommand extends AgentControlCommand { - + private String _host; private String _port; private String _vmId; private String _sid; private String _ticket; - - private boolean _isReauthenticating; - + + private boolean _isReauthenticating; + public ConsoleAccessAuthenticationCommand() { - _isReauthenticating = false; - } - + _isReauthenticating = false; + } + public ConsoleAccessAuthenticationCommand(String host, String port, String vmId, String sid, String ticket) { _host = host; _port = port; @@ -37,32 +37,32 @@ public class ConsoleAccessAuthenticationCommand extends AgentControlCommand { _sid = sid; _ticket = ticket; } - + public String getHost() { return _host; } - + public String getPort() { return _port; } - + public String getVmId() { return _vmId; } - + public String getSid() { return _sid; } - + public String getTicket() { return _ticket; } - + public boolean isReauthenticating() { return _isReauthenticating; } - + public void setReauthenticating(boolean value) { _isReauthenticating = value; - } -} + } +} diff --git a/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java b/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java index d4b101ae0d1..ebb06b64dc6 100644 --- a/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java +++ b/api/src/com/cloud/agent/api/ConsoleProxyLoadReportCommand.java @@ -17,22 +17,22 @@ package com.cloud.agent.api; public class ConsoleProxyLoadReportCommand extends AgentControlCommand { - + private long _proxyVmId; private String _loadInfo; - + public ConsoleProxyLoadReportCommand() { } - + public ConsoleProxyLoadReportCommand(long proxyVmId, String loadInfo) { _proxyVmId = proxyVmId; _loadInfo = loadInfo; } - + public long getProxyVmId() { return _proxyVmId; } - + public String getLoadInfo() { return _loadInfo; } diff --git a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java index bf6f2604cdd..9e2680e49e6 100644 --- a/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreatePrivateTemplateFromSnapshotCommand.java @@ -16,31 +16,34 @@ // 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. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { private String origTemplateInstallPath; private Long newTemplateId; private String templateName; - + protected CreatePrivateTemplateFromSnapshotCommand() { - + } - + /** * Given the UUID of a backed up snapshot VHD file on the secondary storage, the execute of this command does * 1) Get the parent chain of this VHD all the way up to the root, say VHDList * 2) Copy all the files in the VHDlist to some temp location * 3) Coalesce all the VHDs to one VHD which contains all the data of the volume. This invokes the DeletePreviousBackupCommand for each VHD * 4) Rename the UUID of this VHD - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field * If you have better ideas on how to get it, you are welcome. * 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 + * @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, @@ -50,9 +53,9 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { String origTemplateInstallPath, Long newTemplateId, String templateName, - int wait) + 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; @@ -65,7 +68,7 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { public String getOrigTemplateInstallPath() { return origTemplateInstallPath; } - + public Long getNewTemplateId() { return newTemplateId; } @@ -76,4 +79,4 @@ public class CreatePrivateTemplateFromSnapshotCommand extends SnapshotCommand { public String getTemplateName() { return templateName; } -} \ No newline at end of file +} 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/CreateStoragePoolCommand.java b/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java index ecba6c232e2..7a4d768e5cb 100644 --- a/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/CreateStoragePoolCommand.java @@ -20,10 +20,10 @@ import com.cloud.storage.StoragePool; public class CreateStoragePoolCommand extends ModifyStoragePoolCommand { - + public CreateStoragePoolCommand() { } - + public CreateStoragePoolCommand(boolean add, StoragePool pool) { super(add, pool); } diff --git a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java index a57d6fa3c50..2f7cd9446e8 100644 --- a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class CreateVolumeFromSnapshotAnswer extends Answer { private String vdiUUID; - + protected CreateVolumeFromSnapshotAnswer() { - + } - + public CreateVolumeFromSnapshotAnswer(CreateVolumeFromSnapshotCommand cmd, boolean success, String result, String vdiUUID) { super(cmd, success, result); this.vdiUUID = vdiUUID; diff --git a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java index f0063299415..a19d34436f7 100644 --- a/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/CreateVolumeFromSnapshotCommand.java @@ -16,15 +16,17 @@ // 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. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { - + protected CreateVolumeFromSnapshotCommand() { - + } - + /** * Given the UUID of a backed up snapshot VHD file on the secondary storage, the execute of this command does * 1) Get the parent chain of this VHD all the way up to the root, say VHDList @@ -33,13 +35,14 @@ public class CreateVolumeFromSnapshotCommand extends SnapshotCommand { * 4) Rename the UUID of this VHD * 5) Move this VHD to primary storage * @param primaryStoragePoolNameLabel The primary storage Pool - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field * If you have better ideas on how to get it, you are welcome. * 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 + * @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); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java b/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java index 01de89163a8..3d62c507b89 100644 --- a/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java +++ b/api/src/com/cloud/agent/api/DeleteObjectFromSwiftCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class DeleteObjectFromSwiftCommand extends Command { @@ -31,9 +31,9 @@ public class DeleteObjectFromSwiftCommand extends Command { private String object; protected DeleteObjectFromSwiftCommand() { - + } - + public DeleteObjectFromSwiftCommand(SwiftTO swift, String container, String object) { this.swift = swift; this.container = container; @@ -58,4 +58,4 @@ public class DeleteObjectFromSwiftCommand extends Command { return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java b/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java index b458aa0edb0..9a895d8471a 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotBackupAnswer.java @@ -18,15 +18,15 @@ package com.cloud.agent.api; public class DeleteSnapshotBackupAnswer extends Answer { - + protected DeleteSnapshotBackupAnswer() { - + } public DeleteSnapshotBackupAnswer(DeleteSnapshotBackupCommand cmd, boolean success, String details) { super(cmd, success, details); } - - - + + + } diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java index 3fa8c2b7eb4..6114148954f 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotBackupCommand.java @@ -17,15 +17,17 @@ 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; /** * This command encapsulates a primitive operation which enables coalescing the backed up VHD snapshots on the secondary server - * This currently assumes that the secondary storage are mounted on the XenServer. + * This currently assumes that the secondary storage are mounted on the XenServer. */ public class DeleteSnapshotBackupCommand extends SnapshotCommand { @LogLevel(Log4jLevel.Off) private SwiftTO swift; + private S3TO s3; private Boolean all; public SwiftTO getSwift() { @@ -44,35 +46,40 @@ public class DeleteSnapshotBackupCommand extends SnapshotCommand { this.swift = swift; } + public S3TO getS3() { + return s3; + } + protected DeleteSnapshotBackupCommand() { } - + /** * Given 2 VHD files on the secondary storage which are linked in a parent chain as follows: * backupUUID = parent(childUUID) - * It gets another VHD + * It gets another VHD * previousBackupVHD = parent(backupUUID) - * + * * And * 1) it coalesces backupUuid into its parent. * 2) It deletes the VHD file corresponding to backupUuid * 3) It sets the parent VHD of childUUID to that of previousBackupUuid - * + * * It takes care of the cases when * 1) childUUID is null. - Step 3 is not done. - * 2) previousBackupUUID is null + * 2) previousBackupUUID is null * - Merge childUUID into its parent backupUUID * - Set the UUID of the resultant VHD to childUUID - * - Essentially we are deleting the oldest VHD file and setting the current oldest VHD to childUUID - * - * @param volumeName The name of the volume whose snapshot was taken (something like i-3-SV-ROOT) - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. + * - Essentially we are deleting the oldest VHD file and setting the current oldest VHD to childUUID + * + * @param volumeName The name of the volume whose snapshot was taken (something like i-3-SV-ROOT) + * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field - * If you have better ideas on how to get it, you are welcome. - * @param backupUUID The VHD which has to be deleted - * @param childUUID The child VHD file of the backup whose parent is reset to its grandparent. + * If you have better ideas on how to get it, you are welcome. + * @param backupUUID The VHD which has to be deleted + * @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); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java b/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java index 6879d2343e8..e2071d7f746 100644 --- a/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java +++ b/api/src/com/cloud/agent/api/DeleteSnapshotsDirCommand.java @@ -18,18 +18,18 @@ package com.cloud.agent.api; /** * This command encapsulates a primitive operation which enables coalescing the backed up VHD snapshots on the secondary server - * This currently assumes that the secondary storage are mounted on the XenServer. + * This currently assumes that the secondary storage are mounted on the XenServer. */ public class DeleteSnapshotsDirCommand extends Command { String secondaryStorageUrl; Long dcId; Long accountId; Long volumeId; - + protected DeleteSnapshotsDirCommand() { - + } - + public DeleteSnapshotsDirCommand(String secondaryStorageUrl, Long dcId, Long accountId, Long volumeId) { @@ -60,4 +60,4 @@ public class DeleteSnapshotsDirCommand extends Command { return volumeId; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java b/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java index 7fa60adb0fe..4618d59da26 100644 --- a/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/DeleteStoragePoolCommand.java @@ -23,20 +23,20 @@ import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.storage.StoragePool; public class DeleteStoragePoolCommand extends Command { - + StorageFilerTO pool; public static final String LOCAL_PATH_PREFIX="/mnt/"; String localPath; - + public DeleteStoragePoolCommand() { - + } - + public DeleteStoragePoolCommand(StoragePool pool, String localPath) { this.pool = new StorageFilerTO(pool); this.localPath = localPath; } - + public DeleteStoragePoolCommand(StoragePool pool) { this(pool, LOCAL_PATH_PREFIX + File.separator + UUID.nameUUIDFromBytes((pool.getHostAddress() + pool.getPath()).getBytes())); } @@ -48,7 +48,7 @@ public class DeleteStoragePoolCommand extends Command { public void setPool(StoragePool pool) { this.pool = new StorageFilerTO(pool); } - + @Override public boolean executeInSequence() { return false; @@ -57,5 +57,5 @@ public class DeleteStoragePoolCommand extends Command { public String getLocalPath() { return localPath; } - + } 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/FenceAnswer.java b/api/src/com/cloud/agent/api/FenceAnswer.java index 13ee3017660..7af18f5e7b3 100644 --- a/api/src/com/cloud/agent/api/FenceAnswer.java +++ b/api/src/com/cloud/agent/api/FenceAnswer.java @@ -20,15 +20,15 @@ public class FenceAnswer extends Answer { public FenceAnswer() { super(); } - + public FenceAnswer(FenceCommand cmd) { super(cmd, true, null); } - + public FenceAnswer(FenceCommand cmd, String details) { super(cmd, true, details); } - + public FenceAnswer(FenceCommand cmd, boolean result, String details) { super(cmd, result, details); } diff --git a/api/src/com/cloud/agent/api/FenceCommand.java b/api/src/com/cloud/agent/api/FenceCommand.java index 5ba293af1a3..a89194442ab 100644 --- a/api/src/com/cloud/agent/api/FenceCommand.java +++ b/api/src/com/cloud/agent/api/FenceCommand.java @@ -20,16 +20,16 @@ import com.cloud.host.Host; import com.cloud.vm.VirtualMachine; public class FenceCommand extends Command { - + public FenceCommand() { super(); } - + String vmName; String hostGuid; String hostIp; boolean inSeq; - + public FenceCommand(VirtualMachine vm, Host host) { super(); vmName = vm.getInstanceName(); @@ -37,19 +37,19 @@ public class FenceCommand extends Command { hostIp = host.getPrivateIpAddress(); inSeq = false; } - + public void setSeq(boolean inseq) { inSeq = inseq; } - + public String getVmName() { return vmName; } - + public String getHostGuid() { return hostGuid; } - + public String getHostIp() { return hostIp; } diff --git a/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java b/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java index 992b5076db7..7487b57c73c 100644 --- a/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java +++ b/api/src/com/cloud/agent/api/GetDomRVersionAnswer.java @@ -21,24 +21,24 @@ public class GetDomRVersionAnswer extends Answer { public static final String ROUTER_IP = "router.ip"; String templateVersion; String scriptsVersion; - + protected GetDomRVersionAnswer() { } - + public GetDomRVersionAnswer(GetDomRVersionCmd cmd, String details, String templateVersion, String scriptsVersion) { super(cmd, true, details); this.templateVersion = templateVersion; this.scriptsVersion = scriptsVersion; } - + public GetDomRVersionAnswer(GetDomRVersionCmd cmd, String details) { super(cmd, false, details); } - + public String getTemplateVersion() { return this.templateVersion; } - + public String getScriptsVersion() { return this.scriptsVersion; } diff --git a/api/src/com/cloud/agent/api/GetVncPortAnswer.java b/api/src/com/cloud/agent/api/GetVncPortAnswer.java index da464264c5b..5e94a18d3d9 100644 --- a/api/src/com/cloud/agent/api/GetVncPortAnswer.java +++ b/api/src/com/cloud/agent/api/GetVncPortAnswer.java @@ -19,29 +19,29 @@ package com.cloud.agent.api; public class GetVncPortAnswer extends Answer { String address; int port; - + protected GetVncPortAnswer() { } - + public GetVncPortAnswer(GetVncPortCommand cmd, int port) { super(cmd, true, null); this.port = port; } - + public GetVncPortAnswer(GetVncPortCommand cmd, String address, int port) { super(cmd, true, null); this.address = address; this.port = port; } - + public GetVncPortAnswer(GetVncPortCommand cmd, String details) { super(cmd, false, details); } - + public String getAddress() { return address; } - + public int getPort() { return port; } diff --git a/api/src/com/cloud/agent/api/GetVncPortCommand.java b/api/src/com/cloud/agent/api/GetVncPortCommand.java index cff787e595b..06165dce8ff 100644 --- a/api/src/com/cloud/agent/api/GetVncPortCommand.java +++ b/api/src/com/cloud/agent/api/GetVncPortCommand.java @@ -22,21 +22,21 @@ public class GetVncPortCommand extends Command { public GetVncPortCommand() { } - + public GetVncPortCommand(long id, String name) { this.id = id; this.name = name; } - + @Override public boolean executeInSequence() { return false; } - + public String getName() { return name; } - + public long getId() { return id; } diff --git a/api/src/com/cloud/agent/api/HostStatsEntry.java b/api/src/com/cloud/agent/api/HostStatsEntry.java index d34e0d76f5c..0d8cfb2d349 100644 --- a/api/src/com/cloud/agent/api/HostStatsEntry.java +++ b/api/src/com/cloud/agent/api/HostStatsEntry.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.host.HostStats; public class HostStatsEntry implements HostStats { - + long hostId; String entityType; double cpuUtilization; @@ -27,12 +27,12 @@ public class HostStatsEntry implements HostStats { double networkWriteKBs; double totalMemoryKBs; double freeMemoryKBs; - + public HostStatsEntry() { } - + public HostStatsEntry(long hostId,double cpuUtilization, double networkReadKBs, double networkWriteKBs, String entityType, - double totalMemoryKBs, double freeMemoryKBs, double xapiMemoryUsageKBs, double averageLoad) + double totalMemoryKBs, double freeMemoryKBs, double xapiMemoryUsageKBs, double averageLoad) { this.hostId = hostId; this.entityType = entityType; @@ -47,16 +47,16 @@ public class HostStatsEntry implements HostStats { public double getNetworkReadKBs() { return networkReadKBs; } - + public void setNetworkReadKBs(double networkReadKBs) { this.networkReadKBs = networkReadKBs; } - + @Override public double getNetworkWriteKBs() { return networkWriteKBs; } - + public void setNetworkWriteKBs(double networkWriteKBs) { this.networkWriteKBs = networkWriteKBs; } @@ -65,16 +65,16 @@ public class HostStatsEntry implements HostStats { public String getEntityType(){ return this.entityType; } - + public void setEntityType(String entityType){ this.entityType = entityType; } - + @Override public double getTotalMemoryKBs(){ return this.totalMemoryKBs; } - + public void setTotalMemoryKBs(double totalMemoryKBs){ this.totalMemoryKBs = totalMemoryKBs; } @@ -83,11 +83,11 @@ public class HostStatsEntry implements HostStats { public double getFreeMemoryKBs(){ return this.freeMemoryKBs; } - + public void setFreeMemoryKBs(double freeMemoryKBs){ this.freeMemoryKBs = freeMemoryKBs; } - + @Override public double getCpuUtilization() { return this.cpuUtilization; @@ -106,7 +106,7 @@ public class HostStatsEntry implements HostStats { public HostStats getHostStats() { return this; } - + public void setHostId(long hostId) { this.hostId = hostId; } diff --git a/api/src/com/cloud/agent/api/MaintainAnswer.java b/api/src/com/cloud/agent/api/MaintainAnswer.java index c36286934ee..dcfdab31708 100644 --- a/api/src/com/cloud/agent/api/MaintainAnswer.java +++ b/api/src/com/cloud/agent/api/MaintainAnswer.java @@ -18,28 +18,28 @@ package com.cloud.agent.api; public class MaintainAnswer extends Answer { boolean willMigrate; - + public MaintainAnswer() { } - + public MaintainAnswer(MaintainCommand cmd) { this(cmd, true, null); } - + public MaintainAnswer(MaintainCommand cmd, boolean willMigrate) { this(cmd, true, null); this.willMigrate = willMigrate; } - + public MaintainAnswer(MaintainCommand cmd, String details) { this(cmd, true, details); } - + public MaintainAnswer(MaintainCommand cmd, boolean result, String details) { super(cmd, result, details); this.willMigrate = true; } - + public boolean getMigrate() { return this.willMigrate; } diff --git a/api/src/com/cloud/agent/api/MaintainCommand.java b/api/src/com/cloud/agent/api/MaintainCommand.java index 654476a58b6..2a9b9a5ae7d 100644 --- a/api/src/com/cloud/agent/api/MaintainCommand.java +++ b/api/src/com/cloud/agent/api/MaintainCommand.java @@ -20,7 +20,7 @@ public class MaintainCommand extends Command { public MaintainCommand() { } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java b/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java index 6dd757505b1..e490bdf076b 100644 --- a/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/ManageSnapshotAnswer.java @@ -20,13 +20,13 @@ package com.cloud.agent.api; public class ManageSnapshotAnswer extends Answer { // For create Snapshot private String _snapshotPath; - + public ManageSnapshotAnswer() {} public ManageSnapshotAnswer(Command cmd, boolean success, String result) { super(cmd, success, result); } - + // For XenServer public ManageSnapshotAnswer(ManageSnapshotCommand cmd, long snapshotId, String snapshotPath, boolean success, String result) { super(cmd, success, result); @@ -36,5 +36,5 @@ public class ManageSnapshotAnswer extends Answer { public String getSnapshotPath() { return _snapshotPath; } - + } diff --git a/api/src/com/cloud/agent/api/ManageSnapshotCommand.java b/api/src/com/cloud/agent/api/ManageSnapshotCommand.java index 9a5f424167c..5effc542c5b 100644 --- a/api/src/com/cloud/agent/api/ManageSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/ManageSnapshotCommand.java @@ -25,9 +25,9 @@ public class ManageSnapshotCommand extends Command { // XXX: Anyway there is something called inheritance in Java public static String CREATE_SNAPSHOT = "-c"; public static String DESTROY_SNAPSHOT = "-d"; - + private String _commandSwitch; - + // Information about the volume that the snapshot is based on private String _volumePath = null; StorageFilerTO _pool; @@ -43,7 +43,7 @@ public class ManageSnapshotCommand extends Command { public ManageSnapshotCommand(long snapshotId, String volumePath, StoragePool pool, String preSnapshotPath ,String snapshotName, String vmName) { _commandSwitch = ManageSnapshotCommand.CREATE_SNAPSHOT; _volumePath = volumePath; - _pool = new StorageFilerTO(pool); + _pool = new StorageFilerTO(pool); _snapshotPath = preSnapshotPath; _snapshotName = snapshotName; _snapshotId = snapshotId; @@ -54,8 +54,8 @@ public class ManageSnapshotCommand extends Command { _commandSwitch = ManageSnapshotCommand.DESTROY_SNAPSHOT; _snapshotPath = snapshotPath; } - - + + @Override public boolean executeInSequence() { return false; @@ -64,15 +64,15 @@ public class ManageSnapshotCommand extends Command { public String getCommandSwitch() { return _commandSwitch; } - + public String getVolumePath() { return _volumePath; } - + public StorageFilerTO getPool() { return _pool; } - + public String getSnapshotPath() { return _snapshotPath; } @@ -84,9 +84,9 @@ public class ManageSnapshotCommand extends Command { public long getSnapshotId() { return _snapshotId; } - + public String getVmName() { return _vmName; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/MigrateAnswer.java b/api/src/com/cloud/agent/api/MigrateAnswer.java index 4b5dd19d06f..19d690a2d99 100644 --- a/api/src/com/cloud/agent/api/MigrateAnswer.java +++ b/api/src/com/cloud/agent/api/MigrateAnswer.java @@ -18,15 +18,15 @@ package com.cloud.agent.api; public class MigrateAnswer extends Answer { Integer vncPort = null; - + protected MigrateAnswer() { } - + public MigrateAnswer(MigrateCommand cmd, boolean result, String detail, Integer vncPort) { super(cmd, result, detail); this.vncPort = vncPort; } - + public Integer getVncPort() { return vncPort; } diff --git a/api/src/com/cloud/agent/api/MigrateCommand.java b/api/src/com/cloud/agent/api/MigrateCommand.java index 18a2be19d88..5042b8c1971 100644 --- a/api/src/com/cloud/agent/api/MigrateCommand.java +++ b/api/src/com/cloud/agent/api/MigrateCommand.java @@ -25,29 +25,29 @@ public class MigrateCommand extends Command { protected MigrateCommand() { } - + public MigrateCommand(String vmName, String destIp, boolean isWindows) { this.vmName = vmName; this.destIp = destIp; this.isWindows = isWindows; } - + public boolean isWindows() { return isWindows; } - + public String getDestinationIp() { return destIp; } - + public String getVmName() { return vmName; } - + public void setHostGuid(String guid) { this.hostGuid = guid; } - + public String getHostGuid() { return this.hostGuid; } diff --git a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java index a8ab78dec99..df77985248f 100644 --- a/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java +++ b/api/src/com/cloud/agent/api/ModifyStoragePoolAnswer.java @@ -30,13 +30,13 @@ public class ModifyStoragePoolAnswer extends Answer { public ModifyStoragePoolAnswer(ModifyStoragePoolCommand cmd, long capacityBytes, long availableBytes, Map tInfo) { super(cmd); this.result = true; - this.poolInfo = new StoragePoolInfo(null, - cmd.getPool().getHost(), cmd.getPool().getPath(), cmd.getLocalPath(), + this.poolInfo = new StoragePoolInfo(null, + cmd.getPool().getHost(), cmd.getPool().getPath(), cmd.getLocalPath(), cmd.getPool().getType(), capacityBytes, availableBytes ); - + this.templateInfo = tInfo; } - + public StoragePoolInfo getPoolInfo() { return poolInfo; } diff --git a/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java b/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java index 04f14e3de8f..8bc956d54d0 100644 --- a/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java +++ b/api/src/com/cloud/agent/api/ModifyStoragePoolCommand.java @@ -23,25 +23,25 @@ import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.storage.StoragePool; public class ModifyStoragePoolCommand extends Command { - + boolean add; StorageFilerTO pool; String localPath; String [] options; public static final String LOCAL_PATH_PREFIX="/mnt/"; - + public ModifyStoragePoolCommand() { - + } - + public ModifyStoragePoolCommand(boolean add, StoragePool pool, String localPath) { this.add = add; this.pool = new StorageFilerTO(pool); this.localPath = localPath; } - + public ModifyStoragePoolCommand(boolean add, StoragePool pool) { this(add, pool, LOCAL_PATH_PREFIX + File.separator + UUID.nameUUIDFromBytes((pool.getHostAddress() + pool.getPath()).getBytes())); } @@ -53,11 +53,11 @@ public class ModifyStoragePoolCommand extends Command { public void setPool(StoragePool pool) { this.pool = new StorageFilerTO(pool); } - + public boolean getAdd() { return add; } - + @Override public boolean executeInSequence() { return false; @@ -71,5 +71,5 @@ public class ModifyStoragePoolCommand extends Command { this.options = options; } - + } diff --git a/api/src/com/cloud/agent/api/NetworkUsageAnswer.java b/api/src/com/cloud/agent/api/NetworkUsageAnswer.java index 7d5d49b3a71..fd8ebda4d2a 100644 --- a/api/src/com/cloud/agent/api/NetworkUsageAnswer.java +++ b/api/src/com/cloud/agent/api/NetworkUsageAnswer.java @@ -33,7 +33,7 @@ public class NetworkUsageAnswer extends Answer { this.bytesSent = bytesSent; routerName = cmd.getDomRName(); } - + public NetworkUsageAnswer(Command command, Exception e) { super(command, e); } diff --git a/api/src/com/cloud/agent/api/NetworkUsageCommand.java b/api/src/com/cloud/agent/api/NetworkUsageCommand.java index acb23cf61d8..6cbf93b3ef2 100644 --- a/api/src/com/cloud/agent/api/NetworkUsageCommand.java +++ b/api/src/com/cloud/agent/api/NetworkUsageCommand.java @@ -57,7 +57,7 @@ public class NetworkUsageCommand extends Command { this.option = "create"; this.vpcCIDR = vpcCIDR; } - + public NetworkUsageCommand(String privateIP, String domRName, String option, boolean forVpc, String gatewayIP) { this.privateIP = privateIP; @@ -66,7 +66,7 @@ public class NetworkUsageCommand extends Command { this.gatewayIP = gatewayIP; this.option = option; } - + public String getPrivateIP() { return privateIP; } diff --git a/api/src/com/cloud/agent/api/PingAnswer.java b/api/src/com/cloud/agent/api/PingAnswer.java index 388d67db0fb..d9ed89cc5df 100644 --- a/api/src/com/cloud/agent/api/PingAnswer.java +++ b/api/src/com/cloud/agent/api/PingAnswer.java @@ -21,7 +21,7 @@ public class PingAnswer extends Answer { protected PingAnswer() { } - + public PingAnswer(PingCommand cmd) { super(cmd); _command = cmd; diff --git a/api/src/com/cloud/agent/api/PingCommand.java b/api/src/com/cloud/agent/api/PingCommand.java index 3b3ca61685a..8d9681f9fa9 100755 --- a/api/src/com/cloud/agent/api/PingCommand.java +++ b/api/src/com/cloud/agent/api/PingCommand.java @@ -21,23 +21,23 @@ import com.cloud.host.Host; public class PingCommand extends Command { Host.Type hostType; long hostId; - + protected PingCommand() { } - + public PingCommand(Host.Type type, long id) { hostType = type; hostId = id; } - + public Host.Type getHostType() { return hostType; } - + public long getHostId() { return hostId; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/PingRoutingCommand.java b/api/src/com/cloud/agent/api/PingRoutingCommand.java index eebe041ff21..e25ac62786f 100755 --- a/api/src/com/cloud/agent/api/PingRoutingCommand.java +++ b/api/src/com/cloud/agent/api/PingRoutingCommand.java @@ -25,15 +25,15 @@ public class PingRoutingCommand extends PingCommand { Map newStates; boolean _gatewayAccessible = true; boolean _vnetAccessible = true; - + protected PingRoutingCommand() { } - + public PingRoutingCommand(Host.Type type, long id, Map states) { super(type, id); this.newStates = states; } - + public Map getNewStates() { return newStates; } diff --git a/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java b/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java index 5842f385402..d44987b20fd 100644 --- a/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java +++ b/api/src/com/cloud/agent/api/PingRoutingWithOvsCommand.java @@ -25,17 +25,17 @@ import com.cloud.vm.VirtualMachine.State; public class PingRoutingWithOvsCommand extends PingRoutingCommand { List> states; - + protected PingRoutingWithOvsCommand() { super(); } - + public PingRoutingWithOvsCommand(Host.Type type, long id, Map states, List> ovsStates) { super(type, id, states); this.states = ovsStates; } - + public List> getStates() { return states; } diff --git a/api/src/com/cloud/agent/api/PingStorageCommand.java b/api/src/com/cloud/agent/api/PingStorageCommand.java index 963bc7b2a6b..438ab507852 100755 --- a/api/src/com/cloud/agent/api/PingStorageCommand.java +++ b/api/src/com/cloud/agent/api/PingStorageCommand.java @@ -25,12 +25,12 @@ public class PingStorageCommand extends PingCommand { protected PingStorageCommand() { } - + public PingStorageCommand(Host.Type type, long id, Map changes) { super(type, id); this.changes = changes; } - + public Map getChanges() { return changes; } diff --git a/api/src/com/cloud/agent/api/PlugNicCommand.java b/api/src/com/cloud/agent/api/PlugNicCommand.java index aa5141eab8e..b896e4540cb 100644 --- a/api/src/com/cloud/agent/api/PlugNicCommand.java +++ b/api/src/com/cloud/agent/api/PlugNicCommand.java @@ -19,22 +19,22 @@ package com.cloud.agent.api; import com.cloud.agent.api.to.NicTO; public class PlugNicCommand extends Command { - + NicTO nic; String instanceName; - + public NicTO getNic() { return nic; } - + @Override public boolean executeInSequence() { return true; } - + protected PlugNicCommand() { } - + public PlugNicCommand(NicTO nic, String instanceName) { this.nic = nic; this.instanceName = instanceName; diff --git a/api/src/com/cloud/agent/api/PoolEjectCommand.java b/api/src/com/cloud/agent/api/PoolEjectCommand.java index faea30e3f86..3085042eeb4 100644 --- a/api/src/com/cloud/agent/api/PoolEjectCommand.java +++ b/api/src/com/cloud/agent/api/PoolEjectCommand.java @@ -18,22 +18,22 @@ package com.cloud.agent.api; public class PoolEjectCommand extends Command { private String hostuuid; - + public String getHostuuid() { return hostuuid; } - + public void setHostuuid(String hostuuid) { this.hostuuid = hostuuid; } public PoolEjectCommand() { super(); } - public PoolEjectCommand(String hostuuid) { + public PoolEjectCommand(String hostuuid) { super(); setHostuuid(hostuuid); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java b/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java index bbd63cc2cea..1b215bc086e 100644 --- a/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java +++ b/api/src/com/cloud/agent/api/PrepareForMigrationAnswer.java @@ -19,15 +19,15 @@ package com.cloud.agent.api; public class PrepareForMigrationAnswer extends Answer { protected PrepareForMigrationAnswer() { } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd, String detail) { super(cmd, false, detail); } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd, Exception ex) { super(cmd, ex); } - + public PrepareForMigrationAnswer(PrepareForMigrationCommand cmd) { super(cmd, true, null); } diff --git a/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java b/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java index e10bca0ba72..c0e136883f9 100644 --- a/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java +++ b/api/src/com/cloud/agent/api/PrepareForMigrationCommand.java @@ -20,18 +20,18 @@ import com.cloud.agent.api.to.VirtualMachineTO; public class PrepareForMigrationCommand extends Command { VirtualMachineTO vm; - + protected PrepareForMigrationCommand() { } - + public PrepareForMigrationCommand(VirtualMachineTO vm) { this.vm = vm; } - + public VirtualMachineTO getVirtualMachine() { return vm; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java b/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java index eda0fd9740f..0c80bfa6f08 100755 --- a/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java +++ b/api/src/com/cloud/agent/api/PrepareOCFS2NodesCommand.java @@ -23,7 +23,7 @@ import com.cloud.utils.Ternary; public class PrepareOCFS2NodesCommand extends Command { List> nodes; String clusterName; - + @Override public boolean executeInSequence() { return true; @@ -33,11 +33,11 @@ public class PrepareOCFS2NodesCommand extends Command { this.nodes = nodes; this.clusterName = clusterName; } - + public List> getNodes() { return nodes; } - + public String getClusterName() { return clusterName; } diff --git a/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java b/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java index 3442c7715e1..45cd4b30ef1 100755 --- a/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java +++ b/api/src/com/cloud/agent/api/PropagateResourceEventCommand.java @@ -21,24 +21,24 @@ import com.cloud.resource.ResourceState; public class PropagateResourceEventCommand extends Command { long hostId; ResourceState.Event event; - + protected PropagateResourceEventCommand() { - + } - + public PropagateResourceEventCommand(long hostId, ResourceState.Event event) { this.hostId = hostId; this.event = event; } - + public long getHostId() { return hostId; } - + public ResourceState.Event getEvent() { return event; } - + @Override public boolean executeInSequence() { // TODO Auto-generated method stub diff --git a/api/src/com/cloud/agent/api/ReadyAnswer.java b/api/src/com/cloud/agent/api/ReadyAnswer.java index 3f8172c39e5..b5dd0b7d360 100644 --- a/api/src/com/cloud/agent/api/ReadyAnswer.java +++ b/api/src/com/cloud/agent/api/ReadyAnswer.java @@ -19,11 +19,11 @@ package com.cloud.agent.api; public class ReadyAnswer extends Answer { protected ReadyAnswer() { } - + public ReadyAnswer(ReadyCommand cmd) { super(cmd, true, null); } - + public ReadyAnswer(ReadyCommand cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/ReadyCommand.java b/api/src/com/cloud/agent/api/ReadyCommand.java index b2502964c91..c6ca799a132 100644 --- a/api/src/com/cloud/agent/api/ReadyCommand.java +++ b/api/src/com/cloud/agent/api/ReadyCommand.java @@ -23,27 +23,36 @@ public class ReadyCommand extends Command { } private Long dcId; - + private Long hostId; + public ReadyCommand(Long dcId) { super(); this.dcId = dcId; } - + + public ReadyCommand(Long dcId, Long hostId) { + this(dcId); + this.hostId = hostId; + } + public void setDetails(String details) { _details = details; } - + public String getDetails() { return _details; } - + public Long getDataCenterId() { return dcId; } - + @Override public boolean executeInSequence() { return true; } + public Long getHostId() { + return hostId; + } } diff --git a/api/src/com/cloud/agent/api/RebootAnswer.java b/api/src/com/cloud/agent/api/RebootAnswer.java index da53b4fb1a3..244bf1e21ce 100644 --- a/api/src/com/cloud/agent/api/RebootAnswer.java +++ b/api/src/com/cloud/agent/api/RebootAnswer.java @@ -18,24 +18,24 @@ package com.cloud.agent.api; public class RebootAnswer extends Answer { Integer vncPort; - + protected RebootAnswer() { } - + public RebootAnswer(RebootCommand cmd, String details, Integer vncport) { super(cmd, true, details); this.vncPort = vncport; } - + public RebootAnswer(RebootCommand cmd, String details, boolean success) { super(cmd, success, details); this.vncPort = null; } - + public RebootAnswer(RebootCommand cmd, Exception e) { super(cmd, e); } - + public Integer getVncPort() { return vncPort; } diff --git a/api/src/com/cloud/agent/api/RebootCommand.java b/api/src/com/cloud/agent/api/RebootCommand.java index 2925e2a8a2b..299e61b76af 100755 --- a/api/src/com/cloud/agent/api/RebootCommand.java +++ b/api/src/com/cloud/agent/api/RebootCommand.java @@ -20,25 +20,25 @@ import com.cloud.vm.VirtualMachine; public class RebootCommand extends Command { String vmName; - + protected RebootCommand() { } - + public RebootCommand(VirtualMachine vm) { vmName = vm.getInstanceName(); } - + public RebootCommand(String vmName) { this.vmName = vmName; } - + public String getVmName() { return vmName; } - + @Override public boolean executeInSequence() { return true; } - + } diff --git a/api/src/com/cloud/agent/api/RebootRouterCommand.java b/api/src/com/cloud/agent/api/RebootRouterCommand.java index bf5d866b0dc..c5027b326a3 100644 --- a/api/src/com/cloud/agent/api/RebootRouterCommand.java +++ b/api/src/com/cloud/agent/api/RebootRouterCommand.java @@ -18,7 +18,7 @@ package com.cloud.agent.api; public class RebootRouterCommand extends RebootCommand { - + protected String privateIp; protected RebootRouterCommand() { diff --git a/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java b/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java index 276ed065182..41a779b7d7a 100755 --- a/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageFirewallCfgCommand.java @@ -33,7 +33,7 @@ public class SecStorageFirewallCfgCommand extends Command { this.intf = intf; } public PortConfig() { - + } public boolean isAdd() { return add; @@ -48,28 +48,28 @@ public class SecStorageFirewallCfgCommand extends Command { return intf; } } - + private List portConfigs = new ArrayList(); - private boolean isAppendAIp = false; - + private boolean isAppendAIp = false; + public SecStorageFirewallCfgCommand() { - + } - + public SecStorageFirewallCfgCommand(boolean isAppend) { this.isAppendAIp = isAppend; - } - + } + public void addPortConfig(String sourceIp, String port, boolean add, String intf) { PortConfig pc = new PortConfig(sourceIp, port, add, intf); this.portConfigs.add(pc); - + } public boolean getIsAppendAIp() { return isAppendAIp; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java b/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java index 494bce53c3b..bb0c01652d5 100644 --- a/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java +++ b/api/src/com/cloud/agent/api/SecStorageSetupAnswer.java @@ -20,12 +20,12 @@ public class SecStorageSetupAnswer extends Answer { private String _dir; protected SecStorageSetupAnswer() { } - + public SecStorageSetupAnswer(String dir) { super(null, true, "success"); this._dir = dir; } - + public String get_dir() { return _dir; } diff --git a/api/src/com/cloud/agent/api/SecStorageSetupCommand.java b/api/src/com/cloud/agent/api/SecStorageSetupCommand.java index 208b8a6cd5b..50c06cffa43 100644 --- a/api/src/com/cloud/agent/api/SecStorageSetupCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageSetupCommand.java @@ -21,7 +21,7 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; public class SecStorageSetupCommand extends Command { private String secUrl; private Certificates certs; - + public static class Certificates { @LogLevel(Log4jLevel.Off) private String privKey; @@ -29,30 +29,30 @@ public class SecStorageSetupCommand extends Command { private String privCert; @LogLevel(Log4jLevel.Off) private String certChain; - + public Certificates() { - + } - + public Certificates(String prvKey, String privCert, String certChain) { this.privKey = prvKey; this.privCert = privCert; this.certChain = certChain; } - + public String getPrivKey() { return this.privKey; } - + public String getPrivCert() { return this.privCert; } - + public String getCertChain() { return this.certChain; } } - + public SecStorageSetupCommand() { super(); } @@ -62,7 +62,7 @@ public class SecStorageSetupCommand extends Command { this.secUrl = secUrl; this.certs = certs; } - + @Override public boolean executeInSequence() { return true; @@ -71,13 +71,13 @@ public class SecStorageSetupCommand extends Command { public String getSecUrl() { return secUrl; } - + public Certificates getCerts() { return this.certs; } public void setSecUrl(String secUrl) { this.secUrl = secUrl; - + } } diff --git a/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java b/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java index 03f2321a355..be977097f06 100644 --- a/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java +++ b/api/src/com/cloud/agent/api/SecStorageVMSetupCommand.java @@ -20,11 +20,11 @@ public class SecStorageVMSetupCommand extends Command { String [] allowedInternalSites = new String[0]; String copyUserName; String copyPassword; - + public SecStorageVMSetupCommand() { super(); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java b/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java index 00cdbe83ffd..144fea2ae87 100644 --- a/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java +++ b/api/src/com/cloud/agent/api/SecurityGroupRuleAnswer.java @@ -26,24 +26,24 @@ public class SecurityGroupRuleAnswer extends Answer { Long logSequenceNumber = null; Long vmId = null; FailureReason reason = FailureReason.NONE; - - + + protected SecurityGroupRuleAnswer() { } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd) { super(cmd); this.logSequenceNumber = cmd.getSeqNum(); this.vmId = cmd.getVmId(); } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail) { super(cmd, result, detail); this.logSequenceNumber = cmd.getSeqNum(); this.vmId = cmd.getVmId(); reason = FailureReason.PROGRAMMING_FAILED; } - + public SecurityGroupRuleAnswer(SecurityGroupRulesCmd cmd, boolean result, String detail, FailureReason r) { super(cmd, result, detail); this.logSequenceNumber = cmd.getSeqNum(); diff --git a/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java b/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java index 32550df8448..affad1f9b9d 100644 --- a/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java +++ b/api/src/com/cloud/agent/api/SecurityGroupRulesCmd.java @@ -126,7 +126,7 @@ public class SecurityGroupRulesCmd extends Command { public void setEgressRuleSet(IpPortAndProto[] egressRuleSet) { this.egressRuleSet = egressRuleSet; } - + public String getGuestIp() { return guestIp; } @@ -156,15 +156,15 @@ public class SecurityGroupRulesCmd extends Command { } return ruleBuilder.toString(); } - + //convert cidrs in the form "a.b.c.d/e" to "hexvalue of 32bit ip/e" private String compressCidr(String cidr) { String [] toks = cidr.split("/"); long ipnum = NetUtils.ip2Long(toks[0]); return Long.toHexString(ipnum) + "/" + toks[1]; } - - + + public String stringifyCompressedRules() { StringBuilder ruleBuilder = new StringBuilder(); for (SecurityGroupRulesCmd.IpPortAndProto ipPandP : getIngressRuleSet()) { @@ -187,7 +187,7 @@ public class SecurityGroupRulesCmd extends Command { } return ruleBuilder.toString(); } - + /* * Compress the security group rules using zlib compression to allow the call to the hypervisor * to scale beyond 8k cidrs. @@ -243,7 +243,7 @@ public class SecurityGroupRulesCmd extends Command { public Long getVmId() { return vmId; } - + public int getTotalNumCidrs() { //useful for logging int count = 0; @@ -255,11 +255,11 @@ public class SecurityGroupRulesCmd extends Command { } return count; } - + public void setMsId(long msId) { this.msId = msId; } - + public Long getMsId() { return msId; } diff --git a/api/src/com/cloud/agent/api/SetupAnswer.java b/api/src/com/cloud/agent/api/SetupAnswer.java index beee79fb84c..97252a2708e 100644 --- a/api/src/com/cloud/agent/api/SetupAnswer.java +++ b/api/src/com/cloud/agent/api/SetupAnswer.java @@ -33,5 +33,5 @@ public class SetupAnswer extends Answer { public boolean needReconnect() { return _reconnect; } - + } diff --git a/api/src/com/cloud/agent/api/SetupCommand.java b/api/src/com/cloud/agent/api/SetupCommand.java index 0397813b9aa..ee43c5933da 100644 --- a/api/src/com/cloud/agent/api/SetupCommand.java +++ b/api/src/com/cloud/agent/api/SetupCommand.java @@ -23,7 +23,7 @@ public class SetupCommand extends Command { HostEnvironment env; boolean multipath; boolean needSetup; - + public boolean needSetup() { return needSetup; } @@ -37,18 +37,18 @@ public class SetupCommand extends Command { this.multipath = false; this.needSetup = false; } - + public HostEnvironment getEnvironment() { return env; } - + protected SetupCommand() { } - + public void setMultipathOn() { this.multipath = true; } - + public boolean useMultipath() { return multipath; } diff --git a/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java b/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java index 10dab557bf5..2cf5bf8ffaa 100644 --- a/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java +++ b/api/src/com/cloud/agent/api/SetupGuestNetworkCommand.java @@ -28,7 +28,7 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand{ Integer priority; boolean add = true; NicTO nic; - + public NicTO getNic() { return nic; } @@ -53,12 +53,12 @@ public class SetupGuestNetworkCommand extends NetworkElementCommand{ public boolean executeInSequence() { return true; } - + protected SetupGuestNetworkCommand() { } - - - public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority, + + + public SetupGuestNetworkCommand(String dhcpRange, String networkDomain, boolean isRedundant, Integer priority, String defaultDns1, String defaultDns2, boolean add, NicTO nic) { this.dhcpRange = dhcpRange; this.networkDomain = networkDomain; diff --git a/api/src/com/cloud/agent/api/ShutdownCommand.java b/api/src/com/cloud/agent/api/ShutdownCommand.java index fa66e34b176..5412f35c583 100644 --- a/api/src/com/cloud/agent/api/ShutdownCommand.java +++ b/api/src/com/cloud/agent/api/ShutdownCommand.java @@ -24,31 +24,31 @@ public class ShutdownCommand extends Command { public static final String Update = "update"; public static final String Unknown = "unknown"; public static final String DeleteHost = "deleteHost"; - + private String reason; private String detail; protected ShutdownCommand() { super(); } - + public ShutdownCommand(String reason, String detail) { super(); this.reason = reason; this.detail = detail; } - + /** - * @return return the reason the agent shutdown. If Unknown, call getDetail() for any details. + * @return return the reason the agent shutdown. If Unknown, call getDetail() for any details. */ public String getReason() { return reason; } - + public String getDetail() { return detail; } - + @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 90eae8e38bb..d8abeb62371 100644 --- a/api/src/com/cloud/agent/api/SnapshotCommand.java +++ b/api/src/com/cloud/agent/api/SnapshotCommand.java @@ -16,39 +16,45 @@ // 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. + * 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; - private Long dcId; - private Long accountId; - private Long volumeId; + private Long dcId; + private Long accountId; + private Long volumeId; private String volumePath; - + protected SnapshotCommand() { - + } - + /** - * @param primaryStoragePoolNameLabel The primary storage Pool - * @param snapshotUuid The UUID of the snapshot which is going to be backed up - * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. - * In the code, it is present as: In the vmops.host_details table, there is a field mount.parent. This is the value of that field - * If you have better ideas on how to get it, you are welcome. + * @param primaryStoragePoolNameLabel + * The primary storage Pool + * @param snapshotUuid + * The UUID of the snapshot which is going to be backed up + * @param secondaryStoragePoolURL + * This is what shows up in the UI when you click on Secondary + * storage. In the code, it is present as: In the + * vmops.host_details table, there is a field mount.parent. This + * is the value of that field If you have better ideas on how to + * get it, you are welcome. */ - public SnapshotCommand(String primaryStoragePoolNameLabel, - String secondaryStorageUrl, - String snapshotUuid, - String snapshotName, - Long dcId, - Long accountId, - Long volumeId) - { - this.primaryStoragePoolNameLabel = primaryStoragePoolNameLabel; + public SnapshotCommand(StoragePool pool, + String secondaryStorageUrl, String snapshotUuid, + String snapshotName, Long dcId, Long accountId, Long volumeId) { + this.primaryStoragePoolNameLabel = pool.getUuid(); + this.primaryPool = new StorageFilerTO(pool); this.snapshotUuid = snapshotUuid; this.secondaryStorageUrl = secondaryStorageUrl; this.dcId = dcId; @@ -64,17 +70,24 @@ public class SnapshotCommand extends Command { return primaryStoragePoolNameLabel; } + /** + * @return the primaryPool + */ + public StorageFilerTO getPool() { + return primaryPool; + } + /** * @return the snapshotUuid */ public String getSnapshotUuid() { return snapshotUuid; } - + public String getSnapshotName() { - return snapshotName; + return snapshotName; } - + /** * @return the secondaryStoragePoolURL */ @@ -82,7 +95,6 @@ public class SnapshotCommand extends Command { return secondaryStorageUrl; } - public Long getDataCenterId() { return dcId; } @@ -94,13 +106,13 @@ public class SnapshotCommand extends Command { public Long getVolumeId() { return volumeId; } - + public String getVolumePath() { - return volumePath; + return volumePath; } - + public void setVolumePath(String path) { - volumePath = path; + volumePath = path; } /** @@ -111,4 +123,4 @@ public class SnapshotCommand extends Command { return false; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/StartAnswer.java b/api/src/com/cloud/agent/api/StartAnswer.java index d4a3f63bc96..922d060cfae 100644 --- a/api/src/com/cloud/agent/api/StartAnswer.java +++ b/api/src/com/cloud/agent/api/StartAnswer.java @@ -21,20 +21,20 @@ import com.cloud.agent.api.to.VirtualMachineTO; public class StartAnswer extends Answer { VirtualMachineTO vm; String host_guid; - + protected StartAnswer() { } - + public StartAnswer(StartCommand cmd, String msg) { super(cmd, false, msg); this.vm = cmd.getVirtualMachine(); } - + public StartAnswer(StartCommand cmd, Exception e) { super(cmd, false, e.getMessage()); this.vm = cmd.getVirtualMachine(); } - + public StartAnswer(StartCommand cmd) { super(cmd, true, null); this.vm = cmd.getVirtualMachine(); @@ -46,7 +46,7 @@ public class StartAnswer extends Answer { this.vm = cmd.getVirtualMachine(); this.host_guid = guid; } - + public VirtualMachineTO getVirtualMachine() { return vm; } diff --git a/api/src/com/cloud/agent/api/StartCommand.java b/api/src/com/cloud/agent/api/StartCommand.java index 4d871389836..ec707d6e851 100644 --- a/api/src/com/cloud/agent/api/StartCommand.java +++ b/api/src/com/cloud/agent/api/StartCommand.java @@ -28,12 +28,12 @@ public class StartCommand extends Command { public VirtualMachineTO getVirtualMachine() { return vm; } - + @Override public boolean executeInSequence() { return true; } - + protected StartCommand() { } diff --git a/api/src/com/cloud/agent/api/StartupAnswer.java b/api/src/com/cloud/agent/api/StartupAnswer.java index a078c2dc4df..c0925cbdd6f 100755 --- a/api/src/com/cloud/agent/api/StartupAnswer.java +++ b/api/src/com/cloud/agent/api/StartupAnswer.java @@ -20,24 +20,24 @@ package com.cloud.agent.api; public class StartupAnswer extends Answer { long hostId; int pingInterval; - + protected StartupAnswer() { } - + public StartupAnswer(StartupCommand cmd, long hostId, int pingInterval) { super(cmd); this.hostId = hostId; this.pingInterval = pingInterval; } - + public StartupAnswer(StartupCommand cmd, String details) { super(cmd, false, details); } - + public long getHostId() { return hostId; } - + public int getPingInterval() { return pingInterval; } diff --git a/api/src/com/cloud/agent/api/StartupCommand.java b/api/src/com/cloud/agent/api/StartupCommand.java index 6088beac785..dd2d3907e7b 100755 --- a/api/src/com/cloud/agent/api/StartupCommand.java +++ b/api/src/com/cloud/agent/api/StartupCommand.java @@ -43,11 +43,11 @@ public class StartupCommand extends Command { String agentTag; String resourceName; String gatewayIpAddress; - + public StartupCommand(Host.Type type) { this.type = type; } - + public StartupCommand(Long id, Host.Type type, String name, String dataCenter, String pod, String guid, String version) { super(); this.id = id; @@ -58,48 +58,48 @@ public class StartupCommand extends Command { this.version = version; this.type = type; } - + public StartupCommand(Long id, Host.Type type, String name, String dataCenter, String pod, String guid, String version, String gatewayIpAddress) { this(id, type, name, dataCenter, pod, guid, version); this.gatewayIpAddress = gatewayIpAddress; - } - + } + public Host.Type getHostType() { return type; } - + public void setHostType(Host.Type type) { this.type = type; } - + public String getIqn() { return iqn; } - + public void setCluster(String cluster) { this.cluster = cluster; } - + public String getCluster() { return cluster; } - + public void setIqn(String iqn) { this.iqn = iqn; } - + public String getDataCenter() { return dataCenter; } - + public String getPod() { return pod; } - + public Long getId() { return id; } - + public String getStorageIpAddressDeux() { return storageIpAddressDeux; } @@ -131,11 +131,11 @@ public class StartupCommand extends Command { public String getName() { return name; } - + public String getVersion() { return version; } - + public void setDataCenter(String dataCenter) { this.dataCenter = dataCenter; } @@ -147,7 +147,7 @@ public class StartupCommand extends Command { public void setGuid(String guid) { this.guid = guid; } - + public void setGuid(String guid, String resourceName) { this.resourceName = resourceName; this.guid = guid + "-" + resourceName; @@ -232,15 +232,15 @@ public class StartupCommand extends Command { public void setVersion(String version) { this.version = version; } - + public void setPublicIpAddress(String publicIpAddress) { this.publicIpAddress = publicIpAddress; } - + public String getAgentTag() { return agentTag; } - + public void setAgentTag(String tag) { agentTag = tag; } @@ -248,7 +248,7 @@ public class StartupCommand extends Command { public void setResourceName(String resourceName) { this.resourceName = resourceName; } - + public String getGuidWithoutResource() { if (resourceName == null) { return guid; @@ -265,11 +265,11 @@ public class StartupCommand extends Command { } } } - + public String getResourceName() { return resourceName; } - + public String getGatewayIpAddress() { return gatewayIpAddress; } @@ -277,8 +277,8 @@ public class StartupCommand extends Command { public void setGatewayIpAddress(String gatewayIpAddress) { this.gatewayIpAddress = gatewayIpAddress; } - - + + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java b/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java index 2ba4ab9eb40..c4ed10729fe 100644 --- a/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java +++ b/api/src/com/cloud/agent/api/StartupExternalFirewallCommand.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; import com.cloud.host.Host; public class StartupExternalFirewallCommand extends StartupCommand { - + public StartupExternalFirewallCommand() { super(Host.Type.ExternalFirewall); } diff --git a/api/src/com/cloud/agent/api/StartupProxyCommand.java b/api/src/com/cloud/agent/api/StartupProxyCommand.java index 63991573bea..25cd769e650 100644 --- a/api/src/com/cloud/agent/api/StartupProxyCommand.java +++ b/api/src/com/cloud/agent/api/StartupProxyCommand.java @@ -21,12 +21,12 @@ import com.cloud.host.Host; public class StartupProxyCommand extends StartupCommand { private int proxyPort; private long proxyVmId; - + public StartupProxyCommand() { super(Host.Type.ConsoleProxy); setIqn("NoIqn"); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/StartupRoutingCommand.java b/api/src/com/cloud/agent/api/StartupRoutingCommand.java index e6989403c11..5961ab0017e 100755 --- a/api/src/com/cloud/agent/api/StartupRoutingCommand.java +++ b/api/src/com/cloud/agent/api/StartupRoutingCommand.java @@ -90,7 +90,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr long memory, long dom0MinMemory, final String caps, - final HypervisorType hypervisorType, + final HypervisorType hypervisorType, final Map hostDetails, Map vms) { super(Host.Type.Routing); @@ -114,7 +114,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public StartupRoutingCommand(int cpus, long speed, long memory, long dom0MinMemory, final String caps, final HypervisorType hypervisorType, final Map hostDetails, Map vms, String hypervisorVersion) { this(cpus, speed, memory, dom0MinMemory, caps, hypervisorType, hostDetails, vms); this.hypervisorVersion = hypervisorVersion; - } + } public void setChanges(Map vms) { this.vms = vms; @@ -128,7 +128,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr this.vms.put(vm_name, new VmState(vms.get(vm_name), null)); } } - + public void setClusterVMStateChanges(HashMap> allStates){ _clusterVMStates = allStates; } @@ -156,7 +156,7 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public Map getVmStates() { return vms; } - + public HashMap> getClusterVMStateChanges() { return _clusterVMStates; } @@ -219,6 +219,6 @@ getHostDetails().put(RouterPrivateIpStrategy.class.getCanonicalName(), privIpStr public void setHypervisorVersion(String hypervisorVersion) { this.hypervisorVersion = hypervisorVersion; - } + } } diff --git a/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java index 35896fb6e48..c19ea99e9e1 100644 --- a/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/StartupSecondaryStorageCommand.java @@ -19,12 +19,12 @@ package com.cloud.agent.api; import com.cloud.host.Host; public class StartupSecondaryStorageCommand extends StartupCommand { - + public StartupSecondaryStorageCommand() { super(Host.Type.SecondaryStorage); setIqn("NoIqn"); } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/StartupStorageCommand.java b/api/src/com/cloud/agent/api/StartupStorageCommand.java index d1e67d48800..3c3b058ce39 100755 --- a/api/src/com/cloud/agent/api/StartupStorageCommand.java +++ b/api/src/com/cloud/agent/api/StartupStorageCommand.java @@ -26,7 +26,7 @@ import com.cloud.storage.template.TemplateInfo; public class StartupStorageCommand extends StartupCommand { - + String parent; Map templateInfo; long totalSize; @@ -39,7 +39,7 @@ public class StartupStorageCommand extends StartupCommand { public StartupStorageCommand() { super(Host.Type.Storage); } - + public StartupStorageCommand(String parent, StoragePoolType fsType, long totalSize, Map info) { super(Host.Type.Storage); this.parent = parent; @@ -48,7 +48,7 @@ public class StartupStorageCommand extends StartupCommand { this.poolInfo = null; this.fsType = fsType; } - + public StartupStorageCommand(String parent, StoragePoolType fsType, Map templateInfo, StoragePoolInfo poolInfo) { super(Host.Type.Storage); @@ -62,7 +62,7 @@ public class StartupStorageCommand extends StartupCommand { public String getParent() { return parent; } - + public void setParent(String parent) { this.parent = parent; } @@ -70,15 +70,15 @@ public class StartupStorageCommand extends StartupCommand { public void setNfsShare(String nfsShare) { this.nfsShare = nfsShare; } - + public String getNfsShare() { return nfsShare; } - + public long getTotalSize() { return totalSize; } - + public Map getTemplateInfo() { return templateInfo; } diff --git a/api/src/com/cloud/agent/api/StopAnswer.java b/api/src/com/cloud/agent/api/StopAnswer.java index 52f28f165f2..1111fed1375 100755 --- a/api/src/com/cloud/agent/api/StopAnswer.java +++ b/api/src/com/cloud/agent/api/StopAnswer.java @@ -18,28 +18,28 @@ package com.cloud.agent.api; public class StopAnswer extends RebootAnswer { Integer vncPort; - + protected StopAnswer() { } - + public StopAnswer(StopCommand cmd, String details, Integer vncPort, boolean success) { super(cmd, details, success); this.vncPort = vncPort; } - + public StopAnswer(StopCommand cmd, String details, boolean success) { super(cmd, details, success); vncPort = null; } - + public StopAnswer(StopCommand cmd, Exception e) { super(cmd, e); } - + @Override public Integer getVncPort() { return vncPort; } - + } diff --git a/api/src/com/cloud/agent/api/StopCommand.java b/api/src/com/cloud/agent/api/StopCommand.java index 176a7fb86ee..9ee7ce3c874 100755 --- a/api/src/com/cloud/agent/api/StopCommand.java +++ b/api/src/com/cloud/agent/api/StopCommand.java @@ -23,35 +23,35 @@ public class StopCommand extends RebootCommand { private boolean isProxy=false; private String urlPort=null; private String publicConsoleProxyIpAddress=null; - + protected StopCommand() { } - + public StopCommand(VirtualMachine vm, boolean isProxy, String urlPort, String publicConsoleProxyIpAddress) { super(vm); this.isProxy = isProxy; this.urlPort = urlPort; this.publicConsoleProxyIpAddress = publicConsoleProxyIpAddress; } - + public StopCommand(VirtualMachine vm, String vnet) { super(vm); this.vnet = vnet; } - + public StopCommand(VirtualMachine vm, String vmName, String vnet) { super(vmName); this.vnet = vnet; } - + public StopCommand(String vmName) { super(vmName); } - + public String getVnet() { return vnet; } - + @Override public boolean executeInSequence() { return true; @@ -60,11 +60,11 @@ public class StopCommand extends RebootCommand { public boolean isProxy() { return this.isProxy; } - + public String getURLPort() { return this.urlPort; } - + public String getPublicConsoleProxyIpAddress() { return this.publicConsoleProxyIpAddress; } diff --git a/api/src/com/cloud/agent/api/StoragePoolInfo.java b/api/src/com/cloud/agent/api/StoragePoolInfo.java index 4ac6b296ba3..475205f2704 100644 --- a/api/src/com/cloud/agent/api/StoragePoolInfo.java +++ b/api/src/com/cloud/agent/api/StoragePoolInfo.java @@ -29,7 +29,7 @@ public class StoragePoolInfo { long capacityBytes; long availableBytes; Map details; - + protected StoragePoolInfo() { super(); } @@ -46,14 +46,14 @@ public class StoragePoolInfo { this.capacityBytes = capacityBytes; this.availableBytes = availableBytes; } - + public StoragePoolInfo(String uuid, String host, String hostPath, String localPath, StoragePoolType poolType, long capacityBytes, long availableBytes, Map details) { this(uuid, host, hostPath, localPath, poolType, capacityBytes, availableBytes); this.details = details; } - + public long getCapacityBytes() { return capacityBytes; } @@ -84,4 +84,4 @@ public class StoragePoolInfo { public Map getDetails() { return details; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/TransferAgentCommand.java b/api/src/com/cloud/agent/api/TransferAgentCommand.java index f6f63b79361..0dfde7eea0c 100644 --- a/api/src/com/cloud/agent/api/TransferAgentCommand.java +++ b/api/src/com/cloud/agent/api/TransferAgentCommand.java @@ -23,10 +23,10 @@ public class TransferAgentCommand extends Command { protected long futureOwner; protected long currentOwner; Event event; - + protected TransferAgentCommand() { } - + public TransferAgentCommand(long agentId, long currentOwner, long futureOwner, Event event) { this.agentId = agentId; this.currentOwner = currentOwner; diff --git a/api/src/com/cloud/agent/api/UnPlugNicCommand.java b/api/src/com/cloud/agent/api/UnPlugNicCommand.java index 0530527d5ba..b6cab8872f5 100644 --- a/api/src/com/cloud/agent/api/UnPlugNicCommand.java +++ b/api/src/com/cloud/agent/api/UnPlugNicCommand.java @@ -21,7 +21,7 @@ import com.cloud.agent.api.to.NicTO; public class UnPlugNicCommand extends Command{ NicTO nic; String instanceName; - + public NicTO getNic() { return nic; } @@ -30,10 +30,10 @@ public class UnPlugNicCommand extends Command{ public boolean executeInSequence() { return true; } - + protected UnPlugNicCommand() { } - + public UnPlugNicCommand(NicTO nic, String instanceName) { this.nic = nic; this.instanceName = instanceName; diff --git a/api/src/com/cloud/agent/api/UnsupportedAnswer.java b/api/src/com/cloud/agent/api/UnsupportedAnswer.java index 10a2b8addb8..7d0f24460d4 100644 --- a/api/src/com/cloud/agent/api/UnsupportedAnswer.java +++ b/api/src/com/cloud/agent/api/UnsupportedAnswer.java @@ -20,7 +20,7 @@ public class UnsupportedAnswer extends Answer { protected UnsupportedAnswer() { super(); } - + public UnsupportedAnswer(Command cmd, String details) { super(cmd, false, details); } diff --git a/api/src/com/cloud/agent/api/UpgradeAnswer.java b/api/src/com/cloud/agent/api/UpgradeAnswer.java index b93131bdd37..00b0f25b050 100644 --- a/api/src/com/cloud/agent/api/UpgradeAnswer.java +++ b/api/src/com/cloud/agent/api/UpgradeAnswer.java @@ -19,7 +19,7 @@ package com.cloud.agent.api; public class UpgradeAnswer extends Answer { protected UpgradeAnswer() { } - + public UpgradeAnswer(UpgradeCommand cmd, String failure) { super(cmd, false, failure); } diff --git a/api/src/com/cloud/agent/api/UpgradeCommand.java b/api/src/com/cloud/agent/api/UpgradeCommand.java index e85e72c8ea8..0e1b6d2e7c4 100644 --- a/api/src/com/cloud/agent/api/UpgradeCommand.java +++ b/api/src/com/cloud/agent/api/UpgradeCommand.java @@ -22,18 +22,18 @@ package com.cloud.agent.api; public class UpgradeCommand extends Command { String url; - + protected UpgradeCommand() { } - + public UpgradeCommand(String url) { this.url = url; } - + public String getUpgradeUrl() { return url; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java index e4517686491..f00f4902970 100644 --- a/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/UpgradeSnapshotCommand.java @@ -15,22 +15,24 @@ // 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; private Long tmpltAccountId; - + protected UpgradeSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The UUID of the primary storage Pool * @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage. * @param snapshotUuid The UUID of the snapshot which is going to be upgraded - * @param _version version for this snapshot + * @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; @@ -58,5 +60,5 @@ public class UpgradeSnapshotCommand extends SnapshotCommand { public Long getTmpltAccountId() { return 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/ValidateSnapshotAnswer.java b/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java index d9b0e61cda0..f5bb5448be0 100644 --- a/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java +++ b/api/src/com/cloud/agent/api/ValidateSnapshotAnswer.java @@ -21,11 +21,11 @@ public class ValidateSnapshotAnswer extends Answer { private String expectedSnapshotBackupUuid; private String actualSnapshotBackupUuid; private String actualSnapshotUuid; - + protected ValidateSnapshotAnswer() { - + } - + public ValidateSnapshotAnswer(ValidateSnapshotCommand cmd, boolean success, String result, String expectedSnapshotBackupUuid, String actualSnapshotBackupUuid, String actualSnapshotUuid) { super(cmd, success, result); this.expectedSnapshotBackupUuid = expectedSnapshotBackupUuid; @@ -39,14 +39,14 @@ public class ValidateSnapshotAnswer extends Answer { public String getExpectedSnapshotBackupUuid() { return expectedSnapshotBackupUuid; } - + /** * @return the actualSnapshotBackupUuid */ public String getActualSnapshotBackupUuid() { return actualSnapshotBackupUuid; } - + public String getActualSnapshotUuid() { return actualSnapshotUuid; } diff --git a/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java b/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java index 527502c28b3..9ffbf292281 100644 --- a/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java +++ b/api/src/com/cloud/agent/api/ValidateSnapshotCommand.java @@ -22,24 +22,24 @@ public class ValidateSnapshotCommand extends Command { private String firstBackupUuid; private String previousSnapshotUuid; private String templateUuid; - + protected ValidateSnapshotCommand() { - + } - + /** * @param primaryStoragePoolNameLabel The primary storage Pool Name Label * @param volumeUuid The UUID of the volume for which the snapshot was taken * @param firstBackupUuid This UUID of the first snapshot that was ever taken for this volume, even it was deleted. * @param previousSnapshotUuid The UUID of the previous snapshot on the primary. - * @param templateUuid If this is a root volume and no snapshot has been taken for it, - * this is the UUID of the template VDI. + * @param templateUuid If this is a root volume and no snapshot has been taken for it, + * this is the UUID of the template VDI. */ public ValidateSnapshotCommand(String primaryStoragePoolNameLabel, String volumeUuid, String firstBackupUuid, String previousSnapshotUuid, - String templateUuid) + String templateUuid) { this.primaryStoragePoolNameLabel = primaryStoragePoolNameLabel; this.volumeUuid = volumeUuid; @@ -51,7 +51,7 @@ public class ValidateSnapshotCommand extends Command { public String getPrimaryStoragePoolNameLabel() { return primaryStoragePoolNameLabel; } - + /** * @return the volumeUuid */ @@ -65,11 +65,11 @@ public class ValidateSnapshotCommand extends Command { public String getFirstBackupUuid() { return firstBackupUuid; } - + public String getPreviousSnapshotUuid() { return previousSnapshotUuid; } - + /** * @return the templateUuid */ @@ -81,4 +81,4 @@ public class ValidateSnapshotCommand extends Command { public boolean executeInSequence() { return false; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/VmStatsEntry.java b/api/src/com/cloud/agent/api/VmStatsEntry.java index 55694f86054..8828e9114f4 100755 --- a/api/src/com/cloud/agent/api/VmStatsEntry.java +++ b/api/src/com/cloud/agent/api/VmStatsEntry.java @@ -19,17 +19,17 @@ package com.cloud.agent.api; import com.cloud.vm.VmStats; public class VmStatsEntry implements VmStats { - + double cpuUtilization; double networkReadKBs; double networkWriteKBs; - int numCPUs; + int numCPUs; String entityType; - + public VmStatsEntry() { } - - public VmStatsEntry(double cpuUtilization, double networkReadKBs, double networkWriteKBs, int numCPUs, String entityType) + + public VmStatsEntry(double cpuUtilization, double networkReadKBs, double networkWriteKBs, int numCPUs, String entityType) { this.cpuUtilization = cpuUtilization; this.networkReadKBs = networkReadKBs; @@ -41,7 +41,7 @@ public class VmStatsEntry implements VmStats { public double getCPUUtilization() { return cpuUtilization; } - + public void setCPUUtilization(double cpuUtilization) { this.cpuUtilization = cpuUtilization; } @@ -49,23 +49,23 @@ public class VmStatsEntry implements VmStats { public double getNetworkReadKBs() { return networkReadKBs; } - + public void setNetworkReadKBs(double networkReadKBs) { this.networkReadKBs = networkReadKBs; } - + public double getNetworkWriteKBs() { return networkWriteKBs; } - + public void setNetworkWriteKBs(double networkWriteKBs) { this.networkWriteKBs = networkWriteKBs; } - + public int getNumCPUs() { return numCPUs; } - + public void setNumCPUs(int numCPUs) { this.numCPUs = numCPUs; } @@ -73,10 +73,10 @@ public class VmStatsEntry implements VmStats { public String getEntityType(){ return this.entityType; } - + public void setEntityType(String entityType){ this.entityType = entityType; } - + } diff --git a/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java b/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java index e0f4a28a156..fdd1fe910e9 100644 --- a/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/IpmISetBootDevCommand.java @@ -18,23 +18,23 @@ package com.cloud.agent.api.baremetal; import com.cloud.agent.api.Command; -public class IpmISetBootDevCommand extends Command { +public class IpmISetBootDevCommand extends Command { public enum BootDev { pxe(), disk(), cdrom(), } - + BootDev bootDev; - + public BootDev getBootDev() { return bootDev; } - + public IpmISetBootDevCommand(BootDev dev) { bootDev = dev; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java index 1190cb30033..d8f0529b44e 100644 --- a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java +++ b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerAnswer.java @@ -22,8 +22,8 @@ public class PreparePxeServerAnswer extends Answer { public PreparePxeServerAnswer(PreparePxeServerCommand cmd) { super(cmd, true, "SUCCESS"); } - + public PreparePxeServerAnswer(PreparePxeServerCommand cmd, String details) { super(cmd, false, details); - } + } } diff --git a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java index 0cda0f11464..6c735637034 100644 --- a/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/PreparePxeServerCommand.java @@ -28,12 +28,12 @@ public class PreparePxeServerCommand extends Command { String template; String vmName; String hostName; - + @Override public boolean executeInSequence() { return true; } - + public PreparePxeServerCommand(String ip, String mac, String netMask, String gateway, String dns, String template, String vmName, String hostName) { this.ip = ip; this.mac = mac; @@ -44,7 +44,7 @@ public class PreparePxeServerCommand extends Command { this.vmName = vmName; this.hostName = hostName; } - + public String getIp() { return ip; } @@ -68,11 +68,11 @@ public class PreparePxeServerCommand extends Command { public String getTemplate() { return template; } - + public String getVmName() { return vmName; } - + public String getHostName() { return hostName; } diff --git a/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java b/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java index 03d178e309a..b18742055df 100644 --- a/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java +++ b/api/src/com/cloud/agent/api/baremetal/prepareCreateTemplateCommand.java @@ -25,12 +25,12 @@ public class prepareCreateTemplateCommand extends Command { String gateway; String dns; String template; - + @Override public boolean executeInSequence() { return true; } - + public prepareCreateTemplateCommand(String ip, String mac, String netMask, String gateway, String dns, String template) { this.ip = ip; this.mac = mac; @@ -43,23 +43,23 @@ public class prepareCreateTemplateCommand extends Command { public String getIp() { return ip; } - + public String getMac() { return mac; } - + public String getNetMask() { return netMask; } - + public String getGateWay() { return gateway; } - + public String getDns() { return dns; } - + public String getTemplate() { return template; } diff --git a/api/src/com/cloud/agent/api/check/CheckSshAnswer.java b/api/src/com/cloud/agent/api/check/CheckSshAnswer.java index 7618159e63e..3414eb07c14 100644 --- a/api/src/com/cloud/agent/api/check/CheckSshAnswer.java +++ b/api/src/com/cloud/agent/api/check/CheckSshAnswer.java @@ -20,17 +20,17 @@ import com.cloud.agent.api.Answer; public class CheckSshAnswer extends Answer { protected CheckSshAnswer() { - + } - + public CheckSshAnswer(CheckSshCommand cmd) { super(cmd, true, null); } - + public CheckSshAnswer(CheckSshCommand cmd, String details) { super(cmd, false, details); } - + public CheckSshAnswer(CheckSshCommand cmd, Throwable th) { super(cmd, false, th.getMessage()); } diff --git a/api/src/com/cloud/agent/api/check/CheckSshCommand.java b/api/src/com/cloud/agent/api/check/CheckSshCommand.java index fb4210fc725..e384983e206 100644 --- a/api/src/com/cloud/agent/api/check/CheckSshCommand.java +++ b/api/src/com/cloud/agent/api/check/CheckSshCommand.java @@ -24,11 +24,11 @@ public class CheckSshCommand extends Command { int interval; int retries; String name; - + protected CheckSshCommand() { super(); } - + public CheckSshCommand(String instanceName, String ip, int port) { super(); this.ip = ip; @@ -37,7 +37,7 @@ public class CheckSshCommand extends Command { this.retries = 100; this.name = instanceName; } - + public String getName() { return name; } diff --git a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java index 0586f8cdcfd..a2ae611d316 100644 --- a/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java +++ b/api/src/com/cloud/agent/api/downloadSnapshotFromSwiftCommand.java @@ -20,7 +20,7 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * This currently assumes that both primary and secondary storage are mounted on the XenServer. + * This currently assumes that both primary and secondary storage are mounted on the XenServer. */ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { @LogLevel(Log4jLevel.Off) @@ -29,12 +29,12 @@ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { private String _parent; protected downloadSnapshotFromSwiftCommand() { - + } - + 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); @@ -57,4 +57,4 @@ public class downloadSnapshotFromSwiftCommand extends SnapshotCommand { this._parent = parent; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java index 0bf6e98e7cb..82290656095 100644 --- a/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/downloadTemplateFromSwiftToSecondaryStorageCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command { @@ -35,9 +35,9 @@ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command private String path; protected downloadTemplateFromSwiftToSecondaryStorageCommand() { - + } - + public downloadTemplateFromSwiftToSecondaryStorageCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long templateId, String path, int wait) { this.swift = swift; @@ -87,4 +87,4 @@ public class downloadTemplateFromSwiftToSecondaryStorageCommand extends Command return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java b/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java index 318d9398d83..7582b0d880c 100644 --- a/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java +++ b/api/src/com/cloud/agent/api/proxy/CheckConsoleProxyLoadCommand.java @@ -26,33 +26,33 @@ public class CheckConsoleProxyLoadCommand extends ProxyCommand { private String proxyVmName; private String proxyManagementIp; private int proxyCmdPort; - + public CheckConsoleProxyLoadCommand() { } - + public CheckConsoleProxyLoadCommand(long proxyVmId, String proxyVmName, String proxyManagementIp, int proxyCmdPort) { this.proxyVmId = proxyVmId; this.proxyVmName = proxyVmName; this.proxyManagementIp = proxyManagementIp; this.proxyCmdPort = proxyCmdPort; } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } - + public String getProxyManagementIp() { return proxyManagementIp; } - + public int getProxyCmdPort() { return proxyCmdPort; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java b/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java index df8f47d3557..ae93f51789b 100644 --- a/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java +++ b/api/src/com/cloud/agent/api/proxy/ConsoleProxyLoadAnswer.java @@ -23,21 +23,21 @@ public class ConsoleProxyLoadAnswer extends Answer { private long proxyVmId; private String proxyVmName; - + protected ConsoleProxyLoadAnswer() { } - + public ConsoleProxyLoadAnswer(Command command, long proxyVmId, String proxyVmName, boolean success, String details) { super(command, success, details); - + this.proxyVmId = proxyVmId; this.proxyVmName = proxyVmName; } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } diff --git a/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java b/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java index fd306ff2a92..c5af38eb724 100644 --- a/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java +++ b/api/src/com/cloud/agent/api/proxy/StartConsoleProxyAgentHttpHandlerCommand.java @@ -27,21 +27,21 @@ public class StartConsoleProxyAgentHttpHandlerCommand extends Command { private String keystorePassword; @LogLevel(Log4jLevel.Off) private String encryptorPassword; - + public StartConsoleProxyAgentHttpHandlerCommand() { super(); } - + public StartConsoleProxyAgentHttpHandlerCommand(byte[] ksBits, String ksPassword) { this.keystoreBits = ksBits; this.keystorePassword = ksPassword; } - + @Override public boolean executeInSequence() { return true; } - + public byte[] getKeystoreBits() { return keystoreBits; } diff --git a/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java b/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java index b918ba49f84..ef4a549daf3 100644 --- a/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java +++ b/api/src/com/cloud/agent/api/proxy/WatchConsoleProxyLoadCommand.java @@ -25,7 +25,7 @@ public class WatchConsoleProxyLoadCommand extends ProxyCommand implements CronCo private String proxyManagementIp; private int proxyCmdPort; int interval; - + public WatchConsoleProxyLoadCommand(int interval, long proxyVmId, String proxyVmName, String proxyManagementIp, int proxyCmdPort) { this.interval = interval; @@ -34,30 +34,30 @@ public class WatchConsoleProxyLoadCommand extends ProxyCommand implements CronCo this.proxyManagementIp = proxyManagementIp; this.proxyCmdPort = proxyCmdPort; } - + protected WatchConsoleProxyLoadCommand() { } - + public long getProxyVmId() { return proxyVmId; } - + public String getProxyVmName() { return proxyVmName; } - + public String getProxyManagementIp() { return proxyManagementIp; } - + public int getProxyCmdPort() { return proxyCmdPort; } - + public int getInterval() { return interval; } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java b/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java index ed972a22f51..dc7f1a188fd 100644 --- a/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java +++ b/api/src/com/cloud/agent/api/routing/CreateLoadBalancerApplianceCommand.java @@ -27,7 +27,7 @@ public class CreateLoadBalancerApplianceCommand extends NetworkElementCommand { String password; String publicInterface; String privateInterface; - + public CreateLoadBalancerApplianceCommand(String ip, String netmask, String gateway) { this.ip = ip; this.netmask = netmask; @@ -45,4 +45,4 @@ public class CreateLoadBalancerApplianceCommand extends NetworkElementCommand { public String getGateway() { return gateway; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java b/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java index ff38941f0a2..5c2cd582d4c 100644 --- a/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java +++ b/api/src/com/cloud/agent/api/routing/DhcpEntryCommand.java @@ -29,56 +29,56 @@ public class DhcpEntryCommand extends NetworkElementCommand { String staticRoutes; String defaultDns; - + protected DhcpEntryCommand() { - + } - + @Override public boolean executeInSequence() { return true; } - + public DhcpEntryCommand(String vmMac, String vmIpAddress, String vmName) { this.vmMac = vmMac; this.vmIpAddress = vmIpAddress; this.vmName = vmName; } - + public DhcpEntryCommand(String vmMac, String vmIpAddress, String vmName, String dns, String gateway) { this(vmMac, vmIpAddress, vmName); this.dns = dns; this.gateway = gateway; } - + public String getDns() { return dns; } - + public String getGateway() { return gateway; } - + public String getVmMac() { return vmMac; } - + public String getVmIpAddress() { return vmIpAddress; } - + public String getVmName() { return vmName; } - + public void setNextServer(String ip) { nextServer = ip; } - + public String getNextServer() { return nextServer; } - + public String getDefaultRouter() { return defaultRouter; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java b/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java index 18921969f75..194923c497e 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocAnswer.java @@ -20,13 +20,13 @@ import com.cloud.agent.api.Answer; public class IpAssocAnswer extends Answer{ String[] results; - + public static final String errorResult = "Failed"; - + protected IpAssocAnswer() { super(); } - + public IpAssocAnswer(IpAssocCommand cmd, String[] results) { boolean finalResult = true; @@ -41,7 +41,7 @@ public class IpAssocAnswer extends Answer{ assert(cmd.getIpAddresses().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocCommand.java b/api/src/com/cloud/agent/api/routing/IpAssocCommand.java index 5326b119352..5cdc2da2efa 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocCommand.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocCommand.java @@ -19,12 +19,12 @@ package com.cloud.agent.api.routing; import com.cloud.agent.api.to.IpAddressTO; public class IpAssocCommand extends NetworkElementCommand { - + IpAddressTO[] ipAddresses; protected IpAssocCommand() { } - + public IpAssocCommand(IpAddressTO[] ips) { this.ipAddresses = ips; } diff --git a/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java b/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java index cc7fcb00f09..e5c900d19e2 100644 --- a/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java +++ b/api/src/com/cloud/agent/api/routing/IpAssocVpcCommand.java @@ -22,7 +22,7 @@ public class IpAssocVpcCommand extends IpAssocCommand{ protected IpAssocVpcCommand() { super(); } - + public IpAssocVpcCommand(IpAddressTO[] ips) { super(ips); } diff --git a/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java b/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java index a5505e1e688..1c1fb914da3 100644 --- a/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java +++ b/api/src/com/cloud/agent/api/routing/LoadBalancerConfigCommand.java @@ -31,13 +31,13 @@ public class LoadBalancerConfigCommand extends NetworkElementCommand { public String lbStatsPort = "8081"; /*load balancer listen on this port for stats */ public String lbStatsSrcCidrs = "0/0" ; /* TODO : currently there is no filtering based on the source ip */ public String lbStatsAuth = "admin1:AdMiN123"; - public String lbStatsUri = "/admin?stats"; + public String lbStatsUri = "/admin?stats"; NicTO nic; Long vpcId; - + protected LoadBalancerConfigCommand() { } - + public LoadBalancerConfigCommand(LoadBalancerTO[] loadBalancers, Long vpcId) { this.loadBalancers = loadBalancers; this.vpcId = vpcId; @@ -51,11 +51,11 @@ public class LoadBalancerConfigCommand extends NetworkElementCommand { this.nic = nic; this.vpcId = vpcId; } - + public NicTO getNic() { return nic; } - + public LoadBalancerTO[] getLoadBalancers() { return loadBalancers; } diff --git a/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java b/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java index 61e41e8f424..41ae80fe223 100644 --- a/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java +++ b/api/src/com/cloud/agent/api/routing/NetworkElementCommand.java @@ -22,7 +22,7 @@ import com.cloud.agent.api.Command; public abstract class NetworkElementCommand extends Command { HashMap accessDetails = new HashMap(0); - + public static final String ACCOUNT_ID = "account.id"; public static final String GUEST_NETWORK_CIDR = "guest.network.cidr"; public static final String GUEST_NETWORK_GATEWAY = "guest.network.gateway"; @@ -32,19 +32,19 @@ public abstract class NetworkElementCommand extends Command { public static final String ROUTER_GUEST_IP = "router.guest.ip"; public static final String ZONE_NETWORK_TYPE = "zone.network.type"; public static final String GUEST_BRIDGE = "guest.bridge"; - + protected NetworkElementCommand() { super(); } - + public void setAccessDetail(String name, String value) { accessDetails.put(name, value); } - + public String getAccessDetail(String name) { return accessDetails.get(name); } - + @Override public boolean executeInSequence() { return false; diff --git a/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java b/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java index 8cf3ba2f89c..68d7caf016f 100644 --- a/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/RemoteAccessVpnCfgCommand.java @@ -18,17 +18,17 @@ package com.cloud.agent.api.routing; public class RemoteAccessVpnCfgCommand extends NetworkElementCommand { - + boolean create; String vpnServerIp; String ipRange; String presharedKey; String localIp; - + protected RemoteAccessVpnCfgCommand() { this.create = false; } - + public boolean isCreate() { return create; } @@ -37,12 +37,12 @@ public class RemoteAccessVpnCfgCommand extends NetworkElementCommand { public boolean executeInSequence() { return true; } - - + + public RemoteAccessVpnCfgCommand(boolean create, String vpnServerAddress, String localIp, String ipRange, String ipsecPresharedKey) { this.vpnServerIp = vpnServerAddress; this.ipRange = ipRange; - this.presharedKey = ipsecPresharedKey; + this.presharedKey = ipsecPresharedKey; this.localIp = localIp; this.create = create; } diff --git a/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java b/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java index 92cf671db6f..6dac1488e11 100644 --- a/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java +++ b/api/src/com/cloud/agent/api/routing/SavePasswordCommand.java @@ -22,25 +22,25 @@ public class SavePasswordCommand extends NetworkElementCommand { String password; String vmIpAddress; String vmName; - - protected SavePasswordCommand() { + + protected SavePasswordCommand() { } - + @Override public boolean executeInSequence() { return true; } - + public SavePasswordCommand(String password, String vmIpAddress, String vmName) { this.password = password; this.vmIpAddress = vmIpAddress; this.vmName = vmName; } - + public String getPassword() { return password; } - + public String getVmIpAddress() { return vmIpAddress; } @@ -48,7 +48,7 @@ public class SavePasswordCommand extends NetworkElementCommand { public String getVmName() { return vmName; } - - - + + + } diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java index 82730bd7ea2..5268c3dda76 100644 --- a/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesAnswer.java @@ -20,16 +20,16 @@ import com.cloud.agent.api.Answer; public class SetFirewallRulesAnswer extends Answer { String[] results; - + protected SetFirewallRulesAnswer() { } - + public SetFirewallRulesAnswer(SetFirewallRulesCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getRules().length == results.length) : "rules and their results should be the same length don't you think?"; this.results = results; } - + public String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java index 528f36bfa81..3841bd7a157 100644 --- a/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetFirewallRulesCommand.java @@ -23,7 +23,7 @@ import java.util.Set; import com.cloud.agent.api.to.FirewallRuleTO; /** - * + * * AccessDetails allow different components to put in information about * how to access the components inside the command. */ @@ -32,11 +32,11 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { protected SetFirewallRulesCommand() { } - + public SetFirewallRulesCommand(List rules) { - this.rules = rules.toArray(new FirewallRuleTO[rules.size()]); + this.rules = rules.toArray(new FirewallRuleTO[rules.size()]); } - + public FirewallRuleTO[] getRules() { return rules; } @@ -45,34 +45,34 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { String [][] result = new String [2][]; Set toAdd = new HashSet(); - + for (FirewallRuleTO fwTO: rules) { - /* example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:, + /* example : 172.16.92.44:tcp:80:80:0.0.0.0/0:,200.16.92.44:tcp:220:220:0.0.0.0/0:, * each entry format :protocol:srcport:destport:scidr: * reverted entry format :reverted:0:0:0: */ - if (fwTO.revoked() == true) + if (fwTO.revoked() == true) { StringBuilder sb = new StringBuilder(); /* This entry is added just to make sure atleast there will one entry in the list to get the ipaddress */ - sb.append(fwTO.getSrcIp()).append(":reverted:0:0:0:"); + sb.append(fwTO.getSrcIp()).append(":reverted:0:0:0:"); String fwRuleEntry = sb.toString(); toAdd.add(fwRuleEntry); continue; } - + List cidr; StringBuilder sb = new StringBuilder(); sb.append(fwTO.getSrcIp()).append(":").append(fwTO.getProtocol()).append(":"); if ("icmp".compareTo(fwTO.getProtocol()) == 0) { sb.append(fwTO.getIcmpType()).append(":").append(fwTO.getIcmpCode()).append(":"); - + }else if (fwTO.getStringSrcPortRange() == null) sb.append("0:0").append(":"); else sb.append(fwTO.getStringSrcPortRange()).append(":"); - + cidr = fwTO.getSourceCidrList(); if (cidr == null || cidr.isEmpty()) { @@ -80,19 +80,19 @@ public class SetFirewallRulesCommand extends NetworkElementCommand { }else{ Boolean firstEntry = true; for (String tag : cidr) { - if (!firstEntry) sb.append("-"); + if (!firstEntry) sb.append("-"); sb.append(tag); firstEntry = false; } } sb.append(":"); String fwRuleEntry = sb.toString(); - + toAdd.add(fwRuleEntry); - + } result[0] = toAdd.toArray(new String[toAdd.size()]); - + return result; } } diff --git a/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java b/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java index cc14295e227..dc192add20b 100644 --- a/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetNetworkACLAnswer.java @@ -20,17 +20,17 @@ import com.cloud.agent.api.Answer; public class SetNetworkACLAnswer extends Answer { String[] results; - + protected SetNetworkACLAnswer() { } - + public SetNetworkACLAnswer(SetNetworkACLCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getRules().length == results.length) : "ACLs and their results should be the same length"; this.results = results; } - + public String[] getResults() { return results; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java b/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java index b8fe119176f..dba7354c8f2 100644 --- a/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetNetworkACLCommand.java @@ -30,12 +30,12 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ protected SetNetworkACLCommand() { } - + public SetNetworkACLCommand(List rules, NicTO nic) { - this.rules = rules.toArray(new NetworkACLTO[rules.size()]); + this.rules = rules.toArray(new NetworkACLTO[rules.size()]); this.nic = nic; } - + public NetworkACLTO[] getRules() { return rules; } @@ -43,22 +43,22 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ String [][] result = new String [2][]; Set toAdd = new HashSet(); - + for (NetworkACLTO aclTO: rules) { - /* example : Ingress:tcp:80:80:0.0.0.0/0:,Egress:tcp:220:220:0.0.0.0/0:, + /* example : Ingress:tcp:80:80:0.0.0.0/0:,Egress:tcp:220:220:0.0.0.0/0:, * each entry format Ingress/Egress:protocol:start port: end port:scidrs: * reverted entry format Ingress/Egress:reverted:0:0:0: */ - if (aclTO.revoked() == true) + if (aclTO.revoked() == true) { StringBuilder sb = new StringBuilder(); /* This entry is added just to make sure atleast there will one entry in the list to get the ipaddress */ - sb.append(aclTO.getTrafficType().toString()).append(":reverted:0:0:0:"); + sb.append(aclTO.getTrafficType().toString()).append(":reverted:0:0:0:"); String aclRuleEntry = sb.toString(); toAdd.add(aclRuleEntry); continue; } - + List cidr; StringBuilder sb = new StringBuilder(); sb.append(aclTO.getTrafficType().toString()).append(":").append(aclTO.getProtocol()).append(":"); @@ -75,22 +75,22 @@ public class SetNetworkACLCommand extends NetworkElementCommand{ }else{ Boolean firstEntry = true; for (String tag : cidr) { - if (!firstEntry) sb.append("-"); + if (!firstEntry) sb.append("-"); sb.append(tag); firstEntry = false; } } sb.append(":"); String aclRuleEntry = sb.toString(); - + toAdd.add(aclRuleEntry); - + } result[0] = toAdd.toArray(new String[toAdd.size()]); - + return result; } - + public NicTO getNic() { return nic; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java index 9aa2f6db5d2..15306fbe645 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesAnswer.java @@ -23,14 +23,14 @@ public class SetPortForwardingRulesAnswer extends Answer { protected SetPortForwardingRulesAnswer() { super(); } - + public SetPortForwardingRulesAnswer(SetPortForwardingRulesCommand cmd, String[] results, boolean success) { super(cmd, success, null); - + assert(cmd.getRules().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java index dc820431e36..a7bf37f83ef 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesCommand.java @@ -25,7 +25,7 @@ public class SetPortForwardingRulesCommand extends NetworkElementCommand { protected SetPortForwardingRulesCommand() { } - + public SetPortForwardingRulesCommand(List pfRules) { rules = new PortForwardingRuleTO[pfRules.size()]; int i = 0; @@ -33,7 +33,7 @@ public class SetPortForwardingRulesCommand extends NetworkElementCommand { rules[i++] = rule; } } - + public PortForwardingRuleTO[] getRules() { return rules; } diff --git a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java index 042e788b4ce..7228457d890 100644 --- a/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetPortForwardingRulesVpcCommand.java @@ -23,7 +23,7 @@ import com.cloud.agent.api.to.PortForwardingRuleTO; public class SetPortForwardingRulesVpcCommand extends SetPortForwardingRulesCommand{ protected SetPortForwardingRulesVpcCommand() { } - + public SetPortForwardingRulesVpcCommand(List pfRules) { super(pfRules); } diff --git a/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java b/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java index 165a15d5640..96aa001de84 100644 --- a/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetSourceNatCommand.java @@ -21,10 +21,10 @@ import com.cloud.agent.api.to.IpAddressTO; public class SetSourceNatCommand extends NetworkElementCommand{ IpAddressTO ipAddress; boolean add; - + protected SetSourceNatCommand() { } - + public SetSourceNatCommand(IpAddressTO ip, boolean add) { this.ipAddress = ip; this.add = add; @@ -38,5 +38,5 @@ public class SetSourceNatCommand extends NetworkElementCommand{ public IpAddressTO getIpAddress() { return ipAddress; } - + } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java index e57b3277850..9b5d09b25c5 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesAnswer.java @@ -23,14 +23,14 @@ public class SetStaticNatRulesAnswer extends Answer { protected SetStaticNatRulesAnswer() { super(); } - + public SetStaticNatRulesAnswer(SetStaticNatRulesCommand cmd, String[] results, boolean success) { super(cmd, success, null); - + assert(cmd.getRules().length == results.length) : "Shouldn't the results match the commands?"; this.results = results; } - + String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java index c28032ccdfb..852d16167ab 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticNatRulesCommand.java @@ -21,13 +21,13 @@ import java.util.List; import com.cloud.agent.api.to.StaticNatRuleTO; public class SetStaticNatRulesCommand extends NetworkElementCommand{ - + StaticNatRuleTO[] rules; Long vpcId; protected SetStaticNatRulesCommand() { } - + public SetStaticNatRulesCommand(List staticNatRules, Long vpcId) { rules = new StaticNatRuleTO[staticNatRules.size()]; int i = 0; @@ -36,7 +36,7 @@ public class SetStaticNatRulesCommand extends NetworkElementCommand{ } this.vpcId = vpcId; } - + public StaticNatRuleTO[] getRules() { return rules; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java b/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java index c13bda060e2..76f5bb96b1e 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticRouteAnswer.java @@ -20,16 +20,16 @@ import com.cloud.agent.api.Answer; public class SetStaticRouteAnswer extends Answer{ String[] results; - + protected SetStaticRouteAnswer() { } - + public SetStaticRouteAnswer(SetStaticRouteCommand cmd, boolean success, String[] results) { super(cmd, success, null); assert (cmd.getStaticRoutes().length == results.length) : "Static routes and their results should be the same length"; this.results = results; } - + public String[] getResults() { return results; } diff --git a/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java b/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java index 0c91a9efa74..c9c2056816b 100644 --- a/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java +++ b/api/src/com/cloud/agent/api/routing/SetStaticRouteCommand.java @@ -27,12 +27,12 @@ import com.cloud.utils.net.NetUtils; public class SetStaticRouteCommand extends NetworkElementCommand{ StaticRouteProfile[] staticRoutes; - + protected SetStaticRouteCommand() { } - + public SetStaticRouteCommand(List staticRoutes) { - this.staticRoutes = staticRoutes.toArray(new StaticRouteProfile[staticRoutes.size()]); + this.staticRoutes = staticRoutes.toArray(new StaticRouteProfile[staticRoutes.size()]); } public StaticRouteProfile[] getStaticRoutes() { diff --git a/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java b/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java index 97db2f96cc3..83163039f51 100644 --- a/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/Site2SiteVpnCfgCommand.java @@ -5,7 +5,7 @@ // 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, @@ -30,16 +30,16 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { private long ikeLifetime; private long espLifetime; private boolean dpd; - + @Override public boolean executeInSequence() { return true; } - + public Site2SiteVpnCfgCommand () { this.create = false; } - + public Site2SiteVpnCfgCommand (boolean create, String localPublicIp, String localPublicGateway, String localGuestCidr, String peerGatewayIp, String peerGuestCidrList, String ikePolicy, String espPolicy, String ipsecPsk, Long ikeLifetime, Long espLifetime, Boolean dpd) { this.create = create; @@ -55,11 +55,11 @@ public class Site2SiteVpnCfgCommand extends NetworkElementCommand { this.espLifetime = espLifetime; this.dpd = dpd; } - + public boolean isCreate() { return create; } - + public void setCreate(boolean create) { this.create = create; } diff --git a/api/src/com/cloud/agent/api/routing/UserDataCommand.java b/api/src/com/cloud/agent/api/routing/UserDataCommand.java index 103bd91f804..f7b38c8c364 100644 --- a/api/src/com/cloud/agent/api/routing/UserDataCommand.java +++ b/api/src/com/cloud/agent/api/routing/UserDataCommand.java @@ -23,31 +23,31 @@ public class UserDataCommand extends NetworkElementCommand { String vmIpAddress; String routerPrivateIpAddress; String vmName; - + protected UserDataCommand() { - + } - + @Override public boolean executeInSequence() { return true; } - + public UserDataCommand(String userData, String vmIpAddress, String routerPrivateIpAddress, String vmName) { this.userData = userData; this.vmIpAddress = vmIpAddress; this.routerPrivateIpAddress = routerPrivateIpAddress; this.vmName = vmName; } - + public String getRouterPrivateIpAddress() { return routerPrivateIpAddress; } - + public String getVmIpAddress() { return vmIpAddress; } - + public String getVmName() { return vmName; } @@ -59,5 +59,5 @@ public class UserDataCommand extends NetworkElementCommand { public void setUserData(String userData) { this.userData = userData; } - + } diff --git a/api/src/com/cloud/agent/api/routing/VmDataCommand.java b/api/src/com/cloud/agent/api/routing/VmDataCommand.java index d5053840e0b..df882554479 100644 --- a/api/src/com/cloud/agent/api/routing/VmDataCommand.java +++ b/api/src/com/cloud/agent/api/routing/VmDataCommand.java @@ -23,24 +23,24 @@ import com.cloud.agent.api.LogLevel; import com.cloud.agent.api.LogLevel.Log4jLevel; public class VmDataCommand extends NetworkElementCommand { - + String vmIpAddress; String vmName; @LogLevel(Log4jLevel.Trace) List vmData; - + protected VmDataCommand() { } - + @Override public boolean executeInSequence() { return true; } - + public VmDataCommand(String vmIpAddress) { this(vmIpAddress, null); } - + public String getVmName() { return vmName; } @@ -50,18 +50,18 @@ public class VmDataCommand extends NetworkElementCommand { this.vmIpAddress = vmIpAddress; this.vmData = new ArrayList(); } - - + + public String getVmIpAddress() { return vmIpAddress; } - + public List getVmData() { return vmData; } - + public void addVmData(String folder, String file, String contents) { vmData.add(new String[]{folder, file, contents}); } - + } diff --git a/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java b/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java index 249c2358d2f..ebe725d2911 100644 --- a/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java +++ b/api/src/com/cloud/agent/api/routing/VpnUsersCfgCommand.java @@ -23,12 +23,12 @@ import com.cloud.network.VpnUser; public class VpnUsersCfgCommand extends NetworkElementCommand { - public static class UsernamePassword{ + public static class UsernamePassword{ private String username; @LogLevel(Log4jLevel.Off) private String password; boolean add = true; - + public boolean isAdd() { return add; } @@ -66,11 +66,11 @@ public class VpnUsersCfgCommand extends NetworkElementCommand { } } UsernamePassword [] userpwds; - + protected VpnUsersCfgCommand() { - + } - + public VpnUsersCfgCommand(List addUsers, List removeUsers) { userpwds = new UsernamePassword[addUsers.size() + removeUsers.size()]; int i = 0; @@ -86,7 +86,7 @@ public class VpnUsersCfgCommand extends NetworkElementCommand { public boolean executeInSequence() { return true; } - + public UsernamePassword[] getUserpwds() { return userpwds; } diff --git a/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java b/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java index 5737a05d98b..04b3d4360d5 100644 --- a/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/AbstractDownloadCommand.java @@ -24,46 +24,46 @@ public abstract class AbstractDownloadCommand extends ssCommand { private ImageFormat format; private long accountId; private String name; - + protected AbstractDownloadCommand() { } - + protected AbstractDownloadCommand(String name, String url, ImageFormat format, long accountId) { assert(url != null); url = url.replace('\\', '/'); - + this.url = url; this.format = format; this.accountId = accountId; this.name = name; } - + protected AbstractDownloadCommand(AbstractDownloadCommand that) { super(that); assert(that.url != null); - + this.url = that.url.replace('\\', '/'); this.format = that.format; this.accountId = that.accountId; this.name = that.name; } - + public String getUrl() { return url; } - + public String getName() { return name; } - + public ImageFormat getFormat() { return format; } - + public long getAccountId() { return accountId; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java b/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java index 1c55e8fafd6..49c04b16a81 100644 --- a/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java +++ b/api/src/com/cloud/agent/api/storage/AbstractUploadCommand.java @@ -25,37 +25,37 @@ public class AbstractUploadCommand extends StorageCommand{ private ImageFormat format; private long accountId; private String name; - + protected AbstractUploadCommand() { } - + protected AbstractUploadCommand(String name, String url, ImageFormat format, long accountId) { this.url = url; this.format = format; this.accountId = accountId; this.name = name; } - + protected AbstractUploadCommand(AbstractUploadCommand that) { this(that.name, that.url, that.format, that.accountId); } - + public String getUrl() { return url; } - + public String getName() { return name; } - + public ImageFormat getFormat() { return format; } - + public long getAccountId() { return accountId; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java index 7704569b37a..8c55ac3eecc 100644 --- a/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CopyVolumeAnswer.java @@ -22,20 +22,20 @@ import com.cloud.agent.api.Command; public class CopyVolumeAnswer extends Answer { private String volumeFolder; private String volumePath; - + protected CopyVolumeAnswer() { } - + public CopyVolumeAnswer(Command command, boolean success, String details, String volumeFolder, String volumePath) { super(command, success, details); this.volumeFolder = volumeFolder; this.volumePath = volumePath; } - + public String getVolumeFolder() { return volumeFolder; } - + public String getVolumePath() { return volumePath; } diff --git a/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java b/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java index 26bd1871138..3d05e9ba69c 100644 --- a/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/CopyVolumeCommand.java @@ -23,49 +23,49 @@ import com.cloud.storage.StoragePool; public class CopyVolumeCommand extends Command { long volumeId; - String volumePath; + String volumePath; StorageFilerTO pool; String secondaryStorageURL; boolean toSecondaryStorage; String vmName; - - public CopyVolumeCommand() { + + public CopyVolumeCommand() { } - + public CopyVolumeCommand(long volumeId, String volumePath, StoragePool pool, String secondaryStorageURL, boolean toSecondaryStorage, int wait) { this.volumeId = volumeId; - this.volumePath = volumePath; + this.volumePath = volumePath; this.pool = new StorageFilerTO(pool); this.secondaryStorageURL = secondaryStorageURL; this.toSecondaryStorage = toSecondaryStorage; setWait(wait); } - + @Override public boolean executeInSequence() { return true; } - + public String getVolumePath() { return volumePath; } - + public long getVolumeId() { return volumeId; } - + public StorageFilerTO getPool() { return pool; } - + public String getSecondaryStorageURL() { return secondaryStorageURL; } - + public boolean toSecondaryStorage() { return toSecondaryStorage; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/storage/CreateAnswer.java b/api/src/com/cloud/agent/api/storage/CreateAnswer.java index 695b6bad316..ab6cc038604 100644 --- a/api/src/com/cloud/agent/api/storage/CreateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreateAnswer.java @@ -24,29 +24,29 @@ public class CreateAnswer extends Answer { boolean requestTemplateReload = false; protected CreateAnswer() { } - + public CreateAnswer(CreateCommand cmd, VolumeTO volume) { super(cmd, true, null); this.volume = volume; } - + public CreateAnswer(CreateCommand cmd, String details) { super(cmd, false, details); } - + public CreateAnswer(CreateCommand cmd, String details, boolean requestTemplateReload) { super(cmd, false, details); this.requestTemplateReload = requestTemplateReload; } - + public CreateAnswer(CreateCommand cmd, Exception e) { super(cmd, e); } - + public VolumeTO getVolume() { return volume; } - + public boolean templateReloadRequested() { return requestTemplateReload; } diff --git a/api/src/com/cloud/agent/api/storage/CreateCommand.java b/api/src/com/cloud/agent/api/storage/CreateCommand.java index b8b2446216d..fd0375aa6e7 100644 --- a/api/src/com/cloud/agent/api/storage/CreateCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreateCommand.java @@ -26,14 +26,14 @@ public class CreateCommand extends Command { private StorageFilerTO pool; private DiskProfile diskCharacteristics; private String templateUrl; - + protected CreateCommand() { super(); } /** * Construction for template based volumes. - * + * * @param vol * @param vm * @param diskCharacteristics @@ -47,7 +47,7 @@ public class CreateCommand extends Command { /** * Construction for regular volumes. - * + * * @param vol * @param vm * @param diskCharacteristics @@ -55,19 +55,19 @@ public class CreateCommand extends Command { */ public CreateCommand(DiskProfile diskCharacteristics, StorageFilerTO pool) { this.volId = diskCharacteristics.getVolumeId(); - this.diskCharacteristics = diskCharacteristics; + this.diskCharacteristics = diskCharacteristics; this.pool = pool; this.templateUrl = null; } - + public CreateCommand(DiskProfile diskCharacteristics, String templateUrl, StoragePool pool) { this(diskCharacteristics, templateUrl, new StorageFilerTO(pool)); } - + public CreateCommand(DiskProfile diskCharacteristics, StoragePool pool) { this(diskCharacteristics, new StorageFilerTO(pool)); } - + @Override public boolean executeInSequence() { return true; @@ -76,19 +76,19 @@ public class CreateCommand extends Command { public String getTemplateUrl() { return templateUrl; } - + public StorageFilerTO getPool() { return pool; } - + public DiskProfile getDiskCharacteristics() { return diskCharacteristics; } - + public long getVolumeId() { return volId; } - + @Deprecated public String getInstanceName() { return null; diff --git a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java index 550a9490e90..808a67f994f 100644 --- a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLAnswer.java @@ -19,19 +19,19 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Answer; public class CreateEntityDownloadURLAnswer extends Answer{ - + String resultString; short resultCode; public static final short RESULT_SUCCESS = 1; public static final short RESULT_FAILURE = 0; - + public CreateEntityDownloadURLAnswer(String resultString, short resultCode) { super(); this.resultString = resultString; this.resultCode = resultCode; - } - - public CreateEntityDownloadURLAnswer(){ + } + + public CreateEntityDownloadURLAnswer(){ } } diff --git a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java index f32002257ca..c80179a0560 100755 --- a/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreateEntityDownloadURLCommand.java @@ -26,7 +26,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { this.installPath = installPath; this.extractLinkUUID = uuid; } - + public CreateEntityDownloadURLCommand(String installPath, String uuid) { super(); this.parent = parent; @@ -40,7 +40,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { private String installPath; private String parent; private String extractLinkUUID; - + @Override public boolean executeInSequence() { return false; @@ -53,7 +53,7 @@ public class CreateEntityDownloadURLCommand extends AbstractDownloadCommand { public void setInstallPath(String installPath) { this.installPath = installPath; } - + public String getParent() { return parent; } diff --git a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java index 2dfcf211c0f..83db84d8b87 100644 --- a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateAnswer.java @@ -29,7 +29,7 @@ public class CreatePrivateTemplateAnswer extends Answer { public CreatePrivateTemplateAnswer() {} - public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result, String path, long virtualSize, + public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result, String path, long virtualSize, long physicalSize, String uniqueName, ImageFormat format) { super(cmd, success, result); _path = path; @@ -42,23 +42,23 @@ public class CreatePrivateTemplateAnswer extends Answer { public CreatePrivateTemplateAnswer(Command cmd, boolean success, String result) { super(cmd, success, result); } - + public String getPath() { return _path; } - + public void setPath(String path) { _path = path; } - + public long getVirtualSize() { return _virtualSize; } - + public void setVirtualSize(long virtualSize) { _virtualSize = virtualSize; } - + public void setphysicalSize(long _physicalSize) { this._physicalSize = _physicalSize; } @@ -70,7 +70,7 @@ public class CreatePrivateTemplateAnswer extends Answer { public String getUniqueName() { return _uniqueName; } - + public ImageFormat getImageFormat() { return _format; } diff --git a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java index 5fd186cb37f..d392a89ec38 100644 --- a/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/CreatePrivateTemplateCommand.java @@ -24,7 +24,7 @@ public class CreatePrivateTemplateCommand extends StorageCommand { private String _uniqueName; private long _templateId; private long _accountId; - + // For XenServer private String _secondaryStorageURL; private String _snapshotName; @@ -44,10 +44,10 @@ public class CreatePrivateTemplateCommand extends StorageCommand { } @Override - public boolean executeInSequence() { + public boolean executeInSequence() { return false; } - + public String getSecondaryStorageURL() { return _secondaryStorageURL; } @@ -67,23 +67,23 @@ public class CreatePrivateTemplateCommand extends StorageCommand { public String getSnapshotPath() { return _snapshotPath; } - + public String getSnapshotName() { return _snapshotName; } - + public String getUserFolder() { return _userFolder; } - + public long getTemplateId() { return _templateId; } - + public long getAccountId() { return _accountId; } - + public void setTemplateId(long templateId) { _templateId = templateId; } diff --git a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java index 69a2b495a30..c6fdf3cb6fe 100644 --- a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLAnswer.java @@ -19,19 +19,19 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Answer; public class DeleteEntityDownloadURLAnswer extends Answer{ - + String resultString; short resultCode; public static final short RESULT_SUCCESS = 1; public static final short RESULT_FAILURE = 0; - + public DeleteEntityDownloadURLAnswer(String resultString, short resultCode) { super(); this.resultString = resultString; this.resultCode = resultCode; - } - - public DeleteEntityDownloadURLAnswer(){ + } + + public DeleteEntityDownloadURLAnswer(){ } } diff --git a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java index 772e6c6b251..fbfacb97c85 100755 --- a/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteEntityDownloadURLCommand.java @@ -19,9 +19,9 @@ package com.cloud.agent.api.storage; import com.cloud.storage.Upload; public class DeleteEntityDownloadURLCommand extends AbstractDownloadCommand { - + private String path; - private String extractUrl; + private String extractUrl; private Upload.Type type; private String parentPath; diff --git a/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java b/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java index ce349dda522..69f465c6b16 100644 --- a/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteTemplateCommand.java @@ -21,19 +21,19 @@ public class DeleteTemplateCommand extends ssCommand { private String templatePath; - public DeleteTemplateCommand() { + public DeleteTemplateCommand() { } - + public DeleteTemplateCommand(String secUrl, String templatePath) { this.setSecUrl(secUrl); this.templatePath = templatePath; } - + @Override public boolean executeInSequence() { return true; } - + public String getTemplatePath() { return templatePath; } diff --git a/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java b/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java index ea729e81bda..949af010423 100755 --- a/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/DeleteVolumeCommand.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -public class DeleteVolumeCommand extends ssCommand { - private String volumePath; - - public DeleteVolumeCommand() { - } - - public DeleteVolumeCommand(String secUrl, String volumePath) { - this.setSecUrl(secUrl); - this.volumePath = volumePath; - } - - @Override - public boolean executeInSequence() { - return true; - } - - public String getVolumePath() { - return volumePath; - } -} +package com.cloud.agent.api.storage; + +public class DeleteVolumeCommand extends ssCommand { + private String volumePath; + + public DeleteVolumeCommand() { + } + + public DeleteVolumeCommand(String secUrl, String volumePath) { + this.setSecUrl(secUrl); + this.volumePath = volumePath; + } + + @Override + public boolean executeInSequence() { + return true; + } + + public String getVolumePath() { + return volumePath; + } +} diff --git a/api/src/com/cloud/agent/api/storage/DestroyAnswer.java b/api/src/com/cloud/agent/api/storage/DestroyAnswer.java index 2f01c1bcd28..ac60015944f 100644 --- a/api/src/com/cloud/agent/api/storage/DestroyAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DestroyAnswer.java @@ -22,7 +22,7 @@ public class DestroyAnswer extends Answer { public DestroyAnswer(DestroyCommand cmd, boolean result, String details) { super(cmd, result, details); } - + // Constructor for gson. protected DestroyAnswer() { super(); diff --git a/api/src/com/cloud/agent/api/storage/DestroyCommand.java b/api/src/com/cloud/agent/api/storage/DestroyCommand.java index 29c564c3bc3..6732ea59c23 100755 --- a/api/src/com/cloud/agent/api/storage/DestroyCommand.java +++ b/api/src/com/cloud/agent/api/storage/DestroyCommand.java @@ -25,25 +25,25 @@ public class DestroyCommand extends StorageCommand { // in VMware, things are designed around VM instead of volume, we need it the volume VM context if the volume is attached String vmName; VolumeTO volume; - + protected DestroyCommand() { } - + public DestroyCommand(StoragePool pool, Volume volume, String vmName) { this.volume = new VolumeTO(volume, pool); this.vmName = vmName; } - + public DestroyCommand(StoragePool pool, VMTemplateStorageResourceAssoc templatePoolRef) { - volume = new VolumeTO(templatePoolRef.getId(), null, pool.getPoolType(), pool.getUuid(), - null, pool.getPath(), templatePoolRef.getInstallPath(), + volume = new VolumeTO(templatePoolRef.getId(), null, pool.getPoolType(), pool.getUuid(), + null, pool.getPath(), templatePoolRef.getInstallPath(), templatePoolRef.getTemplateSize(), null); } - + public VolumeTO getVolume() { return volume; } - + public String getVmName() { return vmName; } diff --git a/api/src/com/cloud/agent/api/storage/DownloadAnswer.java b/api/src/com/cloud/agent/api/storage/DownloadAnswer.java index 52c32455d80..bb7b8a9239c 100755 --- a/api/src/com/cloud/agent/api/storage/DownloadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/DownloadAnswer.java @@ -33,40 +33,40 @@ public class DownloadAnswer extends Answer { private long templateSize = 0L; private long templatePhySicalSize = 0L; private String checkSum; - + public String getCheckSum() { return checkSum; } - + public int getDownloadPct() { return downloadPct; } public String getErrorString() { return errorString; } - + public String getDownloadStatusString() { return downloadStatus.toString(); } - + public VMTemplateStorageResourceAssoc.Status getDownloadStatus() { return downloadStatus; } - + public String getDownloadPath() { return downloadPath; } protected DownloadAnswer() { - + } - + public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } - + public DownloadAnswer(String errorString, Status status) { super(); this.downloadPct = 0; @@ -74,7 +74,7 @@ public class DownloadAnswer extends Answer { this.downloadStatus = status; this.details = errorString; } - + public DownloadAnswer(String jobId, int downloadPct, String errorString, Status downloadStatus, String fileSystemPath, String installPath, long templateSize, long templatePhySicalSize, String checkSum) { super(); @@ -89,7 +89,7 @@ public class DownloadAnswer extends Answer { this.templatePhySicalSize = templatePhySicalSize; this.checkSum = checkSum; } - + public DownloadAnswer(String jobId, int downloadPct, Command command, Status downloadStatus, String fileSystemPath, String installPath) { super(command); @@ -99,7 +99,7 @@ public class DownloadAnswer extends Answer { this.downloadPath = fileSystemPath; this.installPath = installPath; } - + private static String fixPath(String path){ if (path == null) { return path; @@ -112,11 +112,11 @@ public class DownloadAnswer extends Answer { } return path; } - + public void setDownloadStatus(VMTemplateStorageResourceAssoc.Status downloadStatus) { this.downloadStatus = downloadStatus; } - + public String getInstallPath() { return installPath; } @@ -127,7 +127,7 @@ public class DownloadAnswer extends Answer { public void setTemplateSize(long templateSize) { this.templateSize = templateSize; } - + public Long getTemplateSize() { return templateSize; } @@ -137,5 +137,5 @@ public class DownloadAnswer extends Answer { public long getTemplatePhySicalSize() { return templatePhySicalSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/DownloadCommand.java b/api/src/com/cloud/agent/api/storage/DownloadCommand.java index af9ff40b0f2..efb5ecb5256 100644 --- a/api/src/com/cloud/agent/api/storage/DownloadCommand.java +++ b/api/src/com/cloud/agent/api/storage/DownloadCommand.java @@ -21,14 +21,15 @@ import java.net.URI; import com.cloud.storage.Volume; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class DownloadCommand extends AbstractDownloadCommand { +public class DownloadCommand extends AbstractDownloadCommand implements InternalIdentity { public static class PasswordAuth { String userName; String password; public PasswordAuth() { - + } public PasswordAuth(String user, String password) { this.userName = user; @@ -41,28 +42,28 @@ public class DownloadCommand extends AbstractDownloadCommand { return password; } } - + public static enum ResourceType { VOLUME, TEMPLATE } - + public static class Proxy { private String _host; private int _port; private String _userName; private String _password; - + public Proxy() { - + } - + public Proxy(String host, int port, String userName, String password) { this._host = host; this._port = port; this._userName = userName; this._password = password; } - + public Proxy(URI uri) { this._host = uri.getHost(); this._port = uri.getPort() == -1 ? 3128 : uri.getPort(); @@ -78,19 +79,19 @@ public class DownloadCommand extends AbstractDownloadCommand { } } } - + public String getHost() { return _host; } - + public int getPort() { return _port; } - + public String getUserName() { return _userName; } - + public String getPassword() { return _password; } @@ -103,11 +104,11 @@ public class DownloadCommand extends AbstractDownloadCommand { private Long maxDownloadSizeInBytes = null; private long id; private ResourceType resourceType = ResourceType.TEMPLATE; - + protected DownloadCommand() { } - - + + public DownloadCommand(DownloadCommand that) { super(that); this.hvm = that.hvm; @@ -119,7 +120,7 @@ public class DownloadCommand extends AbstractDownloadCommand { this.maxDownloadSizeInBytes = that.getMaxDownloadSizeInBytes(); this.resourceType = that.resourceType; } - + public DownloadCommand(String secUrl, VirtualMachineTemplate template, Long maxDownloadSizeInBytes) { super(template.getUniqueName(), template.getUrl(), template.getFormat(), template.getAccountId()); this.hvm = template.isRequiresHvm(); @@ -129,7 +130,7 @@ public class DownloadCommand extends AbstractDownloadCommand { this.setSecUrl(secUrl); this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; } - + public DownloadCommand(String secUrl, Volume volume, Long maxDownloadSizeInBytes, String checkSum, String url, ImageFormat format) { super(volume.getName(), url, format, volume.getAccountId()); //this.hvm = volume.isRequiresHvm(); @@ -150,11 +151,11 @@ public class DownloadCommand extends AbstractDownloadCommand { this.maxDownloadSizeInBytes = maxDownloadSizeInBytes; auth = new PasswordAuth(user, passwd); } - + public long getId() { return id; } - + public void setHvm(boolean hvm) { this.hvm = hvm; } @@ -188,19 +189,19 @@ public class DownloadCommand extends AbstractDownloadCommand { public PasswordAuth getAuth() { return auth; } - + public void setCreds(String userName, String passwd) { auth = new PasswordAuth(userName, passwd); } - + public Proxy getProxy() { return _proxy; } - + public void setProxy(Proxy proxy) { _proxy = proxy; } - + public Long getMaxDownloadSizeInBytes() { return maxDownloadSizeInBytes; } diff --git a/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java b/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java index 205ba801527..835847bedeb 100644 --- a/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java +++ b/api/src/com/cloud/agent/api/storage/DownloadProgressCommand.java @@ -26,7 +26,7 @@ public class DownloadProgressCommand extends DownloadCommand { protected DownloadProgressCommand() { super(); } - + public DownloadProgressCommand(DownloadCommand cmd, String jobId, RequestType req) { super(cmd); diff --git a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java index 45622faffd3..06e95fe4265 100644 --- a/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ListTemplateAnswer.java @@ -25,17 +25,17 @@ import com.cloud.storage.template.TemplateInfo; public class ListTemplateAnswer extends Answer { private String secUrl; private Map templateInfos; - + public ListTemplateAnswer() { - + } - + public ListTemplateAnswer(String secUrl, Map templateInfos) { super(null, true, "success"); this.setSecUrl(secUrl); - this.templateInfos = templateInfos; + this.templateInfos = templateInfos; } - + public Map getTemplateInfo() { return templateInfos; } diff --git a/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java b/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java index 18123fa1997..da25ed56bf3 100644 --- a/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java +++ b/api/src/com/cloud/agent/api/storage/ListTemplateCommand.java @@ -24,15 +24,15 @@ public class ListTemplateCommand extends StorageCommand { private String secUrl; @LogLevel(Log4jLevel.Off) private SwiftTO swift; - + public ListTemplateCommand() { } - + public ListTemplateCommand(String secUrl) { this.secUrl = secUrl; this.swift = null; } - + public ListTemplateCommand(SwiftTO swift) { this.secUrl = null; this.swift = swift; diff --git a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java index e2dc447ec6d..6bbb2e82c33 100755 --- a/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ListVolumeAnswer.java @@ -14,40 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -import java.util.Map; - -import com.cloud.agent.api.Answer; -import com.cloud.storage.template.TemplateInfo; - -public class ListVolumeAnswer extends Answer { - private String secUrl; - private Map templateInfos; - - public ListVolumeAnswer() { - - } - - public ListVolumeAnswer(String secUrl, Map templateInfos) { - super(null, true, "success"); - this.setSecUrl(secUrl); - this.templateInfos = templateInfos; - } - - public Map getTemplateInfo() { - return templateInfos; - } - - public void setTemplateInfo(Map templateInfos) { - this.templateInfos = templateInfos; - } - - public void setSecUrl(String secUrl) { - this.secUrl = secUrl; - } - - public String getSecUrl() { - return secUrl; - } -} +package com.cloud.agent.api.storage; + +import java.util.Map; + +import com.cloud.agent.api.Answer; +import com.cloud.storage.template.TemplateInfo; + +public class ListVolumeAnswer extends Answer { + private String secUrl; + private Map templateInfos; + + public ListVolumeAnswer() { + + } + + public ListVolumeAnswer(String secUrl, Map templateInfos) { + super(null, true, "success"); + this.setSecUrl(secUrl); + this.templateInfos = templateInfos; + } + + public Map getTemplateInfo() { + return templateInfos; + } + + public void setTemplateInfo(Map templateInfos) { + this.templateInfos = templateInfos; + } + + public void setSecUrl(String secUrl) { + this.secUrl = secUrl; + } + + public String getSecUrl() { + return secUrl; + } +} diff --git a/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java b/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java index afec624b984..a2776c2af46 100755 --- a/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java +++ b/api/src/com/cloud/agent/api/storage/ListVolumeCommand.java @@ -14,30 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.agent.api.storage; - -import com.cloud.agent.api.LogLevel; -import com.cloud.agent.api.LogLevel.Log4jLevel; -import com.cloud.agent.api.to.SwiftTO; - -public class ListVolumeCommand extends StorageCommand { - - private String secUrl; - - public ListVolumeCommand() { - } - - public ListVolumeCommand(String secUrl) { - this.secUrl = secUrl; - } - - @Override - public boolean executeInSequence() { - return true; - } - - public String getSecUrl() { - return secUrl; - } - -} +package com.cloud.agent.api.storage; + +import com.cloud.agent.api.LogLevel; +import com.cloud.agent.api.LogLevel.Log4jLevel; +import com.cloud.agent.api.to.SwiftTO; + +public class ListVolumeCommand extends StorageCommand { + + private String secUrl; + + public ListVolumeCommand() { + } + + public ListVolumeCommand(String secUrl) { + this.secUrl = secUrl; + } + + @Override + public boolean executeInSequence() { + return true; + } + + public String getSecUrl() { + return secUrl; + } + +} diff --git a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java index 354a693ee9d..edd283090b1 100644 --- a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java +++ b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityAnswer.java @@ -20,12 +20,12 @@ import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; public class ManageVolumeAvailabilityAnswer extends Answer { - + protected ManageVolumeAvailabilityAnswer() { } - + public ManageVolumeAvailabilityAnswer(Command command, boolean success, String details) { super(command, success, details); } - + } diff --git a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java index e27fe8ce2b3..1a7d4807f28 100644 --- a/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java +++ b/api/src/com/cloud/agent/api/storage/ManageVolumeAvailabilityCommand.java @@ -19,36 +19,36 @@ package com.cloud.agent.api.storage; import com.cloud.agent.api.Command; public class ManageVolumeAvailabilityCommand extends Command { - + boolean attach; String primaryStorageSRUuid; String volumeUuid; - - - public ManageVolumeAvailabilityCommand() { + + + public ManageVolumeAvailabilityCommand() { } - + public ManageVolumeAvailabilityCommand(boolean attach, String primaryStorageSRUuid, String volumeUuid) { this.attach = attach; this.primaryStorageSRUuid = primaryStorageSRUuid; this.volumeUuid = volumeUuid; } - + @Override public boolean executeInSequence() { return false; } - + public boolean getAttach() { return attach; } - + public String getPrimaryStorageSRUuid() { return primaryStorageSRUuid; } - + public String getVolumeUuid() { return volumeUuid; } - + } diff --git a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java index 3d5c55645ae..a5a6c49e9ab 100644 --- a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadAnswer.java @@ -21,24 +21,24 @@ import com.cloud.agent.api.Answer; public class PrimaryStorageDownloadAnswer extends Answer { private String installPath; private long templateSize = 0L; - + protected PrimaryStorageDownloadAnswer() { } - + public PrimaryStorageDownloadAnswer(String detail) { super(null, false, detail); } - + public PrimaryStorageDownloadAnswer(String installPath, long templateSize ) { super(null); this.installPath = installPath; - this.templateSize = templateSize; + this.templateSize = templateSize; } - + public String getInstallPath() { return installPath; } - + public void setInstallPath(String installPath) { this.installPath = installPath; } @@ -50,5 +50,5 @@ public class PrimaryStorageDownloadAnswer extends Answer { public Long getTemplateSize() { return templateSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java b/api/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java index b56317727e2..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; /** * @@ -26,52 +27,59 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { String localPath; 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); } - + public String getPoolUuid() { return poolUuid; } - + public long getPoolId() { return poolId; } + + public StorageFilerTO getPool() { + return primaryPool; + } public void setLocalPath(String path) { this.localPath = path; } - + public String getLocalPath() { return localPath; } - + public void setSecondaryStorageUrl(String url) { secondaryStorageUrl = url; } - + public String getSecondaryStorageUrl() { return secondaryStorageUrl; } - + public void setPrimaryStorageUrl(String url) { primaryStorageUrl = url; } - + public String getPrimaryStorageUrl() { return primaryStorageUrl; } - + @Override public boolean executeInSequence() { return true; diff --git a/api/src/com/cloud/agent/api/storage/UploadAnswer.java b/api/src/com/cloud/agent/api/storage/UploadAnswer.java index 430eb83c9b0..f2d9788e8dc 100755 --- a/api/src/com/cloud/agent/api/storage/UploadAnswer.java +++ b/api/src/com/cloud/agent/api/storage/UploadAnswer.java @@ -24,7 +24,7 @@ import com.cloud.storage.Upload; public class UploadAnswer extends Answer { - + private String jobId; private int uploadPct; private String errorString; @@ -32,29 +32,29 @@ public class UploadAnswer extends Answer { private String uploadPath; private String installPath; public Long templateSize = 0L; - + public int getUploadPct() { return uploadPct; } public String getErrorString() { return errorString; } - + public String getUploadStatusString() { return uploadStatus.toString(); } - + public Upload.Status getUploadStatus() { return uploadStatus; } - + public String getUploadPath() { return uploadPath; } protected UploadAnswer() { - + } - + public void setErrorString(String errorString) { this.errorString = errorString; } @@ -64,7 +64,7 @@ public class UploadAnswer extends Answer { public void setJobId(String jobId) { this.jobId = jobId; } - + public UploadAnswer(String jobId, int uploadPct, String errorString, Upload.Status uploadStatus, String fileSystemPath, String installPath, long templateSize) { super(); @@ -87,7 +87,7 @@ public class UploadAnswer extends Answer { this.uploadPath = fileSystemPath; this.installPath = installPath; } - + private static String fixPath(String path){ if (path == null) { return path; @@ -100,11 +100,11 @@ public class UploadAnswer extends Answer { } return path; } - + public void setUploadStatus(Upload.Status uploadStatus) { this.uploadStatus = uploadStatus; } - + public String getInstallPath() { return installPath; } @@ -115,9 +115,9 @@ public class UploadAnswer extends Answer { public void setTemplateSize(long templateSize) { this.templateSize = templateSize; } - + public Long getTemplateSize() { return templateSize; } - + } diff --git a/api/src/com/cloud/agent/api/storage/UploadCommand.java b/api/src/com/cloud/agent/api/storage/UploadCommand.java index 4b004c91ed7..2a7c60a51ff 100644 --- a/api/src/com/cloud/agent/api/storage/UploadCommand.java +++ b/api/src/com/cloud/agent/api/storage/UploadCommand.java @@ -20,13 +20,14 @@ import com.cloud.agent.api.storage.DownloadCommand.PasswordAuth; import com.cloud.agent.api.to.TemplateTO; import com.cloud.storage.Upload.Type; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class UploadCommand extends AbstractUploadCommand { +public class UploadCommand extends AbstractUploadCommand implements InternalIdentity { private TemplateTO template; private String url; - private String installPath; + private String installPath; private boolean hvm; private String description; private String checksum; @@ -36,16 +37,16 @@ public class UploadCommand extends AbstractUploadCommand { private Type type; public UploadCommand(VirtualMachineTemplate template, String url, String installPath, long sizeInBytes) { - + this.template = new TemplateTO(template); this.url = url; this.installPath = installPath; this.checksum = template.getChecksum(); this.id = template.getId(); this.templateSizeInBytes = sizeInBytes; - + } - + public UploadCommand(String url, long id, long sizeInBytes, String installPath, Type type){ this.template = null; this.url = url; @@ -54,10 +55,10 @@ public class UploadCommand extends AbstractUploadCommand { this.type = type; this.templateSizeInBytes = sizeInBytes; } - + protected UploadCommand() { } - + public UploadCommand(UploadCommand that) { this.template = that.template; this.url = that.url; diff --git a/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java b/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java index 36b1437ef90..7f6d584045d 100644 --- a/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java +++ b/api/src/com/cloud/agent/api/storage/UploadProgressCommand.java @@ -25,7 +25,7 @@ public class UploadProgressCommand extends UploadCommand { protected UploadProgressCommand() { super(); } - + public UploadProgressCommand(UploadCommand cmd, String jobId, RequestType req) { super(cmd); @@ -44,5 +44,5 @@ public class UploadProgressCommand extends UploadCommand { public RequestType getRequest() { return request; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/agent/api/storage/ssCommand.java b/api/src/com/cloud/agent/api/storage/ssCommand.java index c7b75ea3873..c218a8d5b79 100644 --- a/api/src/com/cloud/agent/api/storage/ssCommand.java +++ b/api/src/com/cloud/agent/api/storage/ssCommand.java @@ -22,21 +22,21 @@ public abstract class ssCommand extends Command { private String secUrl; - public ssCommand() { + public ssCommand() { } - + protected ssCommand(ssCommand that) { this.secUrl = that.secUrl; } public ssCommand(String secUrl) { this.secUrl = secUrl; } - + @Override public boolean executeInSequence() { return true; } - + public String getSecUrl() { return secUrl; } @@ -44,5 +44,5 @@ public abstract class ssCommand extends Command { public void setSecUrl(String secUrl) { this.secUrl = secUrl; } - + } diff --git a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java index 01860204c00..95ac57c3867 100644 --- a/api/src/com/cloud/agent/api/to/FirewallRuleTO.java +++ b/api/src/com/cloud/agent/api/to/FirewallRuleTO.java @@ -22,22 +22,23 @@ import java.util.List; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.State; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; /** * FirewallRuleTO transfers a port range for an ip to be opened. - * + * * There are essentially three states transferred with each state. - * sent multiple times to the destination. If the rule is not on + * sent multiple times to the destination. If the rule is not on * 2. alreadyAdded - the rule has been successfully added before. Rules * in this state are sent for completeness and optimization. * If the rule already exists on the destination, the destination should * reply the rule is successfully applied. - * + * * - srcPortRange: port range to open. * - protocol: protocol to open for. Usually tcp and udp. * */ -public class FirewallRuleTO { +public class FirewallRuleTO implements InternalIdentity { long id; String srcVlanTag; String srcIp; @@ -49,34 +50,35 @@ public class FirewallRuleTO { FirewallRule.Purpose purpose; private Integer icmpType; private Integer icmpCode; - + protected FirewallRuleTO() { } - + public FirewallRuleTO(long id, String srcIp, String protocol, Integer srcPortStart, Integer srcPortEnd, boolean revoked, boolean alreadyAdded, FirewallRule.Purpose purpose, List sourceCidr,Integer icmpType,Integer icmpCode) { this(id,null,srcIp,protocol,srcPortStart,srcPortEnd,revoked,alreadyAdded,purpose,sourceCidr,icmpType,icmpCode); - } + } public FirewallRuleTO(long id,String srcVlanTag, String srcIp, String protocol, Integer srcPortStart, Integer srcPortEnd, boolean revoked, boolean alreadyAdded, FirewallRule.Purpose purpose, List sourceCidr,Integer icmpType,Integer icmpCode) { + this.id = id; this.srcVlanTag = srcVlanTag; this.srcIp = srcIp; this.protocol = protocol; - + if (srcPortStart != null) { List portRange = new ArrayList(); portRange.add(srcPortStart); if (srcPortEnd != null) { portRange.add(srcPortEnd); } - + srcPortRange = new int[portRange.size()]; int i = 0; for (Integer port : portRange) { srcPortRange[i] = port.intValue(); i ++; - } - } - + } + } + this.revoked = revoked; this.alreadyAdded = alreadyAdded; this.purpose = purpose; @@ -87,11 +89,11 @@ public class FirewallRuleTO { public FirewallRuleTO(FirewallRule rule, String srcVlanTag, String srcIp) { this(rule.getId(),srcVlanTag, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(),rule.getSourceCidrList(),rule.getIcmpType(),rule.getIcmpCode()); } - + public FirewallRuleTO(FirewallRule rule, String srcIp) { this(rule.getId(),null, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(),rule.getSourceCidrList(),rule.getIcmpType(),rule.getIcmpCode()); } - + public long getId() { return id; } @@ -99,7 +101,7 @@ public class FirewallRuleTO { public String getSrcVlanTag() { return srcVlanTag; } - + public String getSrcIp() { return srcIp; } @@ -111,15 +113,15 @@ public class FirewallRuleTO { public int[] getSrcPortRange() { return srcPortRange; } - + public Integer getIcmpType(){ return icmpType; } - + public Integer getIcmpCode(){ - return icmpCode; + return icmpCode; } - + public String getStringSrcPortRange() { if (srcPortRange == null || srcPortRange.length < 2) return "0:0"; @@ -130,11 +132,11 @@ public class FirewallRuleTO { public boolean revoked() { return revoked; } - + public List getSourceCidrList() { return sourceCidrList; } - + public boolean isAlreadyAdded() { return alreadyAdded; } @@ -142,5 +144,5 @@ public class FirewallRuleTO { public FirewallRule.Purpose getPurpose() { return purpose; } - + } diff --git a/api/src/com/cloud/agent/api/to/HostTO.java b/api/src/com/cloud/agent/api/to/HostTO.java index f7b734c19d2..967a63d63b5 100644 --- a/api/src/com/cloud/agent/api/to/HostTO.java +++ b/api/src/com/cloud/agent/api/to/HostTO.java @@ -24,10 +24,10 @@ public class HostTO { private NetworkTO publicNetwork; private NetworkTO storageNetwork1; private NetworkTO storageNetwork2; - + protected HostTO() { } - + public HostTO(Host vo) { guid = vo.getGuid(); privateNetwork = new NetworkTO(vo.getPrivateIpAddress(), vo.getPrivateNetmask(), vo.getPrivateMacAddress()); diff --git a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java index d0eeb66b77e..2d166ea1e1e 100644 --- a/api/src/com/cloud/agent/api/to/LoadBalancerTO.java +++ b/api/src/com/cloud/agent/api/to/LoadBalancerTO.java @@ -17,30 +17,50 @@ package com.cloud.agent.api.to; +import java.io.Serializable; +import java.util.ArrayList; import java.util.List; -import com.cloud.utils.Pair; + +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.Condition; +import com.cloud.network.as.Counter; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScalePolicy; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmProfile; +import com.cloud.network.lb.LoadBalancingRule.LbCondition; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; +import com.cloud.utils.Pair; public class LoadBalancerTO { + String uuid; String srcIp; int srcPort; String protocol; - String algorithm; + String algorithm; boolean revoked; boolean alreadyAdded; + boolean inline; DestinationTO[] destinations; private StickinessPolicyTO[] stickinessPolicies; - final static int MAX_STICKINESS_POLICIES = 1; - - public LoadBalancerTO (String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, List destinations) { + private AutoScaleVmGroupTO autoScaleVmGroupTO; + final static int MAX_STICKINESS_POLICIES = 1; + + public LoadBalancerTO(String uuid, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, boolean inline, List destinations) { + if (destinations == null) { // for autoscaleconfig destinations will be null; + destinations = new ArrayList(); + } + this.uuid = uuid; this.srcIp = srcIp; this.srcPort = srcPort; this.protocol = protocol; - this.algorithm = algorithm; + this.algorithm = algorithm; this.revoked = revoked; this.alreadyAdded = alreadyAdded; + this.inline = inline; this.destinations = new DestinationTO[destinations.size()]; this.stickinessPolicies = null; int i = 0; @@ -48,11 +68,11 @@ public class LoadBalancerTO { this.destinations[i++] = new DestinationTO(destination.getIpAddress(), destination.getDestinationPortStart(), destination.isRevoked(), false); } } - - public LoadBalancerTO (String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, List arg_destinations, List stickinessPolicies) { - this(srcIp, srcPort, protocol, algorithm, revoked, alreadyAdded, arg_destinations); + + public LoadBalancerTO(String id, String srcIp, int srcPort, String protocol, String algorithm, boolean revoked, boolean alreadyAdded, boolean inline, List arg_destinations, List stickinessPolicies) { + this(id, srcIp, srcPort, protocol, algorithm, revoked, alreadyAdded, inline, arg_destinations); this.stickinessPolicies = null; - if (stickinessPolicies != null && stickinessPolicies.size()>0) { + if (stickinessPolicies != null && stickinessPolicies.size() > 0) { this.stickinessPolicies = new StickinessPolicyTO[MAX_STICKINESS_POLICIES]; int index = 0; for (LbStickinessPolicy stickinesspolicy : stickinessPolicies) { @@ -60,16 +80,20 @@ public class LoadBalancerTO { this.stickinessPolicies[index] = new StickinessPolicyTO(stickinesspolicy.getMethodName(), stickinesspolicy.getParams()); index++; if (index == MAX_STICKINESS_POLICIES) break; + } } - } if (index == 0) this.stickinessPolicies = null; - } - } - - + } + } + + protected LoadBalancerTO() { } - + + public String getUuid() { + return uuid; + } + public String getSrcIp() { return srcIp; } @@ -93,15 +117,31 @@ public class LoadBalancerTO { public boolean isAlreadyAdded() { return alreadyAdded; } - + + public boolean isInline() { + return inline; + } + public StickinessPolicyTO[] getStickinessPolicies() { return stickinessPolicies; } - + public DestinationTO[] getDestinations() { return destinations; } - + + public AutoScaleVmGroupTO getAutoScaleVmGroupTO() { + return autoScaleVmGroupTO; + } + + public void setAutoScaleVmGroupTO(AutoScaleVmGroupTO autoScaleVmGroupTO) { + this.autoScaleVmGroupTO = autoScaleVmGroupTO; + } + + public boolean isAutoScaleVmGroupTO() { + return this.autoScaleVmGroupTO != null; + } + public static class StickinessPolicyTO { private String _methodName; private List> _paramsList; @@ -119,7 +159,7 @@ public class LoadBalancerTO { this._paramsList = paramsList; } } - + public static class DestinationTO { String destIp; int destPort; @@ -131,18 +171,18 @@ public class LoadBalancerTO { this.revoked = revoked; this.alreadyAdded = alreadyAdded; } - + protected DestinationTO() { } - + public String getDestIp() { return destIp; } - + public int getDestPort() { return destPort; } - + public boolean isRevoked() { return revoked; } @@ -151,5 +191,268 @@ public class LoadBalancerTO { return alreadyAdded; } } + public static class CounterTO implements Serializable { + private final String name; + private final String source; + private final String value; + + public CounterTO(String name, String source, String value) { + this.name = name; + this.source = source; + this.value = value; + } + + public String getName() { + return name; + } + + public String getSource() { + return source; + } + + public String getValue() { + return value; + } + } + + public static class ConditionTO implements Serializable { + private final long threshold; + private final String relationalOperator; + private final CounterTO counter; + + public ConditionTO(long threshold, String relationalOperator, CounterTO counter) + { + this.threshold = threshold; + this.relationalOperator = relationalOperator; + this.counter = counter; + } + + public long getThreshold() { + return threshold; + } + + public String getRelationalOperator() { + return relationalOperator; + } + + public CounterTO getCounter() { + return counter; + } + } + + public static class AutoScalePolicyTO implements Serializable { + private final long id; + private final int duration; + private final int quietTime; + private String action; + boolean revoked; + private final List conditions; + + public AutoScalePolicyTO(long id, int duration, int quietTime, String action, List conditions, boolean revoked) { + this.id = id; + this.duration = duration; + this.quietTime = quietTime; + this.conditions = conditions; + this.action = action; + this.revoked = revoked; + } + + public long getId() { + return id; + } + + public int getDuration() { + return duration; + } + + public int getQuietTime() { + return quietTime; + } + + public String getAction() { + return action; + } + + public boolean isRevoked() { + return revoked; + } + + public List getConditions() { + return conditions; + } + } + + public static class AutoScaleVmProfileTO implements Serializable { + private final String zoneId; + private final String domainId; + private final String serviceOfferingId; + private final String templateId; + private final String otherDeployParams; + private final List> counterParamList; + private final Integer destroyVmGraceperiod; + private final String cloudStackApiUrl; + private final String autoScaleUserApiKey; + private final String autoScaleUserSecretKey; + private final String vmName; + private final String networkId; + + public AutoScaleVmProfileTO(String zoneId, String domainId, String cloudStackApiUrl, String autoScaleUserApiKey, String autoScaleUserSecretKey, String serviceOfferingId, + String templateId, String vmName, String networkId, String otherDeployParams, List> counterParamList, Integer destroyVmGraceperiod) { + this.zoneId = zoneId; + this.domainId = domainId; + this.serviceOfferingId = serviceOfferingId; + this.templateId = templateId; + this.otherDeployParams = otherDeployParams; + this.counterParamList = counterParamList; + this.destroyVmGraceperiod = destroyVmGraceperiod; + this.cloudStackApiUrl = cloudStackApiUrl; + this.autoScaleUserApiKey = autoScaleUserApiKey; + this.autoScaleUserSecretKey = autoScaleUserSecretKey; + this.vmName = vmName; + this.networkId = networkId; + } + + public String getZoneId() { + return zoneId; + } + + public String getDomainId() { + return domainId; + } + + public String getServiceOfferingId() { + return serviceOfferingId; + } + + public String getTemplateId() { + return templateId; + } + + public String getOtherDeployParams() { + return otherDeployParams; + } + + public List> getCounterParamList() { + return counterParamList; + } + + public Integer getDestroyVmGraceperiod() { + return destroyVmGraceperiod; + } + + public String getCloudStackApiUrl() { + return cloudStackApiUrl; + } + + public String getAutoScaleUserApiKey() { + return autoScaleUserApiKey; + } + + public String getAutoScaleUserSecretKey() { + return autoScaleUserSecretKey; + } + + public String getVmName() { + return vmName; + } + + public String getNetworkId() { + return networkId; + } + } + + public static class AutoScaleVmGroupTO implements Serializable { + private final String uuid; + private final int minMembers; + private final int maxMembers; + private final int memberPort; + private final int interval; + private final List policies; + private final AutoScaleVmProfileTO profile; + private final String state; + private final String currentState; + + AutoScaleVmGroupTO(String uuid, int minMembers, int maxMembers, int memberPort, int interval, List policies, AutoScaleVmProfileTO profile, String state, String currentState) + { + this.uuid = uuid; + this.minMembers = minMembers; + this.maxMembers = maxMembers; + this.memberPort = memberPort; + this.interval = interval; + this.policies = policies; + this.profile = profile; + this.state = state; + this.currentState = currentState; + } + + public String getUuid() { + return uuid; + } + + public int getMinMembers() { + return minMembers; + } + + public int getMaxMembers() { + return maxMembers; + } + + public int getMemberPort() { + return memberPort; + } + + public int getInterval() { + return interval; + } + + public List getPolicies() { + return policies; + } + + public AutoScaleVmProfileTO getProfile() { + return profile; + } + + public String getState() { + return state; + } + + public String getCurrentState() { + return currentState; + } + } + + public void setAutoScaleVmGroup(LbAutoScaleVmGroup lbAutoScaleVmGroup) + { + List lbAutoScalePolicies = lbAutoScaleVmGroup.getPolicies(); + List autoScalePolicyTOs = new ArrayList(lbAutoScalePolicies.size()); + for (LbAutoScalePolicy lbAutoScalePolicy : lbAutoScalePolicies) { + List lbConditions = lbAutoScalePolicy.getConditions(); + List conditionTOs = new ArrayList(lbConditions.size()); + for (LbCondition lbCondition : lbConditions) { + Counter counter = lbCondition.getCounter(); + CounterTO counterTO = new CounterTO(counter.getName(), counter.getSource().toString(), "" + counter.getValue()); + Condition condition = lbCondition.getCondition(); + ConditionTO conditionTO = new ConditionTO(condition.getThreshold(), condition.getRelationalOperator().toString(), counterTO); + conditionTOs.add(conditionTO); + } + AutoScalePolicy autoScalePolicy = lbAutoScalePolicy.getPolicy(); + autoScalePolicyTOs.add(new AutoScalePolicyTO(autoScalePolicy.getId(), autoScalePolicy.getDuration(), + autoScalePolicy.getQuietTime(), autoScalePolicy.getAction(), + conditionTOs, lbAutoScalePolicy.isRevoked())); + } + LbAutoScaleVmProfile lbAutoScaleVmProfile = lbAutoScaleVmGroup.getProfile(); + AutoScaleVmProfile autoScaleVmProfile = lbAutoScaleVmProfile.getProfile(); + + AutoScaleVmProfileTO autoScaleVmProfileTO = new AutoScaleVmProfileTO(lbAutoScaleVmProfile.getZoneId(), lbAutoScaleVmProfile.getDomainId(), + lbAutoScaleVmProfile.getCsUrl(), lbAutoScaleVmProfile.getAutoScaleUserApiKey(), lbAutoScaleVmProfile.getAutoScaleUserSecretKey(), + lbAutoScaleVmProfile.getServiceOfferingId(), lbAutoScaleVmProfile.getTemplateId(), lbAutoScaleVmProfile.getVmName(), + lbAutoScaleVmProfile.getNetworkId(),autoScaleVmProfile.getOtherDeployParams(), autoScaleVmProfile.getCounterParams(), + autoScaleVmProfile.getDestroyVmGraceperiod()); + + AutoScaleVmGroup autoScaleVmGroup = lbAutoScaleVmGroup.getVmGroup(); + autoScaleVmGroupTO = new AutoScaleVmGroupTO(autoScaleVmGroup.getUuid(), autoScaleVmGroup.getMinMembers(), autoScaleVmGroup.getMaxMembers(), autoScaleVmGroup.getMemberPort(), + autoScaleVmGroup.getInterval(), autoScalePolicyTOs, autoScaleVmProfileTO, autoScaleVmGroup.getState(), lbAutoScaleVmGroup.getCurrentState()); + } } diff --git a/api/src/com/cloud/agent/api/to/NetworkACLTO.java b/api/src/com/cloud/agent/api/to/NetworkACLTO.java index 3cdf8fb476e..9b1a6296b08 100644 --- a/api/src/com/cloud/agent/api/to/NetworkACLTO.java +++ b/api/src/com/cloud/agent/api/to/NetworkACLTO.java @@ -23,9 +23,10 @@ import java.util.List; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.TrafficType; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; -public class NetworkACLTO { +public class NetworkACLTO implements InternalIdentity { long id; String vlanTag; String protocol; @@ -36,32 +37,32 @@ public class NetworkACLTO { private Integer icmpType; private Integer icmpCode; private FirewallRule.TrafficType trafficType; - + protected NetworkACLTO() { } - + public NetworkACLTO(long id,String vlanTag, String protocol, Integer portStart, Integer portEnd, boolean revoked, boolean alreadyAdded, List cidrList, Integer icmpType,Integer icmpCode,TrafficType trafficType) { this.vlanTag = vlanTag; this.protocol = protocol; - + if (portStart != null) { List range = new ArrayList(); range.add(portStart); if (portEnd != null) { range.add(portEnd); } - + portRange = new int[range.size()]; int i = 0; for (Integer port : range) { portRange[i] = port.intValue(); i ++; - } - } - + } + } + this.revoked = revoked; this.alreadyAdded = alreadyAdded; this.cidrList = cidrList; @@ -71,11 +72,11 @@ public class NetworkACLTO { } public NetworkACLTO(FirewallRule rule, String vlanTag, FirewallRule.TrafficType trafficType ) { - this(rule.getId(), vlanTag, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), + this(rule.getId(), vlanTag, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(), rule.getState() == FirewallRule.State.Revoke, rule.getState() == FirewallRule.State.Active, rule.getSourceCidrList() ,rule.getIcmpType(), rule.getIcmpCode(),trafficType); } - + public long getId() { return id; } @@ -91,15 +92,15 @@ public class NetworkACLTO { public int[] getSrcPortRange() { return portRange; } - + public Integer getIcmpType(){ return icmpType; } - + public Integer getIcmpCode(){ - return icmpCode; + return icmpCode; } - + public String getStringPortRange() { if (portRange == null || portRange.length < 2) return "0:0"; @@ -110,11 +111,11 @@ public class NetworkACLTO { public boolean revoked() { return revoked; } - + public List getSourceCidrList() { return cidrList; } - + public boolean isAlreadyAdded() { return alreadyAdded; } diff --git a/api/src/com/cloud/agent/api/to/NetworkTO.java b/api/src/com/cloud/agent/api/to/NetworkTO.java index ad9d4d90ee7..3edd4c0f937 100644 --- a/api/src/com/cloud/agent/api/to/NetworkTO.java +++ b/api/src/com/cloud/agent/api/to/NetworkTO.java @@ -100,7 +100,7 @@ public class NetworkTO { /** * This constructor is usually for hosts where the other information are not important. - * + * * @param ip ip address * @param netmask netmask * @param mac mac address @@ -112,7 +112,7 @@ public class NetworkTO { /** * This is the full constructor and should be used for VM's network as it contains * the full information about what is needed. - * + * * @param ip * @param vlan * @param netmask diff --git a/api/src/com/cloud/agent/api/to/NicTO.java b/api/src/com/cloud/agent/api/to/NicTO.java index 79a43d2e625..aa2aa19cc19 100644 --- a/api/src/com/cloud/agent/api/to/NicTO.java +++ b/api/src/com/cloud/agent/api/to/NicTO.java @@ -26,45 +26,45 @@ public class NicTO extends NetworkTO { public NicTO() { super(); } - + public void setDeviceId(int deviceId) { this.deviceId = deviceId; } - + public int getDeviceId() { return deviceId; } - + public Integer getNetworkRateMbps() { return networkRateMbps; } - + public void setNetworkRateMbps(Integer networkRateMbps) { this.networkRateMbps = networkRateMbps; } - + public Integer getNetworkRateMulticastMbps() { return networkRateMulticastMbps; } - + public boolean isDefaultNic() { return defaultNic; } - + public void setDefaultNic(boolean defaultNic) { this.defaultNic = defaultNic; } - + @Override public String getUuid() { return uuid; } - + @Override public void setUuid(String uuid) { this.uuid = uuid; } - + @Override public String toString() { return new StringBuilder("[Nic:").append(type).append("-").append(ip).append("-").append(broadcastUri).append("]").toString(); diff --git a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java index c99a3766642..c23dce8ea86 100644 --- a/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java +++ b/api/src/com/cloud/agent/api/to/PortForwardingRuleTO.java @@ -22,25 +22,25 @@ import com.cloud.utils.net.NetUtils; /** * PortForwardingRuleTO specifies one port forwarding rule. - * + * * */ public class PortForwardingRuleTO extends FirewallRuleTO { String dstIp; int[] dstPortRange; - + protected PortForwardingRuleTO() { super(); } - + public PortForwardingRuleTO(PortForwardingRule rule, String srcVlanTag, String srcIp) { super(rule, srcVlanTag, srcIp); this.dstIp = rule.getDestinationIpAddress().addr(); 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 }; } @@ -56,5 +56,5 @@ public class PortForwardingRuleTO extends FirewallRuleTO { public String getStringDstPortRange() { return NetUtils.portRangeToString(dstPortRange); } - + } 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/agent/api/to/StaticNatRuleTO.java b/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java index fd77dd69578..64ca266a1ca 100644 --- a/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java +++ b/api/src/com/cloud/agent/api/to/StaticNatRuleTO.java @@ -22,34 +22,39 @@ import com.cloud.network.rules.StaticNatRule; /** * StaticNatRuleTO specifies one static nat rule. - * + * * */ public class StaticNatRuleTO extends FirewallRuleTO{ String dstIp; - + protected StaticNatRuleTO() { } - + public StaticNatRuleTO(StaticNatRule rule, String srcVlanTag, String srcIp, String dstIp) { super(rule.getId(),srcVlanTag, srcIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(),rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(), null,0,0); this.dstIp = dstIp; } - + public StaticNatRuleTO(StaticNatRule rule, String scrIp, String dstIp) { super(rule.getId(), scrIp, rule.getProtocol(), rule.getSourcePortStart(), rule.getSourcePortEnd(),rule.getState()==State.Revoke, rule.getState()==State.Active, rule.getPurpose(), null,0,0); this.dstIp = dstIp; } - - + + public StaticNatRuleTO(long id, String srcIp, Integer srcPortStart, Integer srcPortEnd, String dstIp, Integer dstPortStart, Integer dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { super(id, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.StaticNat, null,0,0); this.dstIp = dstIp; } + + public StaticNatRuleTO(long id,String srcVlanTag, String srcIp, Integer srcPortStart, Integer srcPortEnd, String dstIp, Integer dstPortStart, Integer dstPortEnd, String protocol, boolean revoked, boolean alreadyAdded) { + super(id, srcVlanTag, srcIp, protocol, srcPortStart, srcPortEnd, revoked, alreadyAdded, FirewallRule.Purpose.StaticNat, null,0,0); + this.dstIp = dstIp; + } public String getDstIp() { return dstIp; } - + } diff --git a/api/src/com/cloud/agent/api/to/StorageFilerTO.java b/api/src/com/cloud/agent/api/to/StorageFilerTO.java index 26344daaeb6..8f58c9e1c91 100644 --- a/api/src/com/cloud/agent/api/to/StorageFilerTO.java +++ b/api/src/com/cloud/agent/api/to/StorageFilerTO.java @@ -27,7 +27,7 @@ public class StorageFilerTO { String userInfo; int port; StoragePoolType type; - + public StorageFilerTO(StoragePool pool) { this.id = pool.getId(); this.host = pool.getHostAddress(); @@ -61,14 +61,14 @@ public class StorageFilerTO { public int getPort() { return port; } - + public StoragePoolType getType() { return type; } - + protected StorageFilerTO() { } - + @Override public String toString() { return new StringBuilder("Pool[").append(id).append("|").append(host).append(":").append(port).append("|").append(path).append("]").toString(); diff --git a/api/src/com/cloud/agent/api/to/SwiftTO.java b/api/src/com/cloud/agent/api/to/SwiftTO.java index 7920ce83e27..32742c7d0e3 100644 --- a/api/src/com/cloud/agent/api/to/SwiftTO.java +++ b/api/src/com/cloud/agent/api/to/SwiftTO.java @@ -15,15 +15,15 @@ // specific language governing permissions and limitations // under the License. package com.cloud.agent.api.to; - + public class SwiftTO { Long id; String url; String account; - + String userName; String key; - + public SwiftTO() { } public SwiftTO(Long id, String url, String account, String userName, String key) { @@ -33,7 +33,7 @@ public class SwiftTO { this.userName = userName; this.key = key; } - + public Long getId() { return id; } @@ -53,6 +53,6 @@ public class SwiftTO { public String getKey() { return key; } - + } diff --git a/api/src/com/cloud/agent/api/to/TemplateTO.java b/api/src/com/cloud/agent/api/to/TemplateTO.java index e163340fbf0..d77b80551f4 100644 --- a/api/src/com/cloud/agent/api/to/TemplateTO.java +++ b/api/src/com/cloud/agent/api/to/TemplateTO.java @@ -18,21 +18,22 @@ package com.cloud.agent.api.to; import com.cloud.storage.Storage.ImageFormat; import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.InternalIdentity; -public class TemplateTO { +public class TemplateTO implements InternalIdentity { private long id; private String uniqueName; private ImageFormat format; - + protected TemplateTO() { } - + public TemplateTO(VirtualMachineTemplate template) { this.id = template.getId(); this.uniqueName = template.getUniqueName(); this.format = template.getFormat(); } - + public long getId() { return id; } diff --git a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java index a93c242b7c1..8f3f0eb39d6 100644 --- a/api/src/com/cloud/agent/api/to/VirtualMachineTO.java +++ b/api/src/com/cloud/agent/api/to/VirtualMachineTO.java @@ -108,7 +108,7 @@ public class VirtualMachineTO { public boolean getLimitCpuUse() { return limitCpuUse; } - + public long getMinRam() { return minRam; } @@ -185,11 +185,11 @@ public class VirtualMachineTO { public void setNics(NicTO[] nics) { this.nics = nics; } - + public String getVncPassword() { return this.vncPassword; } - + public void setVncPassword(String vncPassword) { this.vncPassword = vncPassword; } @@ -201,11 +201,11 @@ public class VirtualMachineTO { public void setVncAddr(String vncAddr) { this.vncAddr = vncAddr; } - + public Map getDetails() { return params; } - + public void setDetails(Map params) { this.params = params; } @@ -217,6 +217,6 @@ public class VirtualMachineTO { public void setUuid(String uuid) { this.uuid = uuid; } - - + + } diff --git a/api/src/com/cloud/agent/api/to/VolumeTO.java b/api/src/com/cloud/agent/api/to/VolumeTO.java index ca0acb57876..ff739c58f80 100644 --- a/api/src/com/cloud/agent/api/to/VolumeTO.java +++ b/api/src/com/cloud/agent/api/to/VolumeTO.java @@ -19,8 +19,9 @@ package com.cloud.agent.api.to; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.StoragePool; import com.cloud.storage.Volume; +import org.apache.cloudstack.api.InternalIdentity; -public class VolumeTO { +public class VolumeTO implements InternalIdentity { protected VolumeTO() { } diff --git a/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java b/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java index 23f0a7e0fb9..10001b149fa 100644 --- a/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java +++ b/api/src/com/cloud/agent/api/uploadTemplateToSwiftFromSecondaryStorageCommand.java @@ -20,8 +20,8 @@ import com.cloud.agent.api.LogLevel.Log4jLevel; import com.cloud.agent.api.to.SwiftTO; /** - * - * + * + * */ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { @@ -34,9 +34,9 @@ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { private Long templateId; protected uploadTemplateToSwiftFromSecondaryStorageCommand() { - + } - + public uploadTemplateToSwiftFromSecondaryStorageCommand(SwiftTO swift, String secondaryStorageUrl, Long dcId, Long accountId, Long templateId, int wait) { this.swift = swift; @@ -77,4 +77,4 @@ public class uploadTemplateToSwiftFromSecondaryStorageCommand extends Command { return true; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/alert/Alert.java b/api/src/com/cloud/alert/Alert.java index c9368a34522..defd15490e5 100644 --- a/api/src/com/cloud/alert/Alert.java +++ b/api/src/com/cloud/alert/Alert.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.alert; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface Alert { - long getId(); +public interface Alert extends Identity, InternalIdentity { short getType(); String getSubject(); Long getPodId(); diff --git a/api/src/com/cloud/api/commands/.gitignore b/api/src/com/cloud/api/commands/.gitignore index 63e3fa0c721..62042786c83 100644 --- a/api/src/com/cloud/api/commands/.gitignore +++ b/api/src/com/cloud/api/commands/.gitignore @@ -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/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java index 99fd48f82d2..92c7ac58be0 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java +++ b/api/src/com/cloud/api/commands/CreatePrivateNetworkCmd.java @@ -16,16 +16,14 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -33,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.network.Network; import com.cloud.user.UserContext; -@Implementation(description="Creates a private network", responseObject=NetworkResponse.class) +@APICommand(description="Creates a private network", responseObject=NetworkResponse.class) public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePrivateNetworkCmd.class.getName()); @@ -42,42 +40,42 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the network") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the network") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + " range. If not specified, will be defaulted to startIP") private String endIp; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the ID or VID of the network") private String vlan; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a network") private Long domainId; @@ -100,7 +98,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -108,23 +106,23 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public String getStartIp() { return startIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + public Long getProjectId() { return projectId; } - + public long getPhysicalNetworkId() { return physicalNetworkId; } - + public String getEndIp() { return endIp; } @@ -136,8 +134,8 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { Network result = null; @@ -152,14 +150,14 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a Private network"); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.getNetwork(getEntityId()); @@ -171,7 +169,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private network"); } } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); @@ -191,7 +189,7 @@ public class CreatePrivateNetworkCmd extends BaseAsyncCreateCmd { return "creating private network"; } - + @Override public String getEntityTable() { return "networks"; diff --git a/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java b/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java deleted file mode 100755 index 8299ec94693..00000000000 --- a/api/src/com/cloud/api/commands/CreateStorageNetworkIpRangeCmd.java +++ /dev/null @@ -1,127 +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.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; - -@Implementation(description="Creates a Storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") -public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CreateStorageNetworkIpRangeCmd.class); - - private static final String s_name = "createstoragenetworkiprangeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, required=true, description="UUID of pod where the ip range belongs to") - private Long podId; - - @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address") - private String startIp; - - @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") - private String endIp; - - @Parameter(name = ApiConstants.VLAN, type = CommandType.INTEGER, description = "Optional. The vlan the ip range sits on, default to Null when it is not specificed which means you network is not on any Vlan. This is mainly for Vmware as other hypervisors can directly reterive bridge from pyhsical network traffic type table") - private Integer vlan; - - @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for storage network") - private String netmask; - - @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for storage network") - private String gateway; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getEndIp() { - return endIp; - } - - public Long getPodId() { - return podId; - } - - public String getStartIp() { - return startIp; - } - - public Integer getVlan() { - return vlan; - } - - public String getNetmask() { - return netmask; - } - - public String getGateWay() { - return gateway; - } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_CREATE; - } - - @Override - public String getEventDescription() { - return "Creating storage ip range from " + getStartIp() + " to " + getEndIp() + " with vlan " + getVlan(); - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - StorageNetworkIpRange result = _storageNetworkService.createIpRange(this); - StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Create storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - -} diff --git a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java index 3ae61c1118b..17bafb1918d 100644 --- a/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java +++ b/api/src/com/cloud/api/commands/DestroyConsoleProxyCmd.java @@ -16,25 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Destroys console proxy", responseObject=SuccessResponse.class) +@APICommand(description="Destroys console proxy", responseObject=SuccessResponse.class) public class DestroyConsoleProxyCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DestroyConsoleProxyCmd.class.getName()); private static final String s_name = "destroyconsoleproxyresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -80,7 +76,7 @@ public class DestroyConsoleProxyCmd extends BaseAsyncCmd { public String getEventDescription() { return "destroying console proxy: " + getId(); } - + @Override public void execute(){ boolean result = _consoleProxyService.destroyConsoleProxy(this); diff --git a/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java b/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java index 7583cc06a05..41f28f93110 100644 --- a/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java +++ b/api/src/com/cloud/api/commands/ListRecurringSnapshotScheduleCmd.java @@ -19,15 +19,15 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; import com.cloud.storage.snapshot.SnapshotSchedule; -@Implementation(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class) +@APICommand(description="Lists recurring snapshot schedule", responseObject=SnapshotScheduleResponse.class) public class ListRecurringSnapshotScheduleCmd extends BaseListCmd { private static final String s_name = "listrecurringsnapshotscheduleresponse"; @@ -61,20 +61,14 @@ public class ListRecurringSnapshotScheduleCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List snapshotSchedules = _snapshotService.findRecurringSnapshotSchedule(this); ListResponse response = new ListResponse(); List snapshotScheduleResponses = new ArrayList(); for (SnapshotSchedule snapshotSchedule : snapshotSchedules) { - SnapshotScheduleResponse snapSchedResponse = new SnapshotScheduleResponse(); - snapSchedResponse.setId(snapshotSchedule.getId()); - snapSchedResponse.setVolumeId(snapshotSchedule.getVolumeId()); - snapSchedResponse.setSnapshotPolicyId(snapshotSchedule.getPolicyId()); - snapSchedResponse.setScheduled(snapshotSchedule.getScheduledTimestamp()); - - snapSchedResponse.setObjectName("snapshot"); + SnapshotScheduleResponse snapSchedResponse = _responseGenerator.createSnapshotScheduleResponse(snapshotSchedule); snapshotScheduleResponses.add(snapSchedResponse); } diff --git a/api/src/com/cloud/api/commands/RestoreVMCmd.java b/api/src/com/cloud/api/commands/RestoreVMCmd.java deleted file mode 100755 index 31d2c229dee..00000000000 --- a/api/src/com/cloud/api/commands/RestoreVMCmd.java +++ /dev/null @@ -1,90 +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.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; -import com.cloud.event.EventTypes; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -import com.cloud.uservm.UserVm; - -@Implementation(description="Restore a VM to original template or specific snapshot", responseObject=UserVmResponse.class, since="3.0.0") -public class RestoreVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RestoreVMCmd.class); - private static final String s_name = "restorevmresponse"; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="Virtual Machine ID") - private Long vmId; - - @Override - public String getEventType() { - return EventTypes.EVENT_VM_RESTORE; - } - - @Override - public String getEventDescription() { - return "Restore a VM to orignal template or specific snapshot"; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - UserVm result; - UserContext.current().setEventDetails("Vm Id: " + getVmId()); - result = _userVmService.restoreVM(this); - if (result != null) { - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - UserVm vm = _responseGenerator.findUserVmById(getVmId()); - if (vm == null) { - return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked - } - return vm.getAccountId(); - } - - public long getVmId() { - return vmId; - } - -} diff --git a/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java b/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java deleted file mode 100755 index f0b3a53fcb1..00000000000 --- a/api/src/com/cloud/api/commands/listStorageNetworkIpRangeCmd.java +++ /dev/null @@ -1,108 +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.api.commands; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.dc.StorageNetworkIpRange; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.user.Account; - -@Implementation(description="List a storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") -public class listStorageNetworkIpRangeCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(listStorageNetworkIpRangeCmd.class); - - String s_name = "liststoragenetworkiprangeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="optional parameter. Storaget network IP range uuid, if specicied, using it to search the range.") - private Long rangeId; - - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="optional parameter. Pod uuid, if specicied and range uuid is absent, using it to search the range.") - private Long podId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="optional parameter. Zone uuid, if specicied and both pod uuid and range uuid are absent, using it to search the range.") - private Long zoneId; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public Long getRangeId() { - return rangeId; - } - - public Long getPodId() { - return podId; - } - - public Long getZoneId() { - return zoneId; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - List results = _storageNetworkService.listIpRange(this); - ListResponse response = new ListResponse(); - List resList = new ArrayList(results.size()); - for (StorageNetworkIpRange r : results) { - StorageNetworkIpRangeResponse resp = _responseGenerator.createStorageNetworkIpRangeResponse(r); - resList.add(resp); - } - response.setResponses(resList); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - -} diff --git a/api/src/com/cloud/api/response/AsyncJobResponse.java b/api/src/com/cloud/api/response/AsyncJobResponse.java deleted file mode 100644 index 9f18f653d74..00000000000 --- a/api/src/com/cloud/api/response/AsyncJobResponse.java +++ /dev/null @@ -1,148 +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.api.response; - -import java.util.Date; - -import com.cloud.api.ApiConstants; -import com.cloud.api.ResponseObject; -import com.cloud.async.AsyncJob; -import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; -import com.google.gson.annotations.SerializedName; - -@SuppressWarnings("unused") -public class AsyncJobResponse extends BaseResponse { - - @SerializedName("accountid") @Param(description="the account that executed the async command") - private IdentityProxy accountId = new IdentityProxy("account"); - - @SerializedName(ApiConstants.USER_ID) @Param(description="the user that executed the async command") - private IdentityProxy userId = new IdentityProxy("user"); - - @SerializedName("cmd") @Param(description="the async command executed") - private String cmd; - - @SerializedName("jobstatus") @Param(description="the current job status-should be 0 for PENDING") - private Integer jobStatus; - - @SerializedName("jobprocstatus") @Param(description="the progress information of the PENDING job") - private Integer jobProcStatus; - - @SerializedName("jobresultcode") @Param(description="the result code for the job") - private Integer jobResultCode; - - @SerializedName("jobresulttype") @Param(description="the result type") - private String jobResultType; - - @SerializedName("jobresult") @Param(description="the result reason") - private ResponseObject jobResult; - - @SerializedName("jobinstancetype") @Param(description="the instance/entity object related to the job") - private String jobInstanceType; - - @SerializedName("jobinstanceid") @Param(description="the unique ID of the instance/entity object related to the job") - private IdentityProxy jobInstanceId = new IdentityProxy(); - - @SerializedName(ApiConstants.CREATED) @Param(description=" the created date of the job") - private Date created; - - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); - } - - public void setUserId(Long userId) { - this.userId.setValue(userId); - } - - public void setCmd(String cmd) { - this.cmd = cmd; - } - - public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; - } - - public void setJobProcStatus(Integer jobProcStatus) { - this.jobProcStatus = jobProcStatus; - } - - public void setJobResultCode(Integer jobResultCode) { - this.jobResultCode = jobResultCode; - } - - public void setJobResultType(String jobResultType) { - this.jobResultType = jobResultType; - } - - public void setJobResult(ResponseObject jobResult) { - this.jobResult = jobResult; - } - - public void setJobInstanceType(String jobInstanceType) { - this.jobInstanceType = jobInstanceType; - - if(jobInstanceType != null) { - if(jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Volume.toString())) { - this.jobInstanceId.setTableName("volumes"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Template.toString())) { - this.jobInstanceId.setTableName("vm_template"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Iso.toString())) { - this.jobInstanceId.setTableName("vm_template"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.VirtualMachine.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.ConsoleProxy.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.SystemVm.toString()) || jobInstanceType.equalsIgnoreCase(AsyncJob.Type.DomainRouter.toString()) ) { - this.jobInstanceId.setTableName("vm_instance"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Snapshot.toString())) { - this.jobInstanceId.setTableName("snapshots"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Host.toString())) { - this.jobInstanceId.setTableName("host"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.StoragePool.toString())) { - this.jobInstanceId.setTableName("storage_pool"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.IpAddress.toString())) { - this.jobInstanceId.setTableName("user_ip_address"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.SecurityGroup.toString())) { - this.jobInstanceId.setTableName("security_group"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PhysicalNetwork.toString())) { - this.jobInstanceId.setTableName("physical_network"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.TrafficType.toString())) { - this.jobInstanceId.setTableName("physical_network_traffic_types"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PhysicalNetworkServiceProvider.toString())) { - this.jobInstanceId.setTableName("physical_network_service_providers"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.FirewallRule.toString())) { - this.jobInstanceId.setTableName("firewall_rules"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.Account.toString())) { - this.jobInstanceId.setTableName("account"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.User.toString())) { - this.jobInstanceId.setTableName("user"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.StaticRoute.toString())) { - this.jobInstanceId.setTableName("static_routes"); - } else if (jobInstanceType.equalsIgnoreCase(AsyncJob.Type.PrivateGateway.toString())) { - this.jobInstanceId.setTableName("vpc_gateways"); - } else if (!jobInstanceType.equalsIgnoreCase(AsyncJob.Type.None.toString())){ - // TODO : when we hit here, we need to add instanceType -> UUID entity table mapping - assert(false); - } - } - } - - public void setJobInstanceId(Long jobInstanceId) { - this.jobInstanceId.setValue(jobInstanceId); - } - - public void setCreated(Date created) { - this.created = created; - } -} diff --git a/api/src/com/cloud/async/AsyncJob.java b/api/src/com/cloud/async/AsyncJob.java index 10279c5219e..034c853e8f9 100644 --- a/api/src/com/cloud/async/AsyncJob.java +++ b/api/src/com/cloud/async/AsyncJob.java @@ -18,9 +18,10 @@ package com.cloud.async; import java.util.Date; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface AsyncJob extends Identity { +public interface AsyncJob extends Identity, InternalIdentity { public enum Type { None, VirtualMachine, @@ -42,11 +43,14 @@ public interface AsyncJob extends Identity { Account, User, PrivateGateway, - StaticRoute + StaticRoute, + Counter, + Condition, + AutoScalePolicy, + AutoScaleVmProfile, + AutoScaleVmGroup } - Long getId(); - long getUserId(); long getAccountId(); diff --git a/api/src/com/cloud/async/SyncQueueItem.java b/api/src/com/cloud/async/SyncQueueItem.java index f299481eb11..9f9c379a742 100644 --- a/api/src/com/cloud/async/SyncQueueItem.java +++ b/api/src/com/cloud/async/SyncQueueItem.java @@ -16,7 +16,9 @@ // under the License. package com.cloud.async; + public interface SyncQueueItem { + public final String AsyncJobContentType = "AsyncJob"; String getContentType(); diff --git a/api/src/com/cloud/capacity/Capacity.java b/api/src/com/cloud/capacity/Capacity.java index 2da2a672ce3..c1c5d8fa9b2 100755 --- a/api/src/com/cloud/capacity/Capacity.java +++ b/api/src/com/cloud/capacity/Capacity.java @@ -16,7 +16,10 @@ // under the License. package com.cloud.capacity; -public interface Capacity { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Capacity extends InternalIdentity, Identity { public static final short CAPACITY_TYPE_MEMORY = 0; public static final short CAPACITY_TYPE_CPU = 1; public static final short CAPACITY_TYPE_STORAGE = 2; @@ -28,8 +31,6 @@ public interface Capacity { public static final short CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8; public static final short CAPACITY_TYPE_LOCAL_STORAGE = 9; - public long getId(); - public Long getHostOrPoolId(); public Long getDataCenterId(); @@ -42,11 +43,9 @@ public interface Capacity { public long getTotalCapacity(); - public short getCapacityType(); + public short getCapacityType(); public long getReservedCapacity(); - + public Float getUsedPercentage(); - - } diff --git a/api/src/com/cloud/capacity/CapacityState.java b/api/src/com/cloud/capacity/CapacityState.java index be17663f602..b368567c022 100755 --- a/api/src/com/cloud/capacity/CapacityState.java +++ b/api/src/com/cloud/capacity/CapacityState.java @@ -17,9 +17,9 @@ package com.cloud.capacity; public enum CapacityState { - + Enabled, - Disabled, + Disabled, Maintenance, - + } diff --git a/api/src/com/cloud/cluster/ManagementServerHost.java b/api/src/com/cloud/cluster/ManagementServerHost.java index 0273d472bea..9c88a2b2006 100644 --- a/api/src/com/cloud/cluster/ManagementServerHost.java +++ b/api/src/com/cloud/cluster/ManagementServerHost.java @@ -16,7 +16,9 @@ // under the License. package com.cloud.cluster; -public interface ManagementServerHost { +import org.apache.cloudstack.api.InternalIdentity; + +public interface ManagementServerHost extends InternalIdentity { public static enum State { Up, Starting, Down diff --git a/api/src/com/cloud/configuration/ConfigurationService.java b/api/src/com/cloud/configuration/ConfigurationService.java index 78d7a2250a9..48a060719c6 100644 --- a/api/src/com/cloud/configuration/ConfigurationService.java +++ b/api/src/com/cloud/configuration/ConfigurationService.java @@ -20,26 +20,24 @@ import java.util.List; import javax.naming.NamingException; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; import com.cloud.dc.Vlan; @@ -57,7 +55,7 @@ public interface ConfigurationService { /** * Updates a configuration entry with a new value - * + * * @param cmd * - the command wrapping name and value parameters * @return updated configuration object if successful @@ -66,7 +64,7 @@ public interface ConfigurationService { /** * Create a service offering through the API - * + * * @param cmd * the command object that specifies the name, number of cpu cores, amount of RAM, etc. for the service * offering @@ -76,7 +74,7 @@ public interface ConfigurationService { /** * Updates a service offering - * + * * @param serviceOfferingId * @param userId * @param name @@ -90,7 +88,7 @@ public interface ConfigurationService { /** * Deletes a service offering - * + * * @param userId * @param serviceOfferingId */ @@ -98,7 +96,7 @@ public interface ConfigurationService { /** * Updates a disk offering - * + * * @param cmd * - the command specifying diskOfferingId, name, description, tags * @return updated disk offering @@ -108,7 +106,7 @@ public interface ConfigurationService { /** * Deletes a disk offering - * + * * @param cmd * - the command specifying disk offering id * @return true or false @@ -118,7 +116,7 @@ public interface ConfigurationService { /** * Creates a new disk offering - * + * * @param domainId * @param name * @param description @@ -131,7 +129,7 @@ public interface ConfigurationService { /** * Creates a new pod based on the parameters specified in the command object - * + * * @param zoneId * TODO * @param name @@ -154,7 +152,7 @@ public interface ConfigurationService { /** * Edits a pod in the database. Will not allow you to edit pods that are being used anywhere in the system. - * + * * @param UpdatePodCmd * api command */ @@ -162,7 +160,7 @@ public interface ConfigurationService { /** * Deletes a pod from the database. Will not allow you to delete pods that are being used anywhere in the system. - * + * * @param cmd * - the command containing podId * @return true or false @@ -172,7 +170,7 @@ public interface ConfigurationService { /** * Creates a new zone - * + * * @param cmd * @return the zone if successful, null otherwise * @throws @@ -182,7 +180,7 @@ public interface ConfigurationService { /** * Edits a zone in the database. Will not allow you to edit DNS values if there are VMs in the specified zone. - * + * * @param UpdateZoneCmd * @return Updated zone */ @@ -190,7 +188,7 @@ public interface ConfigurationService { /** * Deletes a zone from the database. Will not allow you to delete zones that are being used anywhere in the system. - * + * * @param userId * @param zoneId */ @@ -200,7 +198,7 @@ public interface ConfigurationService { * Adds a VLAN to the database, along with an IP address range. Can add three types of VLANs: (1) zone-wide VLANs on * the * virtual public network (2) pod-wide direct attached VLANs (3) account-specific direct attached VLANs - * + * * @param userId * @param vlanType * - either "DomR" (VLAN for a virtual public network) or "DirectAttached" (VLAN for IPs that will be diff --git a/api/src/com/cloud/configuration/ResourceCount.java b/api/src/com/cloud/configuration/ResourceCount.java index d776a72d2b1..f0b1d7190d5 100644 --- a/api/src/com/cloud/configuration/ResourceCount.java +++ b/api/src/com/cloud/configuration/ResourceCount.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.configuration; -public interface ResourceCount extends Resource { +import org.apache.cloudstack.api.InternalIdentity; - public Long getId(); +public interface ResourceCount extends Resource, InternalIdentity { public long getCount(); diff --git a/api/src/com/cloud/configuration/ResourceLimit.java b/api/src/com/cloud/configuration/ResourceLimit.java index df47d09b484..801feebbe10 100644 --- a/api/src/com/cloud/configuration/ResourceLimit.java +++ b/api/src/com/cloud/configuration/ResourceLimit.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.configuration; -public interface ResourceLimit extends Resource { +import org.apache.cloudstack.api.InternalIdentity; - public Long getId(); +public interface ResourceLimit extends Resource, InternalIdentity { public Long getMax(); diff --git a/api/src/com/cloud/dao/EntityManager.java b/api/src/com/cloud/dao/EntityManager.java index 0e5b07f51e4..4e4b9c293b5 100644 --- a/api/src/com/cloud/dao/EntityManager.java +++ b/api/src/com/cloud/dao/EntityManager.java @@ -37,7 +37,16 @@ public interface EntityManager { * @return T if found; null if not. */ public T findById(Class entityType, K id); - + + /** + * Finds a unique entity by uuid string + * @param entity class + * @param entityType type of entity you're looking for. + * @param uuid the unique id + * @return T if found, null if not. + */ + public T findByUuid(Class entityType, String uuid); + /** * Finds an entity by external id which is always String * @param entity class @@ -45,8 +54,8 @@ public interface EntityManager { * @param xid external id * @return T if found, null if not. */ - public T findByXid(Class entityType, String xid); - + public T findByXId(Class entityType, String xid); + /** * Lists all entities. Use this method at your own risk. * @param entity class @@ -54,7 +63,7 @@ public interface EntityManager { * @return List */ public List list(Class entityType); - + /** * Persists the entity. * @param entity class @@ -62,13 +71,13 @@ public interface EntityManager { * @return persisted entity. Only use this after persisting. */ public T persist(T t); - + public SearchBuilder createSearchBuilder(Class entityType); - + public GenericSearchBuilder createGenericSearchBuilder(Class entityType, Class resultType); - + public List search(Class entityType, SearchCriteria sc); - + public void remove(Class entityType, K id); } diff --git a/api/src/com/cloud/dc/DataCenter.java b/api/src/com/cloud/dc/DataCenter.java index 707cd34524e..946e9ccb5bd 100644 --- a/api/src/com/cloud/dc/DataCenter.java +++ b/api/src/com/cloud/dc/DataCenter.java @@ -19,18 +19,19 @@ package com.cloud.dc; import java.util.Map; import com.cloud.org.Grouping; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * */ -public interface DataCenter extends Grouping { +public interface DataCenter extends InfrastructureEntity, Grouping, Identity, InternalIdentity { public enum NetworkType { Basic, Advanced, } - long getId(); - String getDns1(); String getDns2(); diff --git a/api/src/com/cloud/dc/Pod.java b/api/src/com/cloud/dc/Pod.java index 791c5ad2c2d..9da5b7e7836 100644 --- a/api/src/com/cloud/dc/Pod.java +++ b/api/src/com/cloud/dc/Pod.java @@ -17,16 +17,15 @@ package com.cloud.dc; import com.cloud.org.Grouping; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Represents one pod in the cloud stack. - * + * */ -public interface Pod extends Grouping { - /** - * @return unique id mapped to the pod. - */ - long getId(); +public interface Pod extends InfrastructureEntity, Grouping, Identity, InternalIdentity { String getCidrAddress(); @@ -36,8 +35,6 @@ public interface Pod extends Grouping { long getDataCenterId(); - // String getUniqueName(); - String getDescription(); String getName(); diff --git a/api/src/com/cloud/dc/StorageNetworkIpRange.java b/api/src/com/cloud/dc/StorageNetworkIpRange.java index 59aa98ae11e..2b50ca1594e 100755 --- a/api/src/com/cloud/dc/StorageNetworkIpRange.java +++ b/api/src/com/cloud/dc/StorageNetworkIpRange.java @@ -16,8 +16,11 @@ // under the License. package com.cloud.dc; -public interface StorageNetworkIpRange { - String getUuid(); +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface StorageNetworkIpRange extends InfrastructureEntity, InternalIdentity, Identity { Integer getVlan(); @@ -30,8 +33,8 @@ public interface StorageNetworkIpRange { String getNetworkUuid(); String getZoneUuid(); - + String getNetmask(); - + String getGateway(); } diff --git a/api/src/com/cloud/dc/Vlan.java b/api/src/com/cloud/dc/Vlan.java index 1e1fce15fc4..0f629ef3cbf 100644 --- a/api/src/com/cloud/dc/Vlan.java +++ b/api/src/com/cloud/dc/Vlan.java @@ -16,7 +16,11 @@ // under the License. package com.cloud.dc; -public interface Vlan { +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Vlan extends InfrastructureEntity, InternalIdentity, Identity { public enum VlanType { DirectAttached, VirtualNetwork @@ -24,8 +28,6 @@ public interface Vlan { public final static String UNTAGGED = "untagged"; - public long getId(); - public String getVlanTag(); public String getVlanGateway(); diff --git a/api/src/com/cloud/deploy/DataCenterDeployment.java b/api/src/com/cloud/deploy/DataCenterDeployment.java index 25522e06cfa..f046b66ef06 100644 --- a/api/src/com/cloud/deploy/DataCenterDeployment.java +++ b/api/src/com/cloud/deploy/DataCenterDeployment.java @@ -37,7 +37,7 @@ public class DataCenterDeployment implements DeploymentPlan { public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId, Long physicalNetworkId) { this(dataCenterId, podId, clusterId, hostId, poolId, physicalNetworkId, null); } - + public DataCenterDeployment(long dataCenterId, Long podId, Long clusterId, Long hostId, Long poolId, Long physicalNetworkId, ReservationContext context) { _dcId = dataCenterId; _podId = podId; @@ -87,7 +87,7 @@ public class DataCenterDeployment implements DeploymentPlan { public Long getPhysicalNetworkId() { return _physicalNetworkId; } - + @Override public ReservationContext getReservationContext() { return _context; diff --git a/api/src/com/cloud/deploy/DeploymentPlanner.java b/api/src/com/cloud/deploy/DeploymentPlanner.java index e5dcff1be54..537dd314733 100644 --- a/api/src/com/cloud/deploy/DeploymentPlanner.java +++ b/api/src/com/cloud/deploy/DeploymentPlanner.java @@ -37,7 +37,7 @@ import com.cloud.vm.VirtualMachineProfile; public interface DeploymentPlanner extends Adapter { /** * plan is called to determine where a virtual machine should be running. - * + * * @param vm * virtual machine. * @param plan @@ -51,7 +51,7 @@ public interface DeploymentPlanner extends Adapter { /** * check() is called right before the virtual machine starts to make sure * the host has enough capacity. - * + * * @param vm * virtual machine in question. * @param plan @@ -69,7 +69,7 @@ public interface DeploymentPlanner extends Adapter { * canHandle is called before plan to determine if the plan can do the allocation. Planers should be exclusive so * planner writer must * make sure only one planer->canHandle return true in the planner list - * + * * @param vm * virtual machine. * @param plan @@ -187,7 +187,7 @@ public interface DeploymentPlanner extends Adapter { } _clusterIds.addAll(clusterList); } - + public void addHost(long hostId) { if (_hostIds == null) { _hostIds = new HashSet(); diff --git a/api/src/com/cloud/domain/Domain.java b/api/src/com/cloud/domain/Domain.java index a7b4031dce5..cfed519ada9 100644 --- a/api/src/com/cloud/domain/Domain.java +++ b/api/src/com/cloud/domain/Domain.java @@ -19,19 +19,20 @@ package com.cloud.domain; import java.util.Date; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Domain defines the Domain object. */ -public interface Domain extends OwnedBy { + +public interface Domain extends OwnedBy, Identity, InternalIdentity { public static final long ROOT_DOMAIN = 1L; enum State { Active, Inactive }; - long getId(); - Long getParent(); void setParent(Long parent); diff --git a/api/src/com/cloud/event/Event.java b/api/src/com/cloud/event/Event.java index 6a305378931..1a61636828a 100644 --- a/api/src/com/cloud/event/Event.java +++ b/api/src/com/cloud/event/Event.java @@ -18,26 +18,24 @@ package com.cloud.event; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Event extends ControlledEntity{ +public interface Event extends ControlledEntity, Identity, InternalIdentity { public enum State { Created, Scheduled, Started, Completed; } - - long getId(); String getType(); State getState(); String getDescription(); Date getCreateDate(); long getUserId(); - long getAccountId(); - long getDomainId(); int getTotalSize(); String getLevel(); long getStartId(); diff --git a/api/src/com/cloud/event/EventTypes.java b/api/src/com/cloud/event/EventTypes.java index e84a40379ad..8c622252d17 100755 --- a/api/src/com/cloud/event/EventTypes.java +++ b/api/src/com/cloud/event/EventTypes.java @@ -263,32 +263,53 @@ public class EventTypes { public static final String EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_ENABLE = "SWITCH.MGMT.ENABLE"; public static final String EVENT_EXTERNAL_SWITCH_MGMT_DEVICE_DISABLE = "SWITCH.MGMT.DISABLE"; - + public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_ADD = "PHYSICAL.FIREWALL.ADD"; public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_DELETE = "PHYSICAL.FIREWALL.DELETE"; public static final String EVENT_EXTERNAL_FIREWALL_DEVICE_CONFIGURE = "PHYSICAL.FIREWALL.CONFIGURE"; - + // VPC public static final String EVENT_VPC_CREATE = "VPC.CREATE"; public static final String EVENT_VPC_UPDATE = "VPC.UPDATE"; public static final String EVENT_VPC_DELETE = "VPC.DELETE"; public static final String EVENT_VPC_RESTART = "VPC.RESTART"; - + // VPC offerings public static final String EVENT_VPC_OFFERING_CREATE = "VPC.OFFERING.CREATE"; public static final String EVENT_VPC_OFFERING_UPDATE = "VPC.OFFERING.UPDATE"; public static final String EVENT_VPC_OFFERING_DELETE = "VPC.OFFERING.DELETE"; - + // Private gateway public static final String EVENT_PRIVATE_GATEWAY_CREATE = "PRIVATE.GATEWAY.CREATE"; public static final String EVENT_PRIVATE_GATEWAY_DELETE = "PRIVATE.GATEWAY.DELETE"; - + // Static routes public static final String EVENT_STATIC_ROUTE_CREATE = "STATIC.ROUTE.CREATE"; public static final String EVENT_STATIC_ROUTE_DELETE = "STATIC.ROUTE.DELETE"; - + // tag related events public static final String EVENT_TAGS_CREATE = "CREATE_TAGS"; public static final String EVENT_TAGS_DELETE = "DELETE_TAGS"; + // external network device events + public static final String EVENT_EXTERNAL_NVP_CONTROLLER_ADD = "PHYSICAL.NVPCONTROLLER.ADD"; + public static final String EVENT_EXTERNAL_NVP_CONTROLLER_DELETE = "PHYSICAL.NVPCONTROLLER.DELETE"; + public static final String EVENT_EXTERNAL_NVP_CONTROLLER_CONFIGURE = "PHYSICAL.NVPCONTROLLER.CONFIGURE"; + + // AutoScale + public static final String EVENT_COUNTER_CREATE = "COUNTER.CREATE"; + public static final String EVENT_COUNTER_DELETE = "COUNTER.DELETE"; + public static final String EVENT_CONDITION_CREATE = "CONDITION.CREATE"; + public static final String EVENT_CONDITION_DELETE = "CONDITION.DELETE"; + public static final String EVENT_AUTOSCALEPOLICY_CREATE = "AUTOSCALEPOLICY.CREATE"; + public static final String EVENT_AUTOSCALEPOLICY_UPDATE = "AUTOSCALEPOLICY.UPDATE"; + public static final String EVENT_AUTOSCALEPOLICY_DELETE = "AUTOSCALEPOLICY.DELETE"; + public static final String EVENT_AUTOSCALEVMPROFILE_CREATE = "AUTOSCALEVMPROFILE.CREATE"; + public static final String EVENT_AUTOSCALEVMPROFILE_DELETE = "AUTOSCALEVMPROFILE.DELETE"; + public static final String EVENT_AUTOSCALEVMPROFILE_UPDATE = "AUTOSCALEVMPROFILE.UPDATE"; + public static final String EVENT_AUTOSCALEVMGROUP_CREATE = "AUTOSCALEVMGROUP.CREATE"; + public static final String EVENT_AUTOSCALEVMGROUP_DELETE = "AUTOSCALEVMGROUP.DELETE"; + public static final String EVENT_AUTOSCALEVMGROUP_UPDATE = "AUTOSCALEVMGROUP.UPDATE"; + public static final String EVENT_AUTOSCALEVMGROUP_ENABLE = "AUTOSCALEVMGROUP.ENABLE"; + public static final String EVENT_AUTOSCALEVMGROUP_DISABLE = "AUTOSCALEVMGROUP.DISABLE"; } diff --git a/api/src/com/cloud/exception/AgentUnavailableException.java b/api/src/com/cloud/exception/AgentUnavailableException.java index a2d052b61f5..89193243e1d 100644 --- a/api/src/com/cloud/exception/AgentUnavailableException.java +++ b/api/src/com/cloud/exception/AgentUnavailableException.java @@ -24,17 +24,17 @@ import com.cloud.utils.SerialVersionUID; * */ public class AgentUnavailableException extends ResourceUnavailableException { - + private static final long serialVersionUID = SerialVersionUID.AgentUnavailableException; - + public AgentUnavailableException(String msg, long agentId) { this(msg, agentId, null); } - + public AgentUnavailableException(long agentId) { this("Unable to reach host.", agentId); } - + public AgentUnavailableException(String msg, long agentId, Throwable cause) { super("Host " + agentId + ": " + msg, Host.class, agentId, cause); } diff --git a/api/src/com/cloud/exception/CloudException.java b/api/src/com/cloud/exception/CloudException.java index 9ebeaad6675..fd839565253 100644 --- a/api/src/com/cloud/exception/CloudException.java +++ b/api/src/com/cloud/exception/CloudException.java @@ -24,16 +24,16 @@ import com.cloud.utils.AnnotationHelper; /** * by the API response serializer. Any exceptions that are thrown by * class, which extends RuntimeException instead of Exception like this - * class does. + * class does. */ public class CloudException extends Exception { - + // This holds a list of uuids and their names. Add uuid:fieldname pairs - protected ArrayList idList = new ArrayList(); - - protected Integer csErrorCode; - + protected ArrayList idList = new ArrayList(); + + protected Integer csErrorCode; + public CloudException(String message) { super(message); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); @@ -43,34 +43,27 @@ public class CloudException extends Exception { super(message, cause); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - - public void addProxyObject(Object voObj, Long id, String idFieldName) { - // Get the VO object's table name. - String tablename = AnnotationHelper.getTableName(voObj); - if (tablename != null) { - addProxyObject(tablename, id, idFieldName); - } - return; - } - + + + public CloudException() { super(); setCSErrorCode(CSExceptionErrorCode.getCSErrCode(this.getClass().getName())); } - - public void addProxyObject(String tableName, Long id, String idFieldName) { - idList.add(new IdentityProxy(tableName, id, idFieldName)); + + public void addProxyObject(String uuid) { + idList.add(uuid); return; } - - public ArrayList getIdProxyList() { + + public ArrayList getIdProxyList() { return idList; } - + public void setCSErrorCode(int cserrcode) { this.csErrorCode = cserrcode; } - + public int getCSErrorCode() { return this.csErrorCode; } diff --git a/api/src/com/cloud/exception/CloudExecutionException.java b/api/src/com/cloud/exception/CloudExecutionException.java index 74b116a0983..d8d70f8ddb5 100755 --- a/api/src/com/cloud/exception/CloudExecutionException.java +++ b/api/src/com/cloud/exception/CloudExecutionException.java @@ -22,11 +22,11 @@ import com.cloud.utils.exception.RuntimeCloudException; import com.cloud.utils.SerialVersionUID; /** - * + * */ public class CloudExecutionException extends RuntimeCloudException { private final static long serialVersionUID = SerialVersionUID.CloudExecutionException; - + private final ErrorCode code; private final HashMap details; @@ -35,15 +35,15 @@ public class CloudExecutionException extends RuntimeCloudException { this.code = code; details = new HashMap(); } - + public ErrorCode getErrorCode() { return code; } - + public String getErrorMessage() { return new StringBuilder("Error Code=").append(code).append("; Error Message=").append(super.toString()).toString(); } - + @Override public String toString() { StringBuilder buff = new StringBuilder(); diff --git a/api/src/com/cloud/exception/ConcurrentOperationException.java b/api/src/com/cloud/exception/ConcurrentOperationException.java index 54826d6a5e9..cfe6ba3fa0a 100644 --- a/api/src/com/cloud/exception/ConcurrentOperationException.java +++ b/api/src/com/cloud/exception/ConcurrentOperationException.java @@ -19,9 +19,9 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class ConcurrentOperationException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.ConcurrentOperationException; - + public ConcurrentOperationException(String msg) { super(msg); } diff --git a/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java b/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java index 7afcfe64575..a777afabeb7 100644 --- a/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java +++ b/api/src/com/cloud/exception/ConflictingNetworkSettingsException.java @@ -21,7 +21,7 @@ import com.cloud.utils.SerialVersionUID; public class ConflictingNetworkSettingsException extends CloudException { private static final long serialVersionUID = SerialVersionUID.ConflictingNetworkSettingException; - + public ConflictingNetworkSettingsException() { super(); } diff --git a/api/src/com/cloud/exception/ConnectionException.java b/api/src/com/cloud/exception/ConnectionException.java index 966e39b3fd2..b3f0726fd34 100644 --- a/api/src/com/cloud/exception/ConnectionException.java +++ b/api/src/com/cloud/exception/ConnectionException.java @@ -25,26 +25,26 @@ import com.cloud.utils.SerialVersionUID; * processing. Upon receiving this exception, the AgentManager will * immediately place the agent under alert. When the function to enable * to disable the agent, the agent is disabled. - * should be disconnected and reconnected to "refresh" all resource + * should be disconnected and reconnected to "refresh" all resource * information. This is useful when the Listener needed to perform setup * on the agent and decided it is best to flush connection and reconnect. * situation where it keeps throwing ConnectionException. */ public class ConnectionException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.ConnectionException; boolean _error; public ConnectionException(boolean setupError, String msg) { this(setupError, msg, null); } - + public ConnectionException(boolean setupError, String msg, Throwable cause) { super(msg, cause); _error = setupError; - + } - + public boolean isSetupError() { return _error; } diff --git a/api/src/com/cloud/exception/DiscoveredWithErrorException.java b/api/src/com/cloud/exception/DiscoveredWithErrorException.java index f59066f83c1..ee59baf45da 100644 --- a/api/src/com/cloud/exception/DiscoveredWithErrorException.java +++ b/api/src/com/cloud/exception/DiscoveredWithErrorException.java @@ -19,13 +19,13 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class DiscoveredWithErrorException extends DiscoveryException { - + private static final long serialVersionUID = SerialVersionUID.DiscoveredWithErrorException; public DiscoveredWithErrorException(String msg) { this(msg, null); } - + public DiscoveredWithErrorException(String msg, Throwable cause) { super(msg, cause); } diff --git a/api/src/com/cloud/exception/DiscoveryException.java b/api/src/com/cloud/exception/DiscoveryException.java index 10a7c5b338f..62ae2724ea5 100644 --- a/api/src/com/cloud/exception/DiscoveryException.java +++ b/api/src/com/cloud/exception/DiscoveryException.java @@ -19,13 +19,13 @@ package com.cloud.exception; import com.cloud.utils.SerialVersionUID; public class DiscoveryException extends CloudException { - + private static final long serialVersionUID = SerialVersionUID.DiscoveryException; public DiscoveryException(String msg) { this(msg, null); } - + public DiscoveryException(String msg, Throwable cause) { super(msg, cause); } diff --git a/api/src/com/cloud/exception/ErrorCode.java b/api/src/com/cloud/exception/ErrorCode.java index 15d9b7e8a1e..8f048b84800 100755 --- a/api/src/com/cloud/exception/ErrorCode.java +++ b/api/src/com/cloud/exception/ErrorCode.java @@ -23,30 +23,30 @@ import java.util.HashSet; public class ErrorCode { String code; private static HashSet s_codes = new HashSet(); - + public ErrorCode(String code) { this.code = code; assert !s_codes.contains(this) : "There is already an error code registered for this code: " + code; s_codes.add(this); } - + public String getCode() { return code; } - + @Override public int hashCode() { return code.hashCode(); } - + @Override public boolean equals(Object that) { if (!(that instanceof ErrorCode)) { return false; } - + return this.code.equals(((ErrorCode)that).code); } - + public final static ErrorCode UnableToReachResource = new ErrorCode("resource.unavailable"); } diff --git a/api/src/com/cloud/exception/HAStateException.java b/api/src/com/cloud/exception/HAStateException.java index aaa5e756aa1..cb2517446ba 100644 --- a/api/src/com/cloud/exception/HAStateException.java +++ b/api/src/com/cloud/exception/HAStateException.java @@ -23,9 +23,9 @@ import com.cloud.utils.SerialVersionUID; * done with it. Hence this special state. */ public class HAStateException extends ManagementServerException { - + private static final long serialVersionUID = SerialVersionUID.HAStateException; - + public HAStateException(String msg) { super(msg); } diff --git a/api/src/com/cloud/exception/InsufficientCapacityException.java b/api/src/com/cloud/exception/InsufficientCapacityException.java index 8a0557f8c06..51a4e593858 100755 --- a/api/src/com/cloud/exception/InsufficientCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientCapacityException.java @@ -49,7 +49,7 @@ public abstract class InsufficientCapacityException extends CloudException { /** * @return the id of the object that it is insufficient in. Note that this method is * marked such that if the id is not set, then it will throw NullPointerException. - * This is intended as you should check to see if the Scope is present before + * This is intended as you should check to see if the Scope is present before * accessing this method. */ public long getId() { diff --git a/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java b/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java index 09a077bfc24..71ec16d88f3 100644 --- a/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientNetworkCapacityException.java @@ -20,11 +20,11 @@ import com.cloud.utils.SerialVersionUID; public class InsufficientNetworkCapacityException extends InsufficientCapacityException { private static final long serialVersionUID = SerialVersionUID.InsufficientAddressCapacityException; - + protected InsufficientNetworkCapacityException() { super(); } - + public InsufficientNetworkCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientServerCapacityException.java b/api/src/com/cloud/exception/InsufficientServerCapacityException.java index 4a30595c12b..af34e579943 100755 --- a/api/src/com/cloud/exception/InsufficientServerCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientServerCapacityException.java @@ -24,13 +24,13 @@ import com.cloud.utils.SerialVersionUID; * trying to start. */ public class InsufficientServerCapacityException extends InsufficientCapacityException { - + private static final long serialVersionUID = SerialVersionUID.InsufficientServerCapacityException; - + public InsufficientServerCapacityException(String msg, Long clusterId) { this(msg, Cluster.class, clusterId); } - + public InsufficientServerCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientStorageCapacityException.java b/api/src/com/cloud/exception/InsufficientStorageCapacityException.java index f8ec10610ce..c70bfc38c8c 100755 --- a/api/src/com/cloud/exception/InsufficientStorageCapacityException.java +++ b/api/src/com/cloud/exception/InsufficientStorageCapacityException.java @@ -24,13 +24,13 @@ import com.cloud.utils.SerialVersionUID; * storage space to create the VM. */ public class InsufficientStorageCapacityException extends InsufficientCapacityException { - + private static final long serialVersionUID = SerialVersionUID.InsufficientStorageCapacityException; - + public InsufficientStorageCapacityException(String msg, long id) { this(msg, StoragePool.class, id); } - + public InsufficientStorageCapacityException(String msg, Class scope, Long id) { super(msg, scope, id); } diff --git a/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java b/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java index 10d9ffc82ce..4741baaf62d 100644 --- a/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java +++ b/api/src/com/cloud/exception/InsufficientVirtualNetworkCapcityException.java @@ -21,11 +21,11 @@ import com.cloud.utils.SerialVersionUID; public class InsufficientVirtualNetworkCapcityException extends InsufficientNetworkCapacityException { private static final long serialVersionUID = SerialVersionUID.InsufficientVirtualNetworkCapacityException; - + public InsufficientVirtualNetworkCapcityException(String msg, Class scope, Long id) { super(msg, scope, id); } - + public InsufficientVirtualNetworkCapcityException(String msg, long podId) { this(msg, Pod.class, podId); } diff --git a/api/src/com/cloud/exception/PermissionDeniedException.java b/api/src/com/cloud/exception/PermissionDeniedException.java index 4900afcd67a..638b762d4c4 100644 --- a/api/src/com/cloud/exception/PermissionDeniedException.java +++ b/api/src/com/cloud/exception/PermissionDeniedException.java @@ -18,7 +18,7 @@ package com.cloud.exception; import java.util.List; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.user.Account; import com.cloud.utils.SerialVersionUID; import com.cloud.utils.exception.CloudRuntimeException; diff --git a/api/src/com/cloud/exception/ResourceUnavailableException.java b/api/src/com/cloud/exception/ResourceUnavailableException.java index 484659a6a94..30daf566b03 100644 --- a/api/src/com/cloud/exception/ResourceUnavailableException.java +++ b/api/src/com/cloud/exception/ResourceUnavailableException.java @@ -23,21 +23,21 @@ public class ResourceUnavailableException extends CloudException { Class _scope; long _id; - + public ResourceUnavailableException(String msg, Class scope, long resourceId) { this(msg, scope, resourceId, null); } - + public ResourceUnavailableException(String msg, Class scope, long resourceId, Throwable cause) { super(new StringBuilder("Resource [").append(scope.getSimpleName()).append(":").append(resourceId).append("] is unreachable: ").append(msg).toString(), cause); _scope = scope; _id = resourceId; } - + public Class getScope() { return _scope; } - + public long getResourceId() { return _id; } diff --git a/api/src/com/cloud/exception/StorageUnavailableException.java b/api/src/com/cloud/exception/StorageUnavailableException.java index 7b443a91087..6db16290237 100644 --- a/api/src/com/cloud/exception/StorageUnavailableException.java +++ b/api/src/com/cloud/exception/StorageUnavailableException.java @@ -20,9 +20,9 @@ import com.cloud.storage.StoragePool; import com.cloud.utils.SerialVersionUID; /** - * If the cause is due to storage pool unavailable, calling + * If the cause is due to storage pool unavailable, calling * problem with. - * + * */ public class StorageUnavailableException extends ResourceUnavailableException { private static final long serialVersionUID = SerialVersionUID.StorageUnavailableException; @@ -33,11 +33,11 @@ public class StorageUnavailableException extends ResourceUnavailableException { public StorageUnavailableException(String msg, long poolId, Throwable cause) { this(msg, StoragePool.class, poolId, cause); } - + public StorageUnavailableException(String msg, Class scope, long resourceId) { this(msg, scope, resourceId, null); } - + public StorageUnavailableException(String msg, Class scope, long resourceId, Throwable th) { super(msg, scope, resourceId, th); } diff --git a/api/src/com/cloud/host/Host.java b/api/src/com/cloud/host/Host.java index 1bac0d20a40..bd26f81c8c2 100755 --- a/api/src/com/cloud/host/Host.java +++ b/api/src/com/cloud/host/Host.java @@ -21,12 +21,14 @@ import java.util.Date; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.resource.ResourceState; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Host represents one particular host server. */ -public interface Host extends StateObject { +public interface Host extends StateObject, Identity, InternalIdentity { public enum Type { Storage(false), Routing(false), @@ -61,11 +63,6 @@ public interface Host extends StateObject { } } - /** - * @return id of the host. - */ - long getId(); - /** * @return name of the machine. */ @@ -198,6 +195,6 @@ public interface Host extends StateObject { String getHypervisorVersion(); boolean isInMaintenanceStates(); - - ResourceState getResourceState(); + + ResourceState getResourceState(); } diff --git a/api/src/com/cloud/host/HostEnvironment.java b/api/src/com/cloud/host/HostEnvironment.java index 31849748486..89077b5fed1 100644 --- a/api/src/com/cloud/host/HostEnvironment.java +++ b/api/src/com/cloud/host/HostEnvironment.java @@ -22,29 +22,29 @@ package com.cloud.host; * the environment. */ public class HostEnvironment { - + public String managementIpAddress; public String managementNetmask; public String managementGateway; public String managementVlan; - + public String[] neighborHosts; - + public String storageIpAddress; public String storageNetwork; public String storageGateway; public String storageVlan; public String secondaryStroageIpAddress; - + public String storage2IpAddress; public String storage2Network; public String storage2Gateway; public String storage2Vlan; public String secondaryStorageIpAddress2; - + public String[] neighborStorages; public String[] neighborStorages2; - + public String publicIpAddress; public String publicNetmask; public String publicGateway; diff --git a/api/src/com/cloud/host/HostStats.java b/api/src/com/cloud/host/HostStats.java index e8fa19ef3d1..803b1484b2b 100755 --- a/api/src/com/cloud/host/HostStats.java +++ b/api/src/com/cloud/host/HostStats.java @@ -17,7 +17,7 @@ package com.cloud.host; public interface HostStats { - + // host related stats public double getCpuUtilization(); public double getNetworkWriteKBs(); @@ -27,7 +27,7 @@ public interface HostStats { public String getEntityType(); public double getUsedMemory(); public HostStats getHostStats(); - + // public double getAverageLoad(); - // public double getXapiMemoryUsageKBs(); + // public double getXapiMemoryUsageKBs(); } diff --git a/api/src/com/cloud/host/Status.java b/api/src/com/cloud/host/Status.java index aed35cbb040..97b151dc723 100755 --- a/api/src/com/cloud/host/Status.java +++ b/api/src/com/cloud/host/Status.java @@ -32,25 +32,25 @@ public enum Status { Removed(true, false, true), Error(true, false, true), Rebalancing(true, false, true); - + private final boolean updateManagementServer; private final boolean checkManagementServer; private final boolean lostConnection; - + private Status(boolean updateConnection, boolean checkManagementServer, boolean lostConnection) { this.updateManagementServer = updateConnection; this.checkManagementServer = checkManagementServer; this.lostConnection = lostConnection; } - + public boolean updateManagementServer() { return updateManagementServer; } - + public boolean checkManagementServer() { return checkManagementServer; } - + public boolean lostConnection() { return lostConnection; } @@ -82,16 +82,16 @@ public enum Status { public String getDescription() { return comment; } - + public boolean isUserRequest() { return isUserRequest; } } - + public static StateMachine2 getStateMachine() { return s_fsm; } - + public Status getNextStatus(Event e) throws NoTransitionException { return s_fsm.getNextState(this, e); } @@ -100,7 +100,7 @@ public enum Status { List from = s_fsm.getFromStates(this, e); return from.toArray(new Status[from.size()]); } - + public Set getPossibleEvents() { return s_fsm.getPossibleEvents(this); } diff --git a/api/src/com/cloud/hypervisor/Hypervisor.java b/api/src/com/cloud/hypervisor/Hypervisor.java index 25dd8b1458d..2e0012dca6f 100644 --- a/api/src/com/cloud/hypervisor/Hypervisor.java +++ b/api/src/com/cloud/hypervisor/Hypervisor.java @@ -23,7 +23,7 @@ public class Hypervisor { XenServer, KVM, VMware, - Hyperv, + Hyperv, VirtualBox, Parralels, BareMetal, diff --git a/api/src/com/cloud/hypervisor/HypervisorCapabilities.java b/api/src/com/cloud/hypervisor/HypervisorCapabilities.java index f91da354c96..efb8a6a208b 100644 --- a/api/src/com/cloud/hypervisor/HypervisorCapabilities.java +++ b/api/src/com/cloud/hypervisor/HypervisorCapabilities.java @@ -17,16 +17,14 @@ package com.cloud.hypervisor; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * HypervisorCapability represents one particular hypervisor version's capabilities. */ -public interface HypervisorCapabilities { - /** - * @return id of the host. - */ - long getId(); +public interface HypervisorCapabilities extends Identity, InternalIdentity{ /** * @return type of hypervisor diff --git a/api/src/com/cloud/hypervisor/HypervisorGuru.java b/api/src/com/cloud/hypervisor/HypervisorGuru.java index d3608dcc347..b4a0b06a7af 100644 --- a/api/src/com/cloud/hypervisor/HypervisorGuru.java +++ b/api/src/com/cloud/hypervisor/HypervisorGuru.java @@ -27,28 +27,28 @@ import com.cloud.vm.VirtualMachineProfile; public interface HypervisorGuru extends Adapter { HypervisorType getHypervisorType(); - + /** * Convert from a virtual machine to the - * virtual machine that the hypervisor expects. - * @param vm + * virtual machine that the hypervisor expects. + * @param vm * @return */ VirtualMachineTO implement(VirtualMachineProfile vm); - + /** * Give hypervisor guru opportunity to decide if certain command needs to be delegated to other host, mainly to secondary storage VM host * @param hostId original hypervisor host * @param cmd command that is going to be sent, hypervisor guru usually needs to register various context objects into the command object - * + * * @return delegated host id if the command will be delegated */ long getCommandHostDelegation(long hostId, Command cmd); - + /** * @return true if VM can be migrated independently with CloudStack, and therefore CloudStack needs to track and reflect host change * into CloudStack database, false if CloudStack enforces VM sync logic - * + * */ boolean trackVmHostChange(); diff --git a/api/src/com/cloud/network/IpAddress.java b/api/src/com/cloud/network/IpAddress.java index f67a1fa3c46..0ac7f500e2c 100644 --- a/api/src/com/cloud/network/IpAddress.java +++ b/api/src/com/cloud/network/IpAddress.java @@ -18,28 +18,30 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * * - Allocated = null * - AccountId = null * - DomainId = null - * + * * - State = Allocated * - AccountId = account owner. * - DomainId = domain of the account owner. * - Allocated = time it was allocated. */ -public interface IpAddress extends ControlledEntity { +public interface IpAddress extends ControlledEntity, Identity, InternalIdentity { enum State { Allocating, // The IP Address is being propagated to other network elements and is not ready for use yet. Allocated, // The IP address is in used. Releasing, // The IP address is being released for other network elements and is not ready for allocation. Free // The IP address is ready to be allocated. } - + enum Purpose { StaticNat, Lb @@ -67,11 +69,6 @@ public interface IpAddress extends ControlledEntity { public Long getPhysicalNetworkId(); - /** - * @return database id. - */ - long getId(); - void setState(IpAddress.State state); Long getAllocatedToAccountId(); @@ -89,5 +86,4 @@ public interface IpAddress extends ControlledEntity { * @param vpcId */ void setVpcId(Long vpcId); - } diff --git a/api/src/com/cloud/network/Network.java b/api/src/com/cloud/network/Network.java index 75d94ee163f..39a0b26c76a 100644 --- a/api/src/com/cloud/network/Network.java +++ b/api/src/com/cloud/network/Network.java @@ -16,23 +16,25 @@ // 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 org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.utils.fsm.FiniteState; import com.cloud.utils.fsm.StateMachine; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; /** - * owned by an account. + * owned by an account. */ -public interface Network extends ControlledEntity { - +public interface Network extends ControlledEntity, InternalIdentity, Identity { + public enum GuestType { Shared, Isolated @@ -45,10 +47,10 @@ public interface Network extends ControlledEntity { public static final Service Dhcp = new Service("Dhcp"); public static final Service Dns = new Service("Dns", Capability.AllowDnsSuffixModification); public static final Service Gateway = new Service("Gateway"); - public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, + public static final Service Firewall = new Service("Firewall", Capability.SupportedProtocols, Capability.MultipleIps, Capability.TrafficStatistics); public static final Service Lb = new Service("Lb", Capability.SupportedLBAlgorithms, Capability.SupportedLBIsolation, - Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, + Capability.SupportedProtocols, Capability.TrafficStatistics, Capability.LoadBalancingSupportedIps, Capability.SupportedStickinessMethods, Capability.ElasticLb); public static final Service UserData = new Service("UserData"); public static final Service SourceNat = new Service("SourceNat", Capability.SupportedSourceNatTypes, Capability.RedundantRouter); @@ -58,6 +60,7 @@ public interface Network extends ControlledEntity { public static final Service NetworkACL = new Service("NetworkACL", Capability.SupportedProtocols); public static final Service Connectivity = new Service("Connectivity"); + private String name; private Capability[] caps; @@ -65,7 +68,7 @@ public interface Network extends ControlledEntity { this.name = name; this.caps = caps; supportedServices.add(this); - } + } public String getName() { return name; @@ -85,11 +88,11 @@ public interface Network extends ControlledEntity { break; } } - } + } return success; } - + public static Service getService(String serviceName) { for (Service service : supportedServices) { if (service.getName().equalsIgnoreCase(serviceName)) { @@ -98,7 +101,7 @@ public interface Network extends ControlledEntity { } return null; } - + public static List listAllServices(){ return supportedServices; } @@ -109,7 +112,7 @@ public interface Network extends ControlledEntity { */ public static class Provider { private static List supportedProviders = new ArrayList(); - + public static final Provider VirtualRouter = new Provider("VirtualRouter", false); public static final Provider JuniperSRX = new Provider("JuniperSRX", true); public static final Provider F5BigIp = new Provider("F5BigIp", true); @@ -135,11 +138,11 @@ public interface Network extends ControlledEntity { public String getName() { return name; } - + public boolean isExternal() { return isExternal; } - + public static Provider getProvider(String providerName) { for (Provider provider : supportedProviders) { if (provider.getName().equalsIgnoreCase(providerName)) { @@ -153,7 +156,7 @@ public interface Network extends ControlledEntity { public static class Capability { private static List supportedCapabilities = new ArrayList(); - + public static final Capability SupportedProtocols = new Capability("SupportedProtocols"); public static final Capability SupportedLBAlgorithms = new Capability("SupportedLbAlgorithms"); public static final Capability SupportedLBIsolation = new Capability("SupportedLBIsolation"); @@ -167,7 +170,10 @@ 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"); + public static final Capability InlineMode = new Capability("InlineMode"); private String name; @@ -248,11 +254,6 @@ public interface Network extends ControlledEntity { } } - /** - * @return id of the network profile. Null means the network profile is not from the database. - */ - long getId(); - String getName(); Mode getMode(); @@ -287,14 +288,15 @@ public interface Network extends ControlledEntity { void setPhysicalNetworkId(Long physicalNetworkId); - ACLType getAclType(); - - boolean isRestartRequired(); + ACLType getAclType(); - boolean getSpecifyIpRanges(); + boolean isRestartRequired(); + + boolean getSpecifyIpRanges(); /** * @return */ Long getVpcId(); + } diff --git a/api/src/com/cloud/network/NetworkProfile.java b/api/src/com/cloud/network/NetworkProfile.java index cd25d9f677e..b5c463de375 100644 --- a/api/src/com/cloud/network/NetworkProfile.java +++ b/api/src/com/cloud/network/NetworkProfile.java @@ -21,9 +21,11 @@ import java.net.URI; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.api.InternalIdentity; public class NetworkProfile implements Network { private long id; + private String uuid; private long dataCenterId; private long ownerId; private long domainId; @@ -51,6 +53,7 @@ public class NetworkProfile implements Network { public NetworkProfile(Network network) { this.id = network.getId(); + this.uuid = network.getUuid(); this.broadcastUri = network.getBroadcastUri(); this.dataCenterId = network.getDataCenterId(); this.ownerId = network.getAccountId(); @@ -105,6 +108,12 @@ public class NetworkProfile implements Network { return id; } + + @Override + public String getUuid() { + return uuid; + } + @Override public long getDataCenterId() { return dataCenterId; diff --git a/api/src/com/cloud/network/NetworkService.java b/api/src/com/cloud/network/NetworkService.java index 6bbc36c75ac..d5841a4692e 100755 --- a/api/src/com/cloud/network/NetworkService.java +++ b/api/src/com/cloud/network/NetworkService.java @@ -20,10 +20,10 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -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; @@ -79,13 +79,13 @@ public interface NetworkService { Map> getNetworkOfferingServiceProvidersMap(long networkOfferingId); - PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, + PhysicalNetwork createPhysicalNetwork(Long zoneId, String vnetRange, String networkSpeed, List isolationMethods, String broadcastDomainRange, Long domainId, List tags, String name); - List searchPhysicalNetworks(Long id, Long zoneId, String keyword, + Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name); - PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, + PhysicalNetwork updatePhysicalNetwork(Long id, String networkSpeed, List tags, String newVnetRangeString, String state); boolean deletePhysicalNetwork(Long id); @@ -97,7 +97,7 @@ public interface NetworkService { PhysicalNetworkServiceProvider addProviderToPhysicalNetwork(Long physicalNetworkId, String providerName, Long destinationPhysicalNetworkId, List enabledServices); - List listNetworkServiceProviders(Long physicalNetworkId, String name, + Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize); PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String state, List enabledServices); @@ -114,7 +114,7 @@ public interface NetworkService { long findPhysicalNetworkId(long zoneId, String tag, TrafficType trafficType); - PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, + PhysicalNetworkTrafficType addTrafficTypeToPhysicalNetwork(Long physicalNetworkId, String trafficType, String xenLabel, String kvmLabel, String vmwareLabel, String simulatorLabel, String vlan); PhysicalNetworkTrafficType getPhysicalNetworkTrafficType(Long id); @@ -123,7 +123,7 @@ public interface NetworkService { boolean deletePhysicalNetworkTrafficType(Long id); - List listTrafficTypes(Long physicalNetworkId); + Pair, Integer> listTrafficTypes(Long physicalNetworkId); PhysicalNetwork getDefaultPhysicalNetworkByZoneAndTrafficType(long zoneId, TrafficType trafficType); @@ -132,19 +132,19 @@ public interface NetworkService { List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd); List getIsolatedNetworksWithSourceNATOwnedByAccountInZone(long zoneId, Account owner); - + List listNetworksByVpc(long vpcId); - + boolean isVmPartOfNetwork(long vmId, long ntwkId); /** * @param networkId * @param entityId * @return - * @throws ConcurrentOperationException - * @throws ResourceUnavailableException - * @throws ResourceAllocationException - * @throws InsufficientAddressCapacityException + * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ResourceAllocationException + * @throws InsufficientAddressCapacityException */ IpAddress associateIPToNetwork(long ipId, long networkId) throws InsufficientAddressCapacityException, ResourceAllocationException, ResourceUnavailableException, ConcurrentOperationException; @@ -161,12 +161,12 @@ public interface NetworkService { * @param networkOwnerId * @param vpcId TODO * @return - * @throws InsufficientCapacityException - * @throws ConcurrentOperationException - * @throws ResourceAllocationException + * @throws InsufficientCapacityException + * @throws ConcurrentOperationException + * @throws ResourceAllocationException */ Network createPrivateNetwork(String networkName, String displayText, long physicalNetworkId, String vlan, - String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId) + String startIp, String endIP, String gateway, String netmask, long networkOwnerId, Long vpcId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; /** * @param network diff --git a/api/src/com/cloud/network/Networks.java b/api/src/com/cloud/network/Networks.java index b96eaa2ff6c..b15661910b4 100755 --- a/api/src/com/cloud/network/Networks.java +++ b/api/src/com/cloud/network/Networks.java @@ -23,7 +23,7 @@ import com.cloud.utils.exception.CloudRuntimeException; /** * Network includes all of the enums used within networking. - * + * */ public class Networks { diff --git a/api/src/com/cloud/network/PhysicalNetwork.java b/api/src/com/cloud/network/PhysicalNetwork.java index be4b1d0d352..a495092879e 100644 --- a/api/src/com/cloud/network/PhysicalNetwork.java +++ b/api/src/com/cloud/network/PhysicalNetwork.java @@ -16,12 +16,15 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.List; /** - * + * */ -public interface PhysicalNetwork { +public interface PhysicalNetwork extends Identity, InternalIdentity { public enum State { Disabled, @@ -40,8 +43,6 @@ public interface PhysicalNetwork { ZONE; } - long getId(); - BroadcastDomainRange getBroadcastDomainRange(); // TrafficType getTrafficType(); @@ -60,8 +61,6 @@ public interface PhysicalNetwork { String getSpeed(); - String getUuid(); - String getName(); } diff --git a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java index 1b913115aa4..0a433dcbc05 100644 --- a/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java +++ b/api/src/com/cloud/network/PhysicalNetworkServiceProvider.java @@ -19,11 +19,12 @@ package com.cloud.network; import java.util.List; import com.cloud.network.Network.Service; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * */ -public interface PhysicalNetworkServiceProvider { +public interface PhysicalNetworkServiceProvider extends InternalIdentity { public enum State { Disabled, diff --git a/api/src/com/cloud/network/PhysicalNetworkTrafficType.java b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java index 0c0bfa1304e..62400e80a9e 100644 --- a/api/src/com/cloud/network/PhysicalNetworkTrafficType.java +++ b/api/src/com/cloud/network/PhysicalNetworkTrafficType.java @@ -17,13 +17,13 @@ package com.cloud.network; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** - * + * */ -public interface PhysicalNetworkTrafficType { - - long getId(); +public interface PhysicalNetworkTrafficType extends InternalIdentity, Identity { long getPhysicalNetworkId(); @@ -36,6 +36,4 @@ public interface PhysicalNetworkTrafficType { String getVmwareNetworkLabel(); String getSimulatorNetworkLabel(); - - String getUuid(); } diff --git a/api/src/com/cloud/network/PublicIpAddress.java b/api/src/com/cloud/network/PublicIpAddress.java index 5d117b84243..21dae54202a 100644 --- a/api/src/com/cloud/network/PublicIpAddress.java +++ b/api/src/com/cloud/network/PublicIpAddress.java @@ -16,19 +16,20 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.dc.Vlan; +import org.apache.cloudstack.api.InternalIdentity; /** */ -public interface PublicIpAddress extends ControlledEntity, IpAddress, Vlan { - +public interface PublicIpAddress extends ControlledEntity, IpAddress, Vlan, InternalIdentity { + String getMacAddress(); - + public String getNetmask(); - + public String getGateway(); - + @Override public String getVlanTag(); -} \ No newline at end of file +} diff --git a/api/src/com/cloud/network/RemoteAccessVpn.java b/api/src/com/cloud/network/RemoteAccessVpn.java index 162e0fce133..1b463309a5f 100644 --- a/api/src/com/cloud/network/RemoteAccessVpn.java +++ b/api/src/com/cloud/network/RemoteAccessVpn.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; public interface RemoteAccessVpn extends ControlledEntity { enum State { @@ -24,7 +24,7 @@ public interface RemoteAccessVpn extends ControlledEntity { Running, Removed } - + long getServerAddressId(); String getIpRange(); String getIpsecPresharedKey(); diff --git a/api/src/com/cloud/network/Site2SiteCustomerGateway.java b/api/src/com/cloud/network/Site2SiteCustomerGateway.java index 8950c771705..3a5438575d9 100644 --- a/api/src/com/cloud/network/Site2SiteCustomerGateway.java +++ b/api/src/com/cloud/network/Site2SiteCustomerGateway.java @@ -5,7 +5,7 @@ // 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, @@ -18,10 +18,11 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteCustomerGateway extends ControlledEntity { - public long getId(); +public interface Site2SiteCustomerGateway extends ControlledEntity, Identity, InternalIdentity { public String getGatewayIp(); public String getGuestCidrList(); public String getIpsecPsk(); diff --git a/api/src/com/cloud/network/Site2SiteVpnConnection.java b/api/src/com/cloud/network/Site2SiteVpnConnection.java index 6cf52a94943..810f9992d93 100644 --- a/api/src/com/cloud/network/Site2SiteVpnConnection.java +++ b/api/src/com/cloud/network/Site2SiteVpnConnection.java @@ -5,7 +5,7 @@ // 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, @@ -18,9 +18,10 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteVpnConnection extends ControlledEntity { +public interface Site2SiteVpnConnection extends ControlledEntity, InternalIdentity { enum State { Pending, Connected, @@ -28,6 +29,7 @@ public interface Site2SiteVpnConnection extends ControlledEntity { Error, } public long getId(); + public String getUuid(); public long getVpnGatewayId(); public long getCustomerGatewayId(); public State getState(); diff --git a/api/src/com/cloud/network/Site2SiteVpnGateway.java b/api/src/com/cloud/network/Site2SiteVpnGateway.java index 52ec5971c14..81379132844 100644 --- a/api/src/com/cloud/network/Site2SiteVpnGateway.java +++ b/api/src/com/cloud/network/Site2SiteVpnGateway.java @@ -5,7 +5,7 @@ // 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, @@ -18,10 +18,11 @@ package com.cloud.network; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Site2SiteVpnGateway extends ControlledEntity { - public long getId(); +public interface Site2SiteVpnGateway extends ControlledEntity, Identity, InternalIdentity { public long getAddrId(); public long getVpcId(); public Date getRemoved(); diff --git a/api/src/com/cloud/network/StorageNetworkService.java b/api/src/com/cloud/network/StorageNetworkService.java index 86a8352316a..1bda247179c 100755 --- a/api/src/com/cloud/network/StorageNetworkService.java +++ b/api/src/com/cloud/network/StorageNetworkService.java @@ -19,18 +19,18 @@ package com.cloud.network; import java.sql.SQLException; import java.util.List; -import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.*; +import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import com.cloud.dc.StorageNetworkIpRange; +import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; public interface StorageNetworkService { StorageNetworkIpRange createIpRange(CreateStorageNetworkIpRangeCmd cmd) throws SQLException; void deleteIpRange(DeleteStorageNetworkIpRangeCmd cmd); - List listIpRange(listStorageNetworkIpRangeCmd cmd); + List listIpRange(ListStorageNetworkIpRangeCmd cmd); StorageNetworkIpRange updateIpRange(UpdateStorageNetworkIpRangeCmd cmd); } diff --git a/api/src/com/cloud/network/VirtualNetworkApplianceService.java b/api/src/com/cloud/network/VirtualNetworkApplianceService.java index d0fb527037b..7b553b29a7f 100644 --- a/api/src/com/cloud/network/VirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VirtualNetworkApplianceService.java @@ -16,38 +16,39 @@ // under the License. package com.cloud.network; -import com.cloud.api.commands.UpgradeRouterCmd; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; public interface VirtualNetworkApplianceService { /** * Starts domain router - * + * * @param cmd * the command specifying router's id * @return DomainRouter object */ - VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, + VirtualRouter startRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** * Reboots domain router - * + * * @param cmd * the command specifying router's id * @return router if successful */ - VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, + VirtualRouter rebootRouter(long routerId, boolean reprogramNetwork) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; VirtualRouter upgradeRouter(UpgradeRouterCmd cmd); /** * Stops domain router - * + * * @param id * of the router * @param forced @@ -60,6 +61,6 @@ public interface VirtualNetworkApplianceService { VirtualRouter startRouter(long id) throws ResourceUnavailableException, InsufficientCapacityException, ConcurrentOperationException; - VirtualRouter destroyRouter(long routerId) throws ResourceUnavailableException, ConcurrentOperationException; + VirtualRouter destroyRouter(long routerId, Account caller, Long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException; } diff --git a/api/src/com/cloud/network/VirtualRouterProvider.java b/api/src/com/cloud/network/VirtualRouterProvider.java index f0837d650cf..ed6a2741ba0 100644 --- a/api/src/com/cloud/network/VirtualRouterProvider.java +++ b/api/src/com/cloud/network/VirtualRouterProvider.java @@ -16,7 +16,10 @@ // under the License. package com.cloud.network; -public interface VirtualRouterProvider { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface VirtualRouterProvider extends InternalIdentity, Identity { public enum VirtualRouterProviderType { VirtualRouter, ElasticLoadBalancerVm, @@ -25,8 +28,6 @@ public interface VirtualRouterProvider { public VirtualRouterProviderType getType(); - public long getId(); - public boolean isEnabled(); public long getNspId(); diff --git a/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java b/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java index 03eb576bc8d..6e8fd38ba66 100644 --- a/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java +++ b/api/src/com/cloud/network/VpcVirtualNetworkApplianceService.java @@ -32,7 +32,7 @@ public interface VpcVirtualNetworkApplianceService extends VirtualNetworkApplian * @throws ResourceUnavailableException * @throws InsufficientCapacityException */ - boolean addVpcRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) + boolean addVpcRouterToGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** @@ -43,7 +43,7 @@ public interface VpcVirtualNetworkApplianceService extends VirtualNetworkApplian * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean removeVpcRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) + boolean removeVpcRouterFromGuestNetwork(VirtualRouter router, Network network, boolean isRedundant) throws ConcurrentOperationException, ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/VpnUser.java b/api/src/com/cloud/network/VpnUser.java index 07a3ee3343e..ad84e9178d6 100644 --- a/api/src/com/cloud/network/VpnUser.java +++ b/api/src/com/cloud/network/VpnUser.java @@ -16,17 +16,17 @@ // under the License. package com.cloud.network; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VpnUser extends ControlledEntity { +public interface VpnUser extends ControlledEntity, InternalIdentity, Identity { enum State { Add, Revoke, Active } - long getId(); - String getUsername(); String getPassword(); diff --git a/api/src/com/cloud/network/as/AutoScaleCounter.java b/api/src/com/cloud/network/as/AutoScaleCounter.java new file mode 100644 index 00000000000..ca7b65a39d4 --- /dev/null +++ b/api/src/com/cloud/network/as/AutoScaleCounter.java @@ -0,0 +1,122 @@ +// 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.as; + +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.annotations.SerializedName; + +public class AutoScaleCounter { + public static class AutoScaleCounterType { + private String _name; + + public static final AutoScaleCounterType Snmp = new AutoScaleCounterType("snmp"); + public static final AutoScaleCounterType Netscaler = new AutoScaleCounterType("netscaler"); + + public AutoScaleCounterType(String name) { + _name = name; + } + + public String getName() { + return _name; + } + } + + public class AutoScaleCounterParam { + @SerializedName("paramname") + private String _paramName; + + @SerializedName("required") + private Boolean _required; + + @SerializedName("isflag") + private Boolean _isFlag; + + @SerializedName("description") + private String _description; + + public AutoScaleCounterParam(String name, Boolean required, + String description, Boolean flag) { + this._paramName = name; + this._required = required; + this._description = description; + this._isFlag = flag; + } + + public String getParamName() { + return _paramName; + } + + public void setParamName(String paramName) { + this._paramName = paramName; + } + + public Boolean getIsflag() { + return _isFlag; + } + + public void setIsflag(Boolean isFlag) { + this._isFlag = isFlag; + } + + public Boolean getRequired() { + return _required; + } + + public void setRequired(Boolean required) { + this._required = required; + } + + public String getDescription() { + return _description; + } + + public void setDescription(String description) { + this._description = description; + } + } + + @SerializedName("methodname") + private String _counterName; + + @SerializedName("paramlist") + private List _paramList; + + public AutoScaleCounter(AutoScaleCounterType methodType) { + this._counterName = methodType.getName(); + this._paramList = new ArrayList(1); + } + + public void addParam(String name, Boolean required, String description, Boolean isFlag) { + AutoScaleCounterParam param = new AutoScaleCounterParam(name, required, description, isFlag); + _paramList.add(param); + return; + } + + public String getName() { + return _counterName; + } + + public List getParamList() { + return _paramList; + } + + public void setParamList(List paramList) { + this._paramList = paramList; + } +} diff --git a/api/src/com/cloud/network/as/AutoScalePolicy.java b/api/src/com/cloud/network/as/AutoScalePolicy.java new file mode 100644 index 00000000000..7f94f355921 --- /dev/null +++ b/api/src/com/cloud/network/as/AutoScalePolicy.java @@ -0,0 +1,35 @@ +// 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.as; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface AutoScalePolicy extends ControlledEntity, InternalIdentity { + + long getId(); + + String getUuid(); + + public int getDuration(); + + public int getQuietTime(); + + public String getAction(); + +} diff --git a/api/src/com/cloud/network/as/AutoScaleService.java b/api/src/com/cloud/network/as/AutoScaleService.java new file mode 100644 index 00000000000..daa8d191366 --- /dev/null +++ b/api/src/com/cloud/network/as/AutoScaleService.java @@ -0,0 +1,73 @@ +// 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.as; + +import java.util.List; + +import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd; +import org.apache.cloudstack.api.command.user.autoscale.*; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmProfileCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListAutoScalePoliciesCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmGroupCmd; +import com.cloud.exception.ResourceInUseException; +import com.cloud.exception.ResourceUnavailableException; + +public interface AutoScaleService { + + public AutoScalePolicy createAutoScalePolicy(CreateAutoScalePolicyCmd createAutoScalePolicyCmd); + + public boolean deleteAutoScalePolicy(long autoScalePolicyId); + + List listAutoScalePolicies(ListAutoScalePoliciesCmd cmd); + + AutoScalePolicy updateAutoScalePolicy(UpdateAutoScalePolicyCmd cmd); + + AutoScaleVmProfile createAutoScaleVmProfile(CreateAutoScaleVmProfileCmd cmd); + + boolean deleteAutoScaleVmProfile(long profileId); + + List listAutoScaleVmProfiles(ListAutoScaleVmProfilesCmd listAutoScaleVmProfilesCmd); + + AutoScaleVmProfile updateAutoScaleVmProfile(UpdateAutoScaleVmProfileCmd cmd); + + AutoScaleVmGroup createAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd); + + boolean configureAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) throws ResourceUnavailableException; + + boolean deleteAutoScaleVmGroup(long vmGroupId); + + AutoScaleVmGroup updateAutoScaleVmGroup(UpdateAutoScaleVmGroupCmd cmd); + + AutoScaleVmGroup enableAutoScaleVmGroup(Long id); + + AutoScaleVmGroup disableAutoScaleVmGroup(Long id); + + List listAutoScaleVmGroups(ListAutoScaleVmGroupsCmd listAutoScaleVmGroupsCmd); + + Counter createCounter(CreateCounterCmd cmd); + + boolean deleteCounter(long counterId) throws ResourceInUseException; + + List listCounters(ListCountersCmd cmd); + + Condition createCondition(CreateConditionCmd cmd); + + List listConditions(ListConditionsCmd cmd); + + boolean deleteCondition(long conditionId) throws ResourceInUseException; +} diff --git a/api/src/com/cloud/network/as/AutoScaleVmGroup.java b/api/src/com/cloud/network/as/AutoScaleVmGroup.java new file mode 100644 index 00000000000..faa166d2bae --- /dev/null +++ b/api/src/com/cloud/network/as/AutoScaleVmGroup.java @@ -0,0 +1,52 @@ +// 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.as; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; + + +public interface AutoScaleVmGroup extends ControlledEntity, InternalIdentity { + + String State_New = "new"; + String State_Revoke = "revoke"; + String State_Enabled = "enabled"; + String State_Disabled = "disabled"; + + long getId(); + + @Override + long getAccountId(); + + Long getLoadBalancerId(); + + long getProfileId(); + + int getMinMembers(); + + int getMaxMembers(); + + int getMemberPort(); + + int getInterval(); + + String getState(); + + String getUuid(); + +} diff --git a/api/src/com/cloud/network/as/AutoScaleVmProfile.java b/api/src/com/cloud/network/as/AutoScaleVmProfile.java new file mode 100644 index 00000000000..3be5a3e8124 --- /dev/null +++ b/api/src/com/cloud/network/as/AutoScaleVmProfile.java @@ -0,0 +1,49 @@ +// 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.as; + +import java.util.List; + +import org.apache.cloudstack.acl.ControlledEntity; +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * AutoScaleVmProfile + */ +public interface AutoScaleVmProfile extends ControlledEntity, InternalIdentity { + + public long getId(); + + public String getUuid(); + + public Long getZoneId(); + + public Long getServiceOfferingId(); + + public Long getTemplateId(); + + public String getOtherDeployParams(); + + List> getCounterParams(); + + public Integer getDestroyVmGraceperiod(); + + public long getAutoScaleUserId(); + +} diff --git a/api/src/com/cloud/network/as/Condition.java b/api/src/com/cloud/network/as/Condition.java new file mode 100644 index 00000000000..b09dc2e91a8 --- /dev/null +++ b/api/src/com/cloud/network/as/Condition.java @@ -0,0 +1,35 @@ +// 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.as; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Condition extends ControlledEntity, Identity, InternalIdentity { + + static enum Operator { + EQ, GT, LT, GE, LE + }; + + long getCounterid(); + + long getThreshold(); + + Operator getRelationalOperator(); +} diff --git a/api/src/com/cloud/network/as/Counter.java b/api/src/com/cloud/network/as/Counter.java new file mode 100644 index 00000000000..207ec57b592 --- /dev/null +++ b/api/src/com/cloud/network/as/Counter.java @@ -0,0 +1,35 @@ +// 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.as; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface Counter extends InternalIdentity, Identity { + + public static enum Source { + netscaler, + snmp + } + + String getName(); + + String getValue(); + + Source getSource(); +} diff --git a/api/src/com/cloud/network/element/IpDeployer.java b/api/src/com/cloud/network/element/IpDeployer.java index 3eebe82cf2e..55b21abe9ab 100644 --- a/api/src/com/cloud/network/element/IpDeployer.java +++ b/api/src/com/cloud/network/element/IpDeployer.java @@ -21,6 +21,7 @@ import java.util.Set; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.PublicIpAddress; @@ -33,4 +34,6 @@ public interface IpDeployer { * @throws ResourceUnavailableException */ boolean applyIps(Network network, List ipAddress, Set services) throws ResourceUnavailableException; + + Provider getProvider(); } diff --git a/api/src/com/cloud/network/element/IpDeployingRequester.java b/api/src/com/cloud/network/element/IpDeployingRequester.java new file mode 100644 index 00000000000..01a11b570c1 --- /dev/null +++ b/api/src/com/cloud/network/element/IpDeployingRequester.java @@ -0,0 +1,28 @@ +// 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.element; + +import com.cloud.network.Network; + +public interface IpDeployingRequester { + /** + * Would return the IpDeployer can deploy IP for this element + * @param network + * @return IpDeployer object, or null if there is no deployer for this element + */ + IpDeployer getIpDeployer(Network network); +} diff --git a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java index 3c5474642a4..879ea0ed663 100644 --- a/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java +++ b/api/src/com/cloud/network/element/LoadBalancingServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.lb.LoadBalancingRule; -public interface LoadBalancingServiceProvider extends NetworkElement { +public interface LoadBalancingServiceProvider extends NetworkElement, IpDeployingRequester { /** * Apply rules * @param network @@ -32,13 +32,12 @@ public interface LoadBalancingServiceProvider extends NetworkElement { */ boolean applyLBRules(Network network, List rules) throws ResourceUnavailableException; - IpDeployer getIpDeployer(Network network); /** * Validate rules * @param network * @param rule * @return true/false. true should be return if there are no validations. false should be return if any oneof the validation fails. - * @throws + * @throws */ boolean validateLBRule(Network network, LoadBalancingRule rule); } diff --git a/api/src/com/cloud/network/element/NetworkElement.java b/api/src/com/cloud/network/element/NetworkElement.java index 480d0a60ee0..d89c2a3c403 100644 --- a/api/src/com/cloud/network/element/NetworkElement.java +++ b/api/src/com/cloud/network/element/NetworkElement.java @@ -103,10 +103,11 @@ public interface NetworkElement extends Adapter { /** * The network is being destroyed. * @param network + * @param context TODO * @return * @throws ConcurrentOperationException */ - boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException; + boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; /** * Check if the instances of this Element are configured to be used on the physical network referred by this provider. diff --git a/api/src/com/cloud/network/element/PortForwardingServiceProvider.java b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java index d6589515d2a..e99bc2fd416 100644 --- a/api/src/com/cloud/network/element/PortForwardingServiceProvider.java +++ b/api/src/com/cloud/network/element/PortForwardingServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.PortForwardingRule; -public interface PortForwardingServiceProvider extends NetworkElement { +public interface PortForwardingServiceProvider extends NetworkElement, IpDeployingRequester { /** * Apply rules * @param network @@ -31,6 +31,4 @@ public interface PortForwardingServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyPFRules(Network network, List rules) throws ResourceUnavailableException; - - IpDeployer getIpDeployer(Network network); } diff --git a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java index d799b0bf4e3..4625d22f6a5 100644 --- a/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java +++ b/api/src/com/cloud/network/element/RemoteAccessVPNServiceProvider.java @@ -23,12 +23,10 @@ import com.cloud.network.Network; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; -public interface RemoteAccessVPNServiceProvider extends NetworkElement { +public interface RemoteAccessVPNServiceProvider extends NetworkElement, IpDeployingRequester { String[] applyVpnUsers(RemoteAccessVpn vpn, List users) throws ResourceUnavailableException; boolean startVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - + boolean stopVpn(Network network, RemoteAccessVpn vpn) throws ResourceUnavailableException; - - IpDeployer getIpDeployer(Network network); } diff --git a/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java b/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java index 8063cbb5642..a61273a8159 100644 --- a/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java +++ b/api/src/com/cloud/network/element/Site2SiteVpnServiceProvider.java @@ -5,7 +5,7 @@ // 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, @@ -22,6 +22,6 @@ import com.cloud.network.Site2SiteVpnConnection; public interface Site2SiteVpnServiceProvider extends NetworkElement { boolean startSite2SiteVpn(Site2SiteVpnConnection conn) throws ResourceUnavailableException; - + boolean stopSite2SiteVpn(Site2SiteVpnConnection conn) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/SourceNatServiceProvider.java b/api/src/com/cloud/network/element/SourceNatServiceProvider.java index af63c6018b9..eaf43f82edd 100644 --- a/api/src/com/cloud/network/element/SourceNatServiceProvider.java +++ b/api/src/com/cloud/network/element/SourceNatServiceProvider.java @@ -16,8 +16,5 @@ // under the License. package com.cloud.network.element; -import com.cloud.network.Network; - -public interface SourceNatServiceProvider extends NetworkElement { - IpDeployer getIpDeployer(Network network); +public interface SourceNatServiceProvider extends NetworkElement, IpDeployingRequester { } diff --git a/api/src/com/cloud/network/element/StaticNatServiceProvider.java b/api/src/com/cloud/network/element/StaticNatServiceProvider.java index 20174b17251..50f5e204658 100644 --- a/api/src/com/cloud/network/element/StaticNatServiceProvider.java +++ b/api/src/com/cloud/network/element/StaticNatServiceProvider.java @@ -22,7 +22,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.rules.StaticNat; -public interface StaticNatServiceProvider extends NetworkElement { +public interface StaticNatServiceProvider extends NetworkElement, IpDeployingRequester { /** * Creates static nat rule (public IP to private IP mapping) on the network element * @param config @@ -31,6 +31,4 @@ public interface StaticNatServiceProvider extends NetworkElement { * @throws ResourceUnavailableException */ boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException; - - IpDeployer getIpDeployer(Network network); } diff --git a/api/src/com/cloud/network/element/UserDataServiceProvider.java b/api/src/com/cloud/network/element/UserDataServiceProvider.java index d848216d37f..321ccc7d456 100644 --- a/api/src/com/cloud/network/element/UserDataServiceProvider.java +++ b/api/src/com/cloud/network/element/UserDataServiceProvider.java @@ -29,4 +29,5 @@ import com.cloud.vm.VirtualMachineProfile; public interface UserDataServiceProvider extends NetworkElement { public boolean addPasswordAndUserdata(Network network, NicProfile nic, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException; boolean savePassword(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; + boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/element/VirtualRouterElementService.java b/api/src/com/cloud/network/element/VirtualRouterElementService.java index bf8cad27946..3ba2045cfd6 100644 --- a/api/src/com/cloud/network/element/VirtualRouterElementService.java +++ b/api/src/com/cloud/network/element/VirtualRouterElementService.java @@ -18,8 +18,8 @@ package com.cloud.network.element; import java.util.List; -import com.cloud.api.commands.ConfigureVirtualRouterElementCmd; -import com.cloud.api.commands.ListVirtualRouterElementsCmd; +import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VirtualRouterProvider.VirtualRouterProviderType; import com.cloud.utils.component.PluggableService; diff --git a/api/src/com/cloud/network/element/VpcProvider.java b/api/src/com/cloud/network/element/VpcProvider.java index e4593e9dbdd..482fe6245a7 100644 --- a/api/src/com/cloud/network/element/VpcProvider.java +++ b/api/src/com/cloud/network/element/VpcProvider.java @@ -36,20 +36,21 @@ public interface VpcProvider extends NetworkElement{ * @param vpc fully specified vpc configuration. * @throws InsufficientNetworkCapacityException TODO */ - boolean implementVpc(Vpc vpc, DeployDestination dest, ReservationContext context) + boolean implementVpc(Vpc vpc, DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; /** * @param vpc + * @param context TODO * @return * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean shutdownVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException; + boolean createPrivateGateway(PrivateGateway gateway) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean deletePrivateGateway(PrivateGateway privateGateway) throws ConcurrentOperationException, ResourceUnavailableException; - + boolean applyStaticRoutes(Vpc vpc, List routes) throws ResourceUnavailableException; } diff --git a/api/src/com/cloud/network/firewall/FirewallService.java b/api/src/com/cloud/network/firewall/FirewallService.java index 6eb9f9943ac..3858499b2bb 100644 --- a/api/src/com/cloud/network/firewall/FirewallService.java +++ b/api/src/com/cloud/network/firewall/FirewallService.java @@ -16,22 +16,24 @@ // under the License. package com.cloud.network.firewall; + import java.util.List; -import com.cloud.api.commands.ListFirewallRulesCmd; +import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.Account; +import com.cloud.utils.Pair; public interface FirewallService { FirewallRule createFirewallRule(FirewallRule rule) throws NetworkRuleConflictException; - List listFirewallRules(ListFirewallRulesCmd cmd); + Pair, Integer> listFirewallRules(ListFirewallRulesCmd cmd); /** * Revokes a firewall rule - * + * * @param ruleId * the id of the rule to revoke. * @return diff --git a/api/src/com/cloud/network/firewall/NetworkACLService.java b/api/src/com/cloud/network/firewall/NetworkACLService.java index 1977088881c..a1fb02cb71f 100644 --- a/api/src/com/cloud/network/firewall/NetworkACLService.java +++ b/api/src/com/cloud/network/firewall/NetworkACLService.java @@ -16,18 +16,20 @@ // under the License. package com.cloud.network.firewall; + import java.util.List; -import com.cloud.api.commands.ListNetworkACLsCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.Account; +import com.cloud.utils.Pair; public interface NetworkACLService { FirewallRule getNetworkACL(long ruleId); boolean applyNetworkACLs(long networkId, Account caller) throws ResourceUnavailableException; - + /** * @param createNetworkACLCmd * @return @@ -43,6 +45,6 @@ public interface NetworkACLService { * @param listNetworkACLsCmd * @return */ - List listNetworkACLs(ListNetworkACLsCmd cmd); - + Pair, Integer> listNetworkACLs(ListNetworkACLsCmd cmd); + } diff --git a/api/src/com/cloud/network/guru/NetworkGuru.java b/api/src/com/cloud/network/guru/NetworkGuru.java index 9b8c04b4fc3..4a9b871e240 100755 --- a/api/src/com/cloud/network/guru/NetworkGuru.java +++ b/api/src/com/cloud/network/guru/NetworkGuru.java @@ -35,7 +35,7 @@ import com.cloud.vm.VirtualMachineProfile; /** * - Designs a virtual network depending on the network offering. * - Implements the virtual network when a virtual machine requires the network to be started. - * + * * There can be multiple NetworkGurus in a CloudStack system. Each NetworkGuru * resources when VMs are gone. * @@ -44,28 +44,28 @@ import com.cloud.vm.VirtualMachineProfile; * This means the NetworkGuru checks the parameters such as cidr, gateway, * vlan, etc and returns a network that can work with those paremeters. * Note that at this point the network is only a virtual network. It has - * not been substantiated with resources, such as vlan, to make the network + * not been substantiated with resources, such as vlan, to make the network * functional in the physical environment. At this stage, the network is in - * Allocated state. - * - * - When the first virtual machine is about to be started and requires network + * Allocated state. + * + * - When the first virtual machine is about to be started and requires network * services, the guest network needs to have resources to make it usable * within the physical environment. At this time, the NetworkGuru is * called with the implement() method to acquire those resources. - * + * * - For every virtual machine starting in the network, the NetworkGuru is * asked via the reserve() method to make sure everything the virtual * machine needs to be functional in the network is reserved. - * + * * - For every virtual machine being stopped in the network, the NetworkGuru * is informed via the release() method to make sure resources occupied * by the virtual machine is released. - * + * * - If all virtual machines within the network have been stopped, the guest * network is garbage collected. When a guest network is garbage collected * the NetworkGuru is informed via the shutdown() method to release any * resources it allocated to that network. - * + * * - When a guest network is being deleted, the NetworkGuru is informed via * the trash() method. * @@ -74,18 +74,18 @@ public interface NetworkGuru extends Adapter { /** * Cloud stack requires the NetworkGuru to design a guest network given * the software packages Once a NetworkGuru returns the designed network, - * that NetworkGuru is forever associated with the guest network. It is + * that NetworkGuru is forever associated with the guest network. It is * very important for the NetworkGuru implementation to be very specific * about the network it is responsible for designing. Things that can * be used to make determination can be isolation methods, services * provided on the guest network and the service provider that's on the * guest network. - * + * * If a network is already fully substantiated with the necessary resources - * during this design phase, then the state should be set to Setup. If + * during this design phase, then the state should be set to Setup. If * the resources are not allocated at this point, the state should be set - * to Allocated. - * + * to Allocated. + * * @param offering network offering that contains the package of services * the end user intends to use on that network. * @param plan where is this network being deployed. @@ -99,29 +99,29 @@ public interface NetworkGuru extends Adapter { * For guest networks that are in Allocated state after the design stage, * resources are allocated when the guest network is actually being used * by a virtual machine. implement() is called to acquire those resources. - * + * * @param network network to be implemented. * @param offering network offering that the network was created with. * @param destination where the network is being deployed in. * @return a fully implemented Network. - * @throws InsufficientVirtualNetworkCapcityException if there's not + * @throws InsufficientVirtualNetworkCapcityException if there's not * enough resources to make the guest network usable in the physical - * environment. At this time, the admin generally must be involved to + * environment. At this time, the admin generally must be involved to * allocate more resources before any more guest network can be implemented. */ Network implement(Network network, NetworkOffering offering, DeployDestination destination, ReservationContext context) throws InsufficientVirtualNetworkCapcityException; /** - * Once a guest network has been designed, virtual machines can be - * created. allocated() is called for the NetworkGuru to design a nic - * that will make the virtual machine work within the guest network. - * + * Once a guest network has been designed, virtual machines can be + * created. allocated() is called for the NetworkGuru to design a nic + * that will make the virtual machine work within the guest network. + * * @param network guest network that the virtual machine will be deployed in. - * @param nic nic information that the end user wants to set. The + * @param nic nic information that the end user wants to set. The * NetworkGuru should check this information with the guest * network settings to make sure everything will work. * @param vm virtual machine that is about to be deployed. - * @return NicProfile nic with all of the information + * @return NicProfile nic with all of the information * @throws InsufficientVirtualNetworkCapcityException if there's * insufficient capacity within the guest network. * @throws InsufficientAddressCapacityException if there are not addresses @@ -134,7 +134,7 @@ public interface NetworkGuru extends Adapter { * be allocated its resources in order for it to participate within the * guest network. reserve() is called for the NetworkGuru to make sure * that works. - * + * * @param nic nic that the vm is using to access the guest network. * @param network guest network the vm is in. * @param vm vm @@ -145,14 +145,14 @@ public interface NetworkGuru extends Adapter { * @throws InsufficientAddressCapacityException if there's not enough ip * addresses. * @throws ConcurrentOperationException if there are multiple operations - * happening on this guest network or vm. + * happening on this guest network or vm. */ void reserve(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest, ReservationContext context) throws InsufficientVirtualNetworkCapcityException, InsufficientAddressCapacityException, ConcurrentOperationException; /** * When a virtual machine is stopped, the NetworkGuru is informed via the - * release() method to release any resources. - * + * release() method to release any resources. + * * @param nic nic that the vm is using to access the guest network. * @param vm virtual machine * @param reservationId reservation id passed to it in the ReservationContext @@ -164,7 +164,7 @@ public interface NetworkGuru extends Adapter { * When a virtual machine is destroyed, the NetworkGuru is informed via * the deallocate() method to make sure any resources that are allocated * are released. - * + * * @param network guest network that the vm was running in. * @param nic nic that the vm was using to access the guest network. * @param vm virtual machine being destroyed. @@ -181,19 +181,19 @@ public interface NetworkGuru extends Adapter { void updateNicProfile(NicProfile profile, Network network); /** - * When no virtual machines are running in the network, the network is + * When no virtual machines are running in the network, the network is * shutdown and all physical resources are released. The NetworkGuru is * informed via the shutdown method(). - * + * * @param network guest network being shut down * @param offering network offering the guest network was created with. */ void shutdown(NetworkProfile network, NetworkOffering offering); /** - * When a guest network is destroyed, the NetworkGuru is informed via the + * When a guest network is destroyed, the NetworkGuru is informed via the * trash() method to recover any resources. - * + * * @param network guest network being destroyed. * @param offering network offering the guest network was created with. * @param owner owner of the network. diff --git a/api/src/com/cloud/network/lb/LoadBalancingRule.java b/api/src/com/cloud/network/lb/LoadBalancingRule.java index 9b4eddcc61c..b68b9cbddd4 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRule.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRule.java @@ -18,50 +18,58 @@ package com.cloud.network.lb; import java.util.List; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.Condition; +import com.cloud.network.as.Counter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; -public class LoadBalancingRule implements FirewallRule, LoadBalancer{ +public class LoadBalancingRule implements FirewallRule, LoadBalancer { private LoadBalancer lb; private List destinations; private List stickinessPolicies; - - public LoadBalancingRule(LoadBalancer lb, List destinations, List stickinessPolicies) { + private LbAutoScaleVmGroup autoScaleVmGroup; + + public LoadBalancingRule(LoadBalancer lb, List destinations, List stickinessPolicies) { this.lb = lb; this.destinations = destinations; this.stickinessPolicies = stickinessPolicies; } - + @Override public long getId() { return lb.getId(); } - + @Override public long getAccountId() { return lb.getAccountId(); } - + @Override public long getDomainId() { return lb.getDomainId(); } - + @Override public String getName() { return lb.getName(); } - + @Override public String getDescription() { return lb.getDescription(); } + @Override public int getDefaultPortStart() { return lb.getDefaultPortStart(); } - + @Override public int getDefaultPortEnd() { return lb.getDefaultPortEnd(); @@ -71,22 +79,27 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ public String getAlgorithm() { return lb.getAlgorithm(); } - + + @Override + public String getUuid() { + return lb.getUuid(); + } + @Override public String getXid() { return lb.getXid(); } - + @Override public Long getSourceIpAddressId() { return lb.getSourceIpAddressId(); } - + @Override public Integer getSourcePortStart() { return lb.getSourcePortStart(); } - + @Override public Integer getSourcePortEnd() { return lb.getSourcePortEnd(); @@ -96,22 +109,22 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ public String getProtocol() { return lb.getProtocol(); } - + @Override public Purpose getPurpose() { return Purpose.LoadBalancing; } - + @Override public State getState() { return lb.getState(); } - + @Override public long getNetworkId() { return lb.getNetworkId(); } - + public LoadBalancer getLb() { return lb; } @@ -119,12 +132,12 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ public List getDestinations() { return destinations; } - + public List getStickinessPolicies() { return stickinessPolicies; } - - + + public interface Destination { String getIpAddress(); int getDestinationPortStart(); @@ -148,7 +161,7 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ this._params = params; this._revoke = false; } - + public String getMethodName() { return _methodName; } @@ -161,66 +174,224 @@ public class LoadBalancingRule implements FirewallRule, LoadBalancer{ return _revoke; } } - + public static class LbDestination implements Destination { private int portStart; private int portEnd; private String ip; boolean revoked; - + public LbDestination(int portStart, int portEnd, String ip, boolean revoked) { this.portStart = portStart; this.portEnd = portEnd; this.ip = ip; this.revoked = revoked; } - + + @Override public String getIpAddress() { return ip; } + @Override public int getDestinationPortStart() { return portStart; } + @Override public int getDestinationPortEnd() { return portEnd; } - + + @Override public boolean isRevoked() { return revoked; } - + public void setRevoked(boolean revoked) { this.revoked = revoked; } } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; } - + @Override public List getSourceCidrList() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } - + @Override public TrafficType getTrafficType() { return null; } + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } + public LbAutoScaleVmGroup getAutoScaleVmGroup() { + return autoScaleVmGroup; + } + + public boolean isAutoScaleConfig() { + return this.autoScaleVmGroup != null; + } + + public void setAutoScaleVmGroup(LbAutoScaleVmGroup autoScaleVmGroup) { + this.autoScaleVmGroup = autoScaleVmGroup; + } + + public static class LbCondition { + private final Condition condition; + private final Counter counter; + + public LbCondition(Counter counter, Condition condition) { + this.condition = condition; + this.counter = counter; + } + + public Condition getCondition() { + return condition; + } + + public Counter getCounter() { + return counter; + } + } + + public static class LbAutoScalePolicy { + private final List conditions; + private final AutoScalePolicy policy; + private boolean revoked; + + public LbAutoScalePolicy(AutoScalePolicy policy, List conditions) + { + this.policy = policy; + this.conditions = conditions; + } + + public List getConditions() { + return conditions; + } + + public AutoScalePolicy getPolicy() { + return policy; + } + + public boolean isRevoked() { + return revoked; + } + + public void setRevoked(boolean revoked) { + this.revoked = revoked; + } + } + + public static class LbAutoScaleVmProfile { + AutoScaleVmProfile profile; + private final String autoScaleUserApiKey; + private final String autoScaleUserSecretKey; + private final String csUrl; + private final String zoneId; + private final String domainId; + private final String serviceOfferingId; + private final String templateId; + private final String networkId; + private final String vmName; + + public LbAutoScaleVmProfile(AutoScaleVmProfile profile, String autoScaleUserApiKey, String autoScaleUserSecretKey, String csUrl, String zoneId, String domainId, String serviceOfferingId, String templateId, String vmName, String networkId) { + this.profile = profile; + this.autoScaleUserApiKey = autoScaleUserApiKey; + this.autoScaleUserSecretKey = autoScaleUserSecretKey; + this.csUrl = csUrl; + this.zoneId = zoneId; + this.domainId = domainId; + this.serviceOfferingId = serviceOfferingId; + this.templateId = templateId; + this.vmName = vmName; + this.networkId = networkId; + } + + public AutoScaleVmProfile getProfile() { + return profile; + } + + public String getAutoScaleUserApiKey() { + return autoScaleUserApiKey; + } + + public String getAutoScaleUserSecretKey() { + return autoScaleUserSecretKey; + } + + public String getCsUrl() { + return csUrl; + } + + public String getZoneId() { + return zoneId; + } + + public String getDomainId() { + return domainId; + } + + public String getServiceOfferingId() { + return serviceOfferingId; + } + + public String getTemplateId() { + return templateId; + } + + public String getVmName() { + return vmName; + } + + public String getNetworkId() { + return networkId; + } + } + + public static class LbAutoScaleVmGroup { + AutoScaleVmGroup vmGroup; + private final List policies; + private final LbAutoScaleVmProfile profile; + private final String currentState; + + public LbAutoScaleVmGroup(AutoScaleVmGroup vmGroup, List policies, LbAutoScaleVmProfile profile, String currentState) { + this.vmGroup = vmGroup; + this.policies = policies; + this.profile = profile; + this.currentState = currentState; + } + + public AutoScaleVmGroup getVmGroup() { + return vmGroup; + } + + public List getPolicies() { + return policies; + } + + public LbAutoScaleVmProfile getProfile() { + return profile; + } + + public String getCurrentState() { + return currentState; + } + } + } diff --git a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java index d30195db5b9..4081f6efc2c 100644 --- a/api/src/com/cloud/network/lb/LoadBalancingRulesService.java +++ b/api/src/com/cloud/network/lb/LoadBalancingRulesService.java @@ -18,23 +18,22 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLBStickinessPolicyCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.ListLBStickinessPoliciesCmd; -import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; -import com.cloud.api.commands.ListLoadBalancerRulesCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.*; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.UpdateLoadBalancerRuleCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.StickinessPolicy; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; + public interface LoadBalancingRulesService { /** * Create a load balancer rule from the given ipAddress/port to the given private port - * + * * @param openFirewall * TODO * @param cmd @@ -51,7 +50,7 @@ public interface LoadBalancingRulesService { /** * Create a stickiness policy to a load balancer from the given stickiness method name and parameters in * (name,value) pairs. - * + * * @param cmd * the command specifying the stickiness method name, params (name,value pairs), policy name and * description. @@ -61,7 +60,7 @@ public interface LoadBalancingRulesService { public StickinessPolicy createLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws NetworkRuleConflictException; public boolean applyLBStickinessPolicy(CreateLBStickinessPolicyCmd cmd) throws ResourceUnavailableException; - + boolean deleteLBStickinessPolicy(long stickinessPolicyId, boolean apply); /** * Assign a virtual machine, or list of virtual machines, to a load balancer. @@ -75,7 +74,7 @@ public interface LoadBalancingRulesService { /** * List instances that have either been applied to a load balancer or are eligible to be assigned to a load * balancer. - * + * * @param cmd * @return list of vm instances that have been or can be applied to a load balancer */ @@ -83,18 +82,18 @@ public interface LoadBalancingRulesService { /** * List load balancer rules based on the given criteria - * + * * @param cmd * the command that specifies the criteria to use for listing load balancers. Load balancers can be * listed * by id, name, public ip, and vm instance id * @return list of load balancers that match the criteria */ - List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd); + Pair, Integer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd); /** * List stickiness policies based on the given criteria - * + * * @param cmd * the command specifies the load balancing rule id. * @return list of stickiness policies that match the criteria. diff --git a/api/src/com/cloud/network/rules/FirewallRule.java b/api/src/com/cloud/network/rules/FirewallRule.java index f2a83af29fe..042665cdcf9 100644 --- a/api/src/com/cloud/network/rules/FirewallRule.java +++ b/api/src/com/cloud/network/rules/FirewallRule.java @@ -18,9 +18,11 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface FirewallRule extends ControlledEntity { +public interface FirewallRule extends ControlledEntity, Identity, InternalIdentity { enum Purpose { Firewall, PortForwarding, @@ -29,39 +31,34 @@ public interface FirewallRule extends ControlledEntity { StaticNat, NetworkACL, } - + enum FirewallRuleType { - System, // The pre-defined rules created by admin, in the system wide - User; // the rules created by user, to a specific ip + System, // The pre-defined rules created by admin, in the system wide + User // the rules created by user, to a specific ip } - + enum State { Staged, // Rule been created but has never got through network rule conflict detection. Rules in this state can not be sent to network elements. Add, // Add means the rule has been created and has gone through network rule conflict detection. Active, // Rule has been sent to the network elements and reported to be active. Revoke // Revoke means this rule has been revoked. If this rule has been sent to the network elements, the rule will be deleted from database. } - + enum TrafficType { Ingress, Egress } - - /** - * @return database id. - */ - long getId(); - + /** * @return external id. */ String getXid(); - + /** * @return first port of the source port range. */ Integer getSourcePortStart(); - + /** * @return last port of the source prot range. If this is null, that means only one port is mapped. */ @@ -71,21 +68,21 @@ public interface FirewallRule extends ControlledEntity { * @return protocol to open these ports for. */ String getProtocol(); - + Purpose getPurpose(); - + State getState(); - + long getNetworkId(); - + Long getSourceIpAddressId(); Integer getIcmpCode(); Integer getIcmpType(); - + List getSourceCidrList(); - + Long getRelated(); FirewallRuleType getType(); diff --git a/api/src/com/cloud/network/rules/LbStickinessMethod.java b/api/src/com/cloud/network/rules/LbStickinessMethod.java index 5f0abe8aaf6..c71b19e3a86 100644 --- a/api/src/com/cloud/network/rules/LbStickinessMethod.java +++ b/api/src/com/cloud/network/rules/LbStickinessMethod.java @@ -24,14 +24,14 @@ import com.google.gson.annotations.SerializedName; public class LbStickinessMethod { public static class StickinessMethodType { private String _name; - + public static final StickinessMethodType LBCookieBased = new StickinessMethodType("LbCookie"); public static final StickinessMethodType AppCookieBased = new StickinessMethodType("AppCookie"); public static final StickinessMethodType SourceBased = new StickinessMethodType("SourceBased"); public StickinessMethodType(String name) { _name = name; } - + public String getName() { return _name; } @@ -40,13 +40,13 @@ public class LbStickinessMethod { public class LbStickinessMethodParam { @SerializedName("paramname") private String _paramName; - + @SerializedName("required") private Boolean _required; - + @SerializedName("isflag") private Boolean _isFlag; - + @SerializedName("description") private String _description; @@ -65,7 +65,7 @@ public class LbStickinessMethod { public void setParamName(String paramName) { this._paramName = paramName; } - + public Boolean getIsflag() { return _isFlag; } @@ -73,7 +73,7 @@ public class LbStickinessMethod { public void setIsflag(Boolean isFlag) { this._isFlag = isFlag; } - + public Boolean getRequired() { return _required; } @@ -94,10 +94,10 @@ public class LbStickinessMethod { @SerializedName("methodname") private String _methodName; - + @SerializedName("paramlist") private List _paramList; - + @SerializedName("description") private String _description; @@ -118,7 +118,7 @@ public class LbStickinessMethod { public String getMethodName() { return _methodName; } - + public List getParamList() { return _paramList; } diff --git a/api/src/com/cloud/network/rules/LoadBalancer.java b/api/src/com/cloud/network/rules/LoadBalancer.java index 9c67f29cc6b..ab6085aceb7 100644 --- a/api/src/com/cloud/network/rules/LoadBalancer.java +++ b/api/src/com/cloud/network/rules/LoadBalancer.java @@ -17,7 +17,7 @@ package com.cloud.network.rules; /** - * Definition for a LoadBalancer + * Definition for a LoadBalancer */ public interface LoadBalancer extends FirewallRule { @@ -26,9 +26,9 @@ public interface LoadBalancer extends FirewallRule { String getDescription(); int getDefaultPortStart(); - + int getDefaultPortEnd(); String getAlgorithm(); - + } diff --git a/api/src/com/cloud/network/rules/PortForwardingRule.java b/api/src/com/cloud/network/rules/PortForwardingRule.java index 6ac6f4521f9..c353e9bc3d4 100644 --- a/api/src/com/cloud/network/rules/PortForwardingRule.java +++ b/api/src/com/cloud/network/rules/PortForwardingRule.java @@ -26,26 +26,26 @@ public interface PortForwardingRule extends FirewallRule { * @return destination ip address. */ Ip getDestinationIpAddress(); - - + + /** * updates the destination ip address. */ void setDestinationIpAddress(Ip destinationIpAddress); - + /** * @return start of destination port. */ int getDestinationPortStart(); - + /** * @return end of destination port range */ int getDestinationPortEnd(); - + /** * @return destination ip address. */ - long getVirtualMachineId(); - + long getVirtualMachineId(); + } diff --git a/api/src/com/cloud/network/rules/RulesService.java b/api/src/com/cloud/network/rules/RulesService.java index 9dd602bc330..80c96d558c4 100644 --- a/api/src/com/cloud/network/rules/RulesService.java +++ b/api/src/com/cloud/network/rules/RulesService.java @@ -18,19 +18,20 @@ package com.cloud.network.rules; import java.util.List; -import com.cloud.api.commands.ListPortForwardingRulesCmd; +import org.apache.cloudstack.api.command.user.firewall.ListPortForwardingRulesCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; +import com.cloud.utils.Pair; public interface RulesService { - List searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll); + Pair, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll); /** * Creates a port forwarding rule between two ip addresses or between * an ip address and a virtual machine. - * + * * @param rule * rule to be created. * @param vmId @@ -45,7 +46,7 @@ public interface RulesService { /** * Revokes a port forwarding rule - * + * * @param ruleId * the id of the rule to revoke. * @param caller @@ -55,12 +56,12 @@ public interface RulesService { /** * List port forwarding rules assigned to an ip address - * + * * @param cmd * the command object holding the criteria for listing port forwarding rules (the ipAddress) * @return list of port forwarding rules on the given address, empty list if no rules exist */ - public List listPortForwardingRules(ListPortForwardingRulesCmd cmd); + public Pair, Integer> listPortForwardingRules(ListPortForwardingRulesCmd cmd); boolean applyPortForwardingRules(long ipAdddressId, Account caller) throws ResourceUnavailableException; diff --git a/api/src/com/cloud/network/rules/StaticNat.java b/api/src/com/cloud/network/rules/StaticNat.java index bf29ab4bf9c..390a0dbaedc 100644 --- a/api/src/com/cloud/network/rules/StaticNat.java +++ b/api/src/com/cloud/network/rules/StaticNat.java @@ -18,13 +18,13 @@ package com.cloud.network.rules; public interface StaticNat{ - + long getAccountId(); - + long getDomainId(); - + long getNetworkId(); - + long getSourceIpAddressId(); String getDestIpAddress(); diff --git a/api/src/com/cloud/network/rules/StaticNatRule.java b/api/src/com/cloud/network/rules/StaticNatRule.java index 601cd6afb9e..839430a6b8c 100644 --- a/api/src/com/cloud/network/rules/StaticNatRule.java +++ b/api/src/com/cloud/network/rules/StaticNatRule.java @@ -16,31 +16,7 @@ // under the License. package com.cloud.network.rules; -import com.cloud.acl.ControlledEntity; - -public interface StaticNatRule extends ControlledEntity, FirewallRule { - - long getId(); - - String getXid(); - - String getProtocol(); - - Integer getSourcePortStart(); - - Integer getSourcePortEnd(); - - Purpose getPurpose(); - - State getState(); - - long getAccountId(); - - long getDomainId(); - - long getNetworkId(); - - Long getSourceIpAddressId(); +public interface StaticNatRule extends FirewallRule { String getDestIpAddress(); -} +} \ No newline at end of file diff --git a/api/src/com/cloud/network/rules/StickinessPolicy.java b/api/src/com/cloud/network/rules/StickinessPolicy.java index 49c2e60c493..e23ff828f74 100644 --- a/api/src/com/cloud/network/rules/StickinessPolicy.java +++ b/api/src/com/cloud/network/rules/StickinessPolicy.java @@ -19,12 +19,12 @@ package com.cloud.network.rules; import java.util.List; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** */ -public interface StickinessPolicy { - - public long getId(); +public interface StickinessPolicy extends InternalIdentity, Identity { public long getLoadBalancerId(); @@ -38,5 +38,4 @@ public interface StickinessPolicy { public List> getParams(); /* get params in Map format */ - public String getUuid(); } diff --git a/api/src/com/cloud/network/security/SecurityGroup.java b/api/src/com/cloud/network/security/SecurityGroup.java index 68467407f3d..3ac0e7cea62 100644 --- a/api/src/com/cloud/network/security/SecurityGroup.java +++ b/api/src/com/cloud/network/security/SecurityGroup.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.network.security; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityGroup extends ControlledEntity { - long getId(); +//FIXME: Annotation @doc("") +public interface SecurityGroup extends ControlledEntity, InternalIdentity, Identity { String getName(); diff --git a/api/src/com/cloud/network/security/SecurityGroupRules.java b/api/src/com/cloud/network/security/SecurityGroupRules.java index 37287f0c76b..0b575e10d56 100644 --- a/api/src/com/cloud/network/security/SecurityGroupRules.java +++ b/api/src/com/cloud/network/security/SecurityGroupRules.java @@ -16,9 +16,9 @@ // under the License. package com.cloud.network.security; import com.cloud.network.security.SecurityRule.SecurityRuleType; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityGroupRules { - long getId(); +public interface SecurityGroupRules extends InternalIdentity { String getName(); @@ -39,6 +39,6 @@ public interface SecurityGroupRules { Long getAllowedNetworkId(); String getAllowedSourceIpCidr(); - + SecurityRuleType getRuleType(); } diff --git a/api/src/com/cloud/network/security/SecurityGroupService.java b/api/src/com/cloud/network/security/SecurityGroupService.java index bace6bbcd26..741f179db50 100644 --- a/api/src/com/cloud/network/security/SecurityGroupService.java +++ b/api/src/com/cloud/network/security/SecurityGroupService.java @@ -18,13 +18,8 @@ package com.cloud.network.security; import java.util.List; -import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; -import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd; -import com.cloud.api.commands.CreateSecurityGroupCmd; -import com.cloud.api.commands.DeleteSecurityGroupCmd; -import com.cloud.api.commands.ListSecurityGroupsCmd; -import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; -import com.cloud.api.commands.RevokeSecurityGroupEgressCmd; +import org.apache.cloudstack.api.command.user.securitygroup.*; + import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceInUseException; @@ -38,18 +33,12 @@ public interface SecurityGroupService { public SecurityGroup createSecurityGroup(CreateSecurityGroupCmd command) throws PermissionDeniedException, InvalidParameterValueException; boolean revokeSecurityGroupIngress(RevokeSecurityGroupIngressCmd cmd); boolean revokeSecurityGroupEgress(RevokeSecurityGroupEgressCmd cmd); - + boolean deleteSecurityGroup(DeleteSecurityGroupCmd cmd) throws ResourceInUseException; - /** - * Search for security groups and associated ingress rules for the given account, domain, group name, and/or keyword. - * The search terms are specified in the search criteria. - * @return the list of security groups and associated ingress rules - */ - public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException; public List authorizeSecurityGroupIngress(AuthorizeSecurityGroupIngressCmd cmd); - + public List authorizeSecurityGroupEgress(AuthorizeSecurityGroupEgressCmd cmd); } diff --git a/api/src/com/cloud/network/security/SecurityRule.java b/api/src/com/cloud/network/security/SecurityRule.java index 401283aba4b..bd4192d614c 100644 --- a/api/src/com/cloud/network/security/SecurityRule.java +++ b/api/src/com/cloud/network/security/SecurityRule.java @@ -17,34 +17,35 @@ package com.cloud.network.security; import com.cloud.async.AsyncInstanceCreateStatus; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SecurityRule { +public interface SecurityRule extends Identity, InternalIdentity { public static class SecurityRuleType { public static final SecurityRuleType IngressRule = new SecurityRuleType("ingress"); public static final SecurityRuleType EgressRule = new SecurityRuleType("egress"); - + public SecurityRuleType(String type) { this._type = type; } - + public String getType(){ return _type; } private String _type; } - long getId(); long getSecurityGroupId(); int getStartPort(); int getEndPort(); - + String getType(); - + SecurityRuleType getRuleType(); - + String getProtocol(); AsyncInstanceCreateStatus getCreateStatus(); @@ -52,7 +53,4 @@ public interface SecurityRule { Long getAllowedNetworkId(); String getAllowedSourceIpCidr(); - - String getUuid(); - } diff --git a/api/src/com/cloud/network/vpc/PrivateGateway.java b/api/src/com/cloud/network/vpc/PrivateGateway.java index 82672a6ef12..2f346852e30 100644 --- a/api/src/com/cloud/network/vpc/PrivateGateway.java +++ b/api/src/com/cloud/network/vpc/PrivateGateway.java @@ -16,6 +16,6 @@ // under the License. package com.cloud.network.vpc; -public interface PrivateGateway extends VpcGateway{ +public interface PrivateGateway extends VpcGateway { long getPhysicalNetworkId(); } diff --git a/api/src/com/cloud/network/vpc/PrivateIp.java b/api/src/com/cloud/network/vpc/PrivateIp.java index 992a87ca475..857fc226f30 100644 --- a/api/src/com/cloud/network/vpc/PrivateIp.java +++ b/api/src/com/cloud/network/vpc/PrivateIp.java @@ -42,7 +42,7 @@ public interface PrivateIp { * @return */ String getMacAddress(); - + long getNetworkId(); } diff --git a/api/src/com/cloud/network/vpc/StaticRoute.java b/api/src/com/cloud/network/vpc/StaticRoute.java index 56b34cbaa86..ccdbec899b8 100644 --- a/api/src/com/cloud/network/vpc/StaticRoute.java +++ b/api/src/com/cloud/network/vpc/StaticRoute.java @@ -16,9 +16,11 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface StaticRoute extends ControlledEntity{ +public interface StaticRoute extends ControlledEntity, Identity, InternalIdentity { enum State { Staged, // route been created but has never got through network rule conflict detection. Routes in this state can not be sent to VPC virtual router. Add, // Add means the route has been created and has gone through network rule conflict detection. @@ -45,11 +47,4 @@ public interface StaticRoute extends ControlledEntity{ * @return */ Long getVpcId(); - - /** - * @return - */ - long getId(); - - } diff --git a/api/src/com/cloud/network/vpc/StaticRouteProfile.java b/api/src/com/cloud/network/vpc/StaticRouteProfile.java index 73d0a84f8b7..656355590f3 100644 --- a/api/src/com/cloud/network/vpc/StaticRouteProfile.java +++ b/api/src/com/cloud/network/vpc/StaticRouteProfile.java @@ -16,8 +16,11 @@ // under the License. package com.cloud.network.vpc; -public class StaticRouteProfile implements StaticRoute{ +import org.apache.cloudstack.api.InternalIdentity; + +public class StaticRouteProfile implements StaticRoute { private long id; + private String uuid; private String targetCidr; private long accountId; private long domainId; @@ -28,10 +31,11 @@ public class StaticRouteProfile implements StaticRoute{ String gateway; String netmask; String ipAddress; - + public StaticRouteProfile(StaticRoute staticRoute, VpcGateway gateway) { this.id = staticRoute.getId(); + this.uuid = staticRoute.getUuid(); this.targetCidr = staticRoute.getCidr(); this.accountId = staticRoute.getAccountId(); this.domainId = staticRoute.getDomainId(); @@ -79,10 +83,16 @@ public class StaticRouteProfile implements StaticRoute{ return id; } + + @Override + public String getUuid() { + return uuid; + } + public String getVlanTag() { return vlanTag; } - + public String getIp4Address() { return ipAddress; } @@ -94,5 +104,5 @@ public class StaticRouteProfile implements StaticRoute{ public String getNetmask() { return netmask; } - + } diff --git a/api/src/com/cloud/network/vpc/Vpc.java b/api/src/com/cloud/network/vpc/Vpc.java index c9f52ff999f..9365e56dd82 100644 --- a/api/src/com/cloud/network/vpc/Vpc.java +++ b/api/src/com/cloud/network/vpc/Vpc.java @@ -16,23 +16,21 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Vpc extends ControlledEntity{ +public interface Vpc extends ControlledEntity, Identity, InternalIdentity { public enum State { Enabled, Inactive } - + public static final String _supportedProviders = Network.Provider.VPCVirtualRouter.getName(); boolean readyToUse(); - long getId(); - - String getUuid(); - String getName(); long getZoneId(); @@ -42,11 +40,11 @@ public interface Vpc extends ControlledEntity{ State getState(); long getVpcOfferingId(); - + String getDisplayText(); String getNetworkDomain(); boolean isRestartRequired(); - + } diff --git a/api/src/com/cloud/network/vpc/VpcGateway.java b/api/src/com/cloud/network/vpc/VpcGateway.java index c972c35c3fb..17566160ec3 100644 --- a/api/src/com/cloud/network/vpc/VpcGateway.java +++ b/api/src/com/cloud/network/vpc/VpcGateway.java @@ -16,23 +16,22 @@ // under the License. package com.cloud.network.vpc; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VpcGateway extends Identity, ControlledEntity { +public interface VpcGateway extends Identity, ControlledEntity, InternalIdentity { public enum Type { Private, Public, Vpn } - + public enum State { Creating, Ready, Deleting } - - long getId(); /** * @return diff --git a/api/src/com/cloud/network/vpc/VpcOffering.java b/api/src/com/cloud/network/vpc/VpcOffering.java index 10c1d2aca96..1acfcd21418 100644 --- a/api/src/com/cloud/network/vpc/VpcOffering.java +++ b/api/src/com/cloud/network/vpc/VpcOffering.java @@ -16,18 +16,17 @@ // under the License. package com.cloud.network.vpc; -public interface VpcOffering { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface VpcOffering extends InternalIdentity, Identity { public enum State { Disabled, Enabled } - + public static final String defaultVPCOfferingName = "Default VPC offering"; - long getId(); - - String getUuid(); - String getName(); String getUniqueName(); @@ -35,7 +34,7 @@ public interface VpcOffering { String getDisplayText(); State getState(); - + boolean isDefault(); /** diff --git a/api/src/com/cloud/network/vpc/VpcService.java b/api/src/com/cloud/network/vpc/VpcService.java index 7d8de553897..68e062c7d79 100644 --- a/api/src/com/cloud/network/vpc/VpcService.java +++ b/api/src/com/cloud/network/vpc/VpcService.java @@ -20,8 +20,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -34,22 +34,23 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.user.Account; import com.cloud.user.User; +import com.cloud.utils.Pair; public interface VpcService { - + public VpcOffering getVpcOffering(long vpcOfferingId); - + public VpcOffering createVpcOffering(String name, String displayText, List supportedServices); - + public Vpc getVpc(long vpcId); - + public Vpc getActiveVpc(long vpcId); - + public List getVpcNetworks(long vpcId); - + Map> getVpcOffSvcProvidersMap(long vpcOffId); - - List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, + + List listVpcOfferings(Long id, String name, String displayText, List supportedServicesStr, Boolean isDefault, String keyword, String state, Long startIndex, Long pageSizeVal); /** @@ -84,9 +85,9 @@ public interface VpcService { /** * @param vpcId * @return - * @throws InsufficientCapacityException - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws InsufficientCapacityException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ public boolean deleteVpc(long vpcId) throws ConcurrentOperationException, ResourceUnavailableException; @@ -119,22 +120,22 @@ public interface VpcService { * @param vpc * @return */ - public List listVpcs(Long id, String vpcName, String displayText, + public List listVpcs(Long id, String vpcName, String displayText, List supportedServicesStr, String cidr, Long vpcOffId, String state, String accountName, Long domainId, - String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, + String keyword, Long startIndex, Long pageSizeVal, Long zoneId, Boolean isRecursive, Boolean listAll, Boolean restartRequired, Map tags, Long projectId); /** * @param vpcId * @param destroyOnFailure TODO * @return - * @throws InsufficientCapacityException - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws InsufficientCapacityException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ - boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException, + boolean startVpc(long vpcId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + /** * @param vpcId * @return @@ -146,10 +147,10 @@ public interface VpcService { /** * @param id * @return - * @throws InsufficientCapacityException + * @throws InsufficientCapacityException */ boolean restartVpc(long id) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException; - + PrivateGateway getVpcPrivateGateway(long id); /** @@ -161,28 +162,28 @@ public interface VpcService { * @param netmask * @param gatewayOwnerId * @return - * @throws InsufficientCapacityException - * @throws ConcurrentOperationException - * @throws ResourceAllocationException + * @throws InsufficientCapacityException + * @throws ConcurrentOperationException + * @throws ResourceAllocationException */ - public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, - String gateway, String netmask, long gatewayOwnerId) throws ResourceAllocationException, + public PrivateGateway createVpcPrivateGateway(long vpcId, Long physicalNetworkId, String vlan, String ipAddress, + String gateway, String netmask, long gatewayOwnerId) throws ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException; /** * @param gatewayId * @param destroyOnFailure TODO * @return - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ public PrivateGateway applyVpcPrivateGateway(long gatewayId, boolean destroyOnFailure) throws ConcurrentOperationException, ResourceUnavailableException; - + /** * @param id * @return - * @throws ResourceUnavailableException - * @throws ConcurrentOperationException + * @throws ResourceUnavailableException + * @throws ConcurrentOperationException */ boolean deleteVpcPrivateGateway(long gatewayId) throws ConcurrentOperationException, ResourceUnavailableException; @@ -190,7 +191,7 @@ public interface VpcService { * @param listPrivateGatewaysCmd * @return */ - public List listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd); + public Pair, Integer> listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd); /** * @param routeId @@ -201,14 +202,14 @@ public interface VpcService { /** * @param vpcId * @return - * @throws ResourceUnavailableException + * @throws ResourceUnavailableException */ public boolean applyStaticRoutes(long vpcId) throws ResourceUnavailableException; /** * @param routeId * @return TODO - * @throws ResourceUnavailableException + * @throws ResourceUnavailableException */ public boolean revokeStaticRoute(long routeId) throws ResourceUnavailableException; @@ -223,14 +224,14 @@ public interface VpcService { * @param listStaticRoutesCmd * @return */ - public List listStaticRoutes(ListStaticRoutesCmd cmd); + public Pair, Integer> listStaticRoutes(ListStaticRoutesCmd cmd); /** * @param id * @return */ VpcGateway getVpcGateway(long id); - + /** * @param ipId * @param vpcId @@ -242,7 +243,7 @@ public interface VpcService { */ IpAddress associateIPToVpc(long ipId, long vpcId) throws ResourceAllocationException, ResourceUnavailableException, InsufficientAddressCapacityException, ConcurrentOperationException; - - public Network updateVpcGuestNetwork(long networkId, String name, String displayText, Account callerAccount, + + public Network updateVpcGuestNetwork(long networkId, String name, String displayText, Account callerAccount, User callerUser, String domainSuffix, Long ntwkOffId, Boolean changeCidr); } diff --git a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java index b2fb34b6831..81599a0c3c9 100644 --- a/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java +++ b/api/src/com/cloud/network/vpn/RemoteAccessVpnService.java @@ -18,30 +18,32 @@ package com.cloud.network.vpn; import java.util.List; -import com.cloud.api.commands.ListRemoteAccessVpnsCmd; -import com.cloud.api.commands.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.VpnUser; +import com.cloud.user.Account; +import com.cloud.utils.Pair; public interface RemoteAccessVpnService { - RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId) + RemoteAccessVpn createRemoteAccessVpn(long vpnServerAddressId, String ipRange, boolean openFirewall, long networkId) throws NetworkRuleConflictException; - void destroyRemoteAccessVpn(long vpnServerAddressId) throws ResourceUnavailableException; + void destroyRemoteAccessVpn(long vpnServerAddressId, Account caller) throws ResourceUnavailableException; RemoteAccessVpn startRemoteAccessVpn(long vpnServerAddressId, boolean openFirewall) throws ResourceUnavailableException; VpnUser addVpnUser(long vpnOwnerId, String userName, String password); - boolean removeVpnUser(long vpnOwnerId, String userName); + boolean removeVpnUser(long vpnOwnerId, String userName, Account caller); List listVpnUsers(long vpnOwnerId, String userName); boolean applyVpnUsers(long vpnOwnerId, String userName); - - List searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd); - List searchForVpnUsers(ListVpnUsersCmd cmd); - + + Pair, Integer> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd); + Pair, Integer> searchForVpnUsers(ListVpnUsersCmd cmd); + List listRemoteAccessVpns(long networkId); - + RemoteAccessVpn getRemoteAccessVpn(long vpnId); } diff --git a/api/src/com/cloud/network/vpn/Site2SiteVpnService.java b/api/src/com/cloud/network/vpn/Site2SiteVpnService.java index 0e98b9e8786..7ac567774d8 100644 --- a/api/src/com/cloud/network/vpn/Site2SiteVpnService.java +++ b/api/src/com/cloud/network/vpn/Site2SiteVpnService.java @@ -18,23 +18,23 @@ package com.cloud.network.vpn; import java.util.List; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.*; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ResetVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IpAddress; import com.cloud.network.Site2SiteCustomerGateway; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; +import com.cloud.utils.Pair; public interface Site2SiteVpnService { Site2SiteVpnGateway createVpnGateway(CreateVpnGatewayCmd cmd); @@ -46,8 +46,8 @@ public interface Site2SiteVpnService { boolean deleteVpnGateway(DeleteVpnGatewayCmd deleteVpnGatewayCmd); boolean deleteVpnConnection(DeleteVpnConnectionCmd deleteVpnConnectionCmd) throws ResourceUnavailableException; Site2SiteVpnConnection resetVpnConnection(ResetVpnConnectionCmd resetVpnConnectionCmd) throws ResourceUnavailableException; - List searchForCustomerGateways(ListVpnCustomerGatewaysCmd listVpnCustomerGatewaysCmd); - List searchForVpnGateways(ListVpnGatewaysCmd listVpnGatewaysCmd); - List searchForVpnConnections(ListVpnConnectionsCmd listVpnConnectionsCmd); + Pair, Integer> searchForCustomerGateways(ListVpnCustomerGatewaysCmd listVpnCustomerGatewaysCmd); + Pair, Integer> searchForVpnGateways(ListVpnGatewaysCmd listVpnGatewaysCmd); + Pair, Integer> searchForVpnConnections(ListVpnConnectionsCmd listVpnConnectionsCmd); Site2SiteCustomerGateway updateCustomerGateway(UpdateVpnCustomerGatewayCmd updateVpnCustomerGatewayCmd); } diff --git a/api/src/com/cloud/offering/DiskOffering.java b/api/src/com/cloud/offering/DiskOffering.java index a937c6d789d..9a48f4bb655 100644 --- a/api/src/com/cloud/offering/DiskOffering.java +++ b/api/src/com/cloud/offering/DiskOffering.java @@ -16,15 +16,18 @@ // under the License. package com.cloud.offering; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; /** * Represents a disk offering that specifies what the end user needs in * the disk offering. - * + * */ -public interface DiskOffering { - long getId(); +public interface DiskOffering extends InfrastructureEntity, Identity, InternalIdentity { String getUniqueName(); diff --git a/api/src/com/cloud/offering/NetworkOffering.java b/api/src/com/cloud/offering/NetworkOffering.java index a514ccf17f4..b69ad886eaa 100644 --- a/api/src/com/cloud/offering/NetworkOffering.java +++ b/api/src/com/cloud/offering/NetworkOffering.java @@ -18,12 +18,15 @@ package com.cloud.offering; import com.cloud.network.Network.GuestType; import com.cloud.network.Networks.TrafficType; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Describes network offering - * + * */ -public interface NetworkOffering { +public interface NetworkOffering extends InfrastructureEntity, InternalIdentity, Identity { public enum Availability { Required, @@ -40,7 +43,7 @@ public interface NetworkOffering { public final static String SystemManagementNetwork = "System-Management-Network"; public final static String SystemStorageNetwork = "System-Storage-Network"; public final static String SystemPrivateGatewayNetworkOffering = "System-Private-Gateway-Network-Offering"; - + public final static String DefaultSharedNetworkOfferingWithSGService = "DefaultSharedNetworkOfferingWithSGService"; public final static String DefaultIsolatedNetworkOfferingWithSourceNatService = "DefaultIsolatedNetworkOfferingWithSourceNatService"; public final static String OvsIsolatedNetworkOfferingWithSourceNatService = "OvsIsolatedNetworkOfferingWithSourceNatService"; @@ -50,9 +53,6 @@ public interface NetworkOffering { public final static String DefaultIsolatedNetworkOfferingForVpcNetworks = "DefaultIsolatedNetworkOfferingForVpcNetworks"; public final static String DefaultIsolatedNetworkOfferingForVpcNetworksNoLB = "DefaultIsolatedNetworkOfferingForVpcNetworksNoLB"; - - long getId(); - /** * @return name for the network offering. */ @@ -105,8 +105,11 @@ public interface NetworkOffering { boolean getElasticIp(); + boolean getAssociatePublicIP(); + boolean getElasticLb(); boolean getSpecifyIpRanges(); + boolean isInline(); } diff --git a/api/src/com/cloud/offering/OfferingManager.java b/api/src/com/cloud/offering/OfferingManager.java index 3cc68dbcc6f..576679d04c9 100644 --- a/api/src/com/cloud/offering/OfferingManager.java +++ b/api/src/com/cloud/offering/OfferingManager.java @@ -18,30 +18,30 @@ package com.cloud.offering; /** * An administrator can create, delete, enable, and disable offerings. - * + * * There are three types of offerings: * - Disk Offering - package of disk performance and size specification. * - Network Offering - package of services available on a network. - * + * */ public interface OfferingManager { /** * Creates a service offering. - * + * * @return ServiceOffering */ ServiceOffering createServiceOffering(); /** * Creates a disk offering. - * + * * @return DiskOffering */ DiskOffering createDiskOffering(); /** * Creates a network offering. - * + * * @return NetworkOffering */ NetworkOffering createNetworkOffering(); diff --git a/api/src/com/cloud/offering/ServiceOffering.java b/api/src/com/cloud/offering/ServiceOffering.java index 1a1acb2ea5a..b13346cfb83 100755 --- a/api/src/com/cloud/offering/ServiceOffering.java +++ b/api/src/com/cloud/offering/ServiceOffering.java @@ -16,12 +16,16 @@ // under the License. package com.cloud.offering; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; /** * offered. */ -public interface ServiceOffering { +public interface ServiceOffering extends InfrastructureEntity, InternalIdentity, Identity { public static final String consoleProxyDefaultOffUniqueName = "Cloud.com-ConsoleProxy"; public static final String ssvmDefaultOffUniqueName = "Cloud.com-SecondaryStorage"; public static final String routerDefaultOffUniqueName = "Cloud.Com-SoftwareRouter"; @@ -32,8 +36,6 @@ public interface ServiceOffering { shared } - long getId(); - String getDisplayText(); Date getCreated(); diff --git a/api/src/com/cloud/org/Cluster.java b/api/src/com/cloud/org/Cluster.java index 7fe64af59a5..cb72a70b817 100644 --- a/api/src/com/cloud/org/Cluster.java +++ b/api/src/com/cloud/org/Cluster.java @@ -18,15 +18,15 @@ package com.cloud.org; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Managed.ManagedState; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Cluster extends Grouping { +public interface Cluster extends Grouping, InternalIdentity, Identity { public static enum ClusterType { CloudManaged, ExternalManaged; }; - long getId(); - String getName(); long getDataCenterId(); diff --git a/api/src/com/cloud/projects/Project.java b/api/src/com/cloud/projects/Project.java index f67506e4997..78d52574f28 100644 --- a/api/src/com/cloud/projects/Project.java +++ b/api/src/com/cloud/projects/Project.java @@ -18,10 +18,11 @@ package com.cloud.projects; import java.util.Date; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.domain.PartOf; +import org.apache.cloudstack.api.InternalIdentity; -public interface Project extends PartOf, Identity { +public interface Project extends PartOf, Identity, InternalIdentity { public enum State { Active, Disabled, Suspended } diff --git a/api/src/com/cloud/projects/ProjectInvitation.java b/api/src/com/cloud/projects/ProjectInvitation.java index 6dca006645b..ee282229034 100644 --- a/api/src/com/cloud/projects/ProjectInvitation.java +++ b/api/src/com/cloud/projects/ProjectInvitation.java @@ -18,15 +18,15 @@ package com.cloud.projects; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface ProjectInvitation extends ControlledEntity { +public interface ProjectInvitation extends ControlledEntity, Identity, InternalIdentity { public enum State { Pending, Completed, Expired, Declined } - long getId(); - long getProjectId(); Long getForAccountId(); diff --git a/api/src/com/cloud/projects/ProjectService.java b/api/src/com/cloud/projects/ProjectService.java index 5834f1ce712..01975188dd9 100644 --- a/api/src/com/cloud/projects/ProjectService.java +++ b/api/src/com/cloud/projects/ProjectService.java @@ -16,9 +16,6 @@ // under the License. package com.cloud.projects; -import java.util.List; -import java.util.Map; - import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; @@ -28,7 +25,7 @@ import com.cloud.user.Account; public interface ProjectService { /** * Creates a new project - * + * * @param name * - project name * @param displayText @@ -44,7 +41,7 @@ public interface ProjectService { /** * Deletes a project - * + * * @param id * - project id * @return true if the project was deleted successfully, false otherwise @@ -53,16 +50,13 @@ public interface ProjectService { /** * Gets a project by id - * + * * @param id * - project id * @return project object */ Project getProject(long id); - List listProjects(Long id, String name, String displayText, String state, String accountName, - Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, boolean isRecursive, Map tags); - ProjectAccount assignAccountToProject(Project project, long accountId, Role accountRole); Account getProjectOwner(long projectId); @@ -79,10 +73,7 @@ public interface ProjectService { boolean deleteAccountFromProject(long projectId, String accountName); - List listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal); - List listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, - boolean listAll); boolean updateInvitation(long projectId, String accountName, String token, boolean accept); @@ -93,6 +84,6 @@ public interface ProjectService { Project enableProject(long projectId); boolean deleteProjectInvitation(long invitationId); - + Project findByProjectAccountIdIncludingRemoved(long projectAccountId); } diff --git a/api/src/com/cloud/resource/ResourceService.java b/api/src/com/cloud/resource/ResourceService.java index 10654539bb6..b9db8e734d9 100755 --- a/api/src/com/cloud/resource/ResourceService.java +++ b/api/src/com/cloud/resource/ResourceService.java @@ -18,34 +18,33 @@ package com.cloud.resource; import java.util.List; -import com.cloud.api.commands.AddClusterCmd; -import com.cloud.api.commands.AddHostCmd; -import com.cloud.api.commands.AddSecondaryStorageCmd; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.CancelMaintenanceCmd; -import com.cloud.api.commands.DeleteClusterCmd; -import com.cloud.api.commands.ListSwiftsCmd; -import com.cloud.api.commands.PrepareForMaintenanceCmd; -import com.cloud.api.commands.ReconnectHostCmd; -import com.cloud.api.commands.UpdateHostCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; +import org.apache.cloudstack.api.command.admin.cluster.DeleteClusterCmd; +import org.apache.cloudstack.api.command.admin.host.*; +import org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; +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.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; public interface ResourceService { /** * Updates a host - * + * * @param cmd * - the command specifying hostId * @return hostObject - * @throws NoTransitionException + * @throws NoTransitionException */ Host updateHost(UpdateHostCmd cmd) throws NoTransitionException; @@ -56,7 +55,7 @@ public interface ResourceService { /** * We will automatically create a cloud.com cluster to attach to the external cluster and return a hyper host to perform * host related operation within the cluster - * + * * @param cmd * @return * @throws IllegalArgumentException @@ -76,12 +75,12 @@ public interface ResourceService { /** * Deletes a host - * + * * @param hostId * TODO * @param isForced * TODO - * + * * @param true if deleted, false otherwise */ boolean deleteHost(long hostId, boolean isForced, boolean isForceDeleteStorage); @@ -93,8 +92,13 @@ public interface ResourceService { Cluster getCluster(Long clusterId); 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/serializer/Param.java b/api/src/com/cloud/serializer/Param.java index 005188216c6..02deb6f1c1f 100644 --- a/api/src/com/cloud/serializer/Param.java +++ b/api/src/com/cloud/serializer/Param.java @@ -31,6 +31,6 @@ public @interface Param { Class responseObject() default Object.class; boolean includeInApiDoc() default true; - + String since() default ""; } diff --git a/api/src/com/cloud/server/ManagementService.java b/api/src/com/cloud/server/ManagementService.java index 8dcc3983599..e547954fff3 100755 --- a/api/src/com/cloud/server/ManagementService.java +++ b/api/src/com/cloud/server/ManagementService.java @@ -23,53 +23,47 @@ import java.util.Map; import java.util.Set; import com.cloud.alert.Alert; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.CreateSSHKeyPairCmd; -import com.cloud.api.commands.DeleteSSHKeyPairCmd; -import com.cloud.api.commands.DestroySystemVmCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.commands.GetVMPasswordCmd; -import com.cloud.api.commands.ListAlertsCmd; -import com.cloud.api.commands.ListAsyncJobsCmd; -import com.cloud.api.commands.ListCapabilitiesCmd; -import com.cloud.api.commands.ListCapacityCmd; -import com.cloud.api.commands.ListCfgsByCmd; -import com.cloud.api.commands.ListClustersCmd; -import com.cloud.api.commands.ListDiskOfferingsCmd; -import com.cloud.api.commands.ListEventsCmd; -import com.cloud.api.commands.ListGuestOsCategoriesCmd; -import com.cloud.api.commands.ListGuestOsCmd; -import com.cloud.api.commands.ListHostsCmd; -import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListPodsByCmd; -import com.cloud.api.commands.ListPublicIpAddressesCmd; -import com.cloud.api.commands.ListRoutersCmd; -import com.cloud.api.commands.ListSSHKeyPairsCmd; -import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListStoragePoolsCmd; -import com.cloud.api.commands.ListSystemVMsCmd; -import com.cloud.api.commands.ListTemplatesCmd; -import com.cloud.api.commands.ListVMGroupsCmd; -import com.cloud.api.commands.ListVlanIpRangesCmd; -import com.cloud.api.commands.ListZonesByCmd; -import com.cloud.api.commands.RebootSystemVmCmd; -import com.cloud.api.commands.RegisterSSHKeyPairCmd; -import com.cloud.api.commands.StopSystemVmCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; -import com.cloud.api.commands.UpdateIsoCmd; -import com.cloud.api.commands.UpdateTemplateCmd; -import com.cloud.api.commands.UpdateVMGroupCmd; -import com.cloud.api.commands.UpgradeSystemVMCmd; -import com.cloud.api.commands.UploadCustomCertificateCmd; -import com.cloud.async.AsyncJob; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; +import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; +import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.*; +import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; +import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; +import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; +import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; +import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; +import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; +import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; +import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; +import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; +import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; +import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; + import com.cloud.capacity.Capacity; import com.cloud.configuration.Configuration; import com.cloud.dc.DataCenter; import com.cloud.dc.Pod; import com.cloud.dc.Vlan; import com.cloud.domain.Domain; -import com.cloud.event.Event; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InternalErrorException; import com.cloud.exception.PermissionDeniedException; @@ -78,7 +72,6 @@ import com.cloud.host.Host; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.network.IpAddress; -import com.cloud.network.router.VirtualRouter; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.org.Cluster; @@ -94,7 +87,7 @@ import com.cloud.vm.VirtualMachine.Type; /** * Hopefully this is temporary. - * + * */ public interface ManagementService { static final String Name = "management-server"; @@ -104,21 +97,21 @@ public interface ManagementService { * for the * account that invokes the API. By specifying available=true all zones which the account can access. By specifying * available=false the zones where the account has virtual machine instances will be returned. - * + * * @return a list of DataCenters */ List listDataCenters(ListZonesByCmd cmd); /** * returns the a map of the names/values in the configuraton table - * + * * @return map of configuration name/values */ - List searchForConfigurations(ListCfgsByCmd c); + Pair, Integer> searchForConfigurations(ListCfgsByCmd c); /** * Searches for Service Offerings by the specified search criteria Can search by: "name" - * + * * @param cmd * @return List of ServiceOfferings */ @@ -126,12 +119,12 @@ public interface ManagementService { /** * Searches for Clusters by the specified search criteria - * + * * @param c * @return */ - List searchForClusters(ListClustersCmd c); - + Pair, Integer> searchForClusters(ListClustersCmd c); + /** * Searches for Clusters by the specified zone Id. * @param zoneId @@ -141,24 +134,16 @@ public interface ManagementService { /** * Searches for Pods by the specified search criteria Can search by: pod name and/or zone name - * + * * @param cmd * @return List of Pods */ - List searchForPods(ListPodsByCmd cmd); + Pair, Integer> searchForPods(ListPodsByCmd cmd); - /** - * Searches for servers by the specified search criteria Can search by: "name", "type", "state", "dataCenterId", - * "podId" - * - * @param cmd - * @return List of Hosts - */ - List searchForServers(ListHostsCmd cmd); /** * Creates a new template - * + * * @param cmd * @return updated template */ @@ -166,49 +151,31 @@ public interface ManagementService { VirtualMachineTemplate updateTemplate(UpdateTemplateCmd cmd); - /** - * Obtains a list of events by the specified search criteria. Can search by: "username", "type", "level", - * "startDate", - * "endDate" - * - * @param c - * @return List of Events. - */ - List searchForEvents(ListEventsCmd c); - /** - * Obtains a list of routers by the specified search criteria. Can search by: "userId", "name", "state", - * "dataCenterId", - * "podId", "hostId" - * - * @param cmd - * @return List of DomainRouters. - */ - List searchForRouters(ListRoutersCmd cmd); /** * Obtains a list of IP Addresses by the specified search criteria. Can search by: "userId", "dataCenterId", * "address" - * + * * @param cmd * the command that wraps the search criteria * @return List of IPAddresses */ - List searchForIPAddresses(ListPublicIpAddressesCmd cmd); + Pair, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd); /** * Obtains a list of all guest OS. - * + * * @return list of GuestOS */ - List listGuestOSByCriteria(ListGuestOsCmd cmd); + Pair, Integer> listGuestOSByCriteria(ListGuestOsCmd cmd); /** * Obtains a list of all guest OS categories. - * + * * @return list of GuestOSCategories */ - List listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd); + Pair, Integer> listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd); VirtualMachine stopSystemVM(StopSystemVmCmd cmd) throws ResourceUnavailableException, ConcurrentOperationException; @@ -217,12 +184,12 @@ public interface ManagementService { VirtualMachine rebootSystemVM(RebootSystemVmCmd cmd); VirtualMachine destroySystemVM(DestroySystemVmCmd cmd); - + VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd); /** * update an existing domain - * + * * @param cmd * - the command containing domainId and new domainName * @return Domain object if the command succeeded @@ -231,15 +198,15 @@ public interface ManagementService { /** * Searches for alerts - * + * * @param c * @return List of Alerts */ - List searchForAlerts(ListAlertsCmd cmd); + Pair, Integer> searchForAlerts(ListAlertsCmd cmd); /** * list all the capacity rows in capacity operations table - * + * * @param cmd * @return List of capacities */ @@ -247,7 +214,7 @@ public interface ManagementService { /** * List ISOs that match the specified criteria. - * + * * @param cmd * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, * and zoneId @@ -258,7 +225,7 @@ public interface ManagementService { /** * List templates that match the specified criteria. - * + * * @param cmd * The command that wraps the (optional) templateId, name, keyword, templateFilter, bootable, account, * and zoneId @@ -269,7 +236,7 @@ public interface ManagementService { /** * Search for disk offerings based on search criteria - * + * * @param cmd * the command containing the criteria to use for searching for disk offerings * @return a list of disk offerings that match the given criteria @@ -278,25 +245,25 @@ public interface ManagementService { /** * List storage pools that match the given criteria - * + * * @param cmd * the command that wraps the search criteria (zone, pod, name, IP address, path, and cluster id) * @return a list of storage pools that match the given criteria */ - List searchForStoragePools(ListStoragePoolsCmd cmd); + Pair, Integer> searchForStoragePools(ListStoragePoolsCmd cmd); /** * List system VMs by the given search criteria - * + * * @param cmd * the command that wraps the search criteria (host, name, state, type, zone, pod, and/or id) * @return the list of system vms that match the given criteria */ - List searchForSystemVm(ListSystemVMsCmd cmd); + Pair, Integer> searchForSystemVm(ListSystemVMsCmd cmd); /** * Returns back a SHA1 signed response - * + * * @param userId * -- id for the user * @return -- ArrayList of @@ -307,13 +274,12 @@ public interface ManagementService { InstanceGroup updateVmGroup(UpdateVMGroupCmd cmd); - List searchForVmGroups(ListVMGroupsCmd cmd); Map listCapabilities(ListCapabilitiesCmd cmd); /** * Extracts the volume to a particular location. - * + * * @param cmd * the command specifying url (where the volume needs to be extracted to), zoneId (zone where the volume * exists), @@ -321,23 +287,23 @@ public interface ManagementService { * @throws URISyntaxException * @throws InternalErrorException * @throws PermissionDeniedException - * + * */ Long extractVolume(ExtractVolumeCmd cmd) throws URISyntaxException; /** * return an array of available hypervisors - * + * * @param zoneId * TODO - * + * * @return an array of available hypervisors in the cloud */ List getHypervisors(Long zoneId); /** * This method uploads a custom cert to the db, and patches every cpvm with it on the current ms - * + * * @param cmd * -- upload certificate cmd * @return -- returns a string on success @@ -350,24 +316,15 @@ public interface ManagementService { /** * Searches for vlan by the specified search criteria Can search by: "id", "vlan", "name", "zoneID" - * + * * @param cmd * @return List of Vlans */ - List searchForVlans(ListVlanIpRangesCmd cmd); - - /** - * Search for async jobs by account and/or startDate - * - * @param cmd - * the command specifying the account and start date parameters - * @return the list of async jobs that match the criteria - */ - List searchForAsyncJobs(ListAsyncJobsCmd cmd); + Pair, Integer> searchForVlans(ListVlanIpRangesCmd cmd); /** * Generates a random password that will be used (initially) by newly created and started virtual machines - * + * * @return a random password */ String generateRandomPassword(); @@ -378,16 +335,16 @@ public interface ManagementService { /** * Search registered key pairs for the logged in user. - * + * * @param cmd * The api command class. * @return The list of key pairs found. */ - List listSSHKeyPairs(ListSSHKeyPairsCmd cmd); + Pair, Integer> listSSHKeyPairs(ListSSHKeyPairsCmd cmd); /** * Registers a key pair for a given public key. - * + * * @param cmd * The api command class. * @return A VO with the key pair name and a finger print for the public key. @@ -396,7 +353,7 @@ public interface ManagementService { /** * Creates a new - * + * * @param cmd * The api command class. * @return A VO containing the key pair name, finger print for the public key and the private key material of the @@ -406,7 +363,7 @@ public interface ManagementService { /** * Deletes a key pair by name. - * + * * @param cmd * The api command class. * @return True on success. False otherwise. @@ -415,7 +372,7 @@ public interface ManagementService { /** * Finds and returns an encrypted password for a VM. - * + * * @param cmd * The api command class. * @return The encrypted password. @@ -428,7 +385,7 @@ public interface ManagementService { * List hosts for migrating the given VM. The API returns list of all hosts in the VM's cluster minus the current * host and * also a list of hosts that seem to have enough CPU and RAM capacity to host this VM. - * + * * @param Long * vmId * Id of The VM to migrate @@ -439,13 +396,13 @@ public interface ManagementService { String[] listEventTypes(); - List listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal); + Pair, Integer> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal); HypervisorCapabilities updateHypervisorCapabilities(Long id, Long maxGuestsLimit, Boolean securityGroupEnabled); /** * list all the top consumed resources across different capacity types - * + * * @param cmd * @return List of capacities */ diff --git a/api/src/com/cloud/server/ResourceTag.java b/api/src/com/cloud/server/ResourceTag.java index 117e721b893..5ec9f0171cc 100644 --- a/api/src/com/cloud/server/ResourceTag.java +++ b/api/src/com/cloud/server/ResourceTag.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.server; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface ResourceTag extends ControlledEntity, Identity, InternalIdentity { -public interface ResourceTag extends ControlledEntity{ - public enum TaggedResourceType { UserVm, Template, @@ -38,11 +40,6 @@ public interface ResourceTag extends ControlledEntity{ StaticRoute } - /** - * @return - */ - long getId(); - /** * @return */ diff --git a/api/src/com/cloud/server/TaggedResourceService.java b/api/src/com/cloud/server/TaggedResourceService.java index dd1b1c6b4ee..92a4300db0a 100644 --- a/api/src/com/cloud/server/TaggedResourceService.java +++ b/api/src/com/cloud/server/TaggedResourceService.java @@ -19,11 +19,10 @@ package com.cloud.server; import java.util.List; import java.util.Map; -import com.cloud.api.commands.ListTagsCmd; import com.cloud.server.ResourceTag.TaggedResourceType; public interface TaggedResourceService { - + TaggedResourceType getResourceType (String resourceTypeStr); /** @@ -42,11 +41,6 @@ public interface TaggedResourceService { */ String getUuid(String resourceId, TaggedResourceType resourceType); - /** - * @param listTagsCmd - * @return - */ - List listTags(ListTagsCmd listTagsCmd); /** * @param resourceIds @@ -55,6 +49,6 @@ public interface TaggedResourceService { * @return */ boolean deleteTags(List resourceIds, TaggedResourceType resourceType, Map tags); - + List listByResourceTypeAndId(TaggedResourceType type, long resourceId); } diff --git a/api/src/com/cloud/storage/GuestOS.java b/api/src/com/cloud/storage/GuestOS.java index b9727db6612..437cd37d1ab 100644 --- a/api/src/com/cloud/storage/GuestOS.java +++ b/api/src/com/cloud/storage/GuestOS.java @@ -16,9 +16,10 @@ // under the License. package com.cloud.storage; -public interface GuestOS { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; - long getId(); +public interface GuestOS extends InternalIdentity, Identity { String getName(); diff --git a/api/src/com/cloud/storage/GuestOsCategory.java b/api/src/com/cloud/storage/GuestOsCategory.java index 42320d9eec8..c28d7d6bf77 100644 --- a/api/src/com/cloud/storage/GuestOsCategory.java +++ b/api/src/com/cloud/storage/GuestOsCategory.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.storage; -public interface GuestOsCategory { +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface GuestOsCategory extends Identity, InternalIdentity { // Used by OS preference, 'None' for no OS preference public static final String CATEGORY_NONE ="None"; - long getId(); String getName(); diff --git a/api/src/com/cloud/storage/S3.java b/api/src/com/cloud/storage/S3.java new file mode 100644 index 00000000000..708e280ca5b --- /dev/null +++ b/api/src/com/cloud/storage/S3.java @@ -0,0 +1,49 @@ +/* + * 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 org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +import java.util.Date; + +public interface S3 extends InternalIdentity, Identity { + + 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/com/cloud/storage/Snapshot.java b/api/src/com/cloud/storage/Snapshot.java index d169e64f116..60c0c281c7f 100644 --- a/api/src/com/cloud/storage/Snapshot.java +++ b/api/src/com/cloud/storage/Snapshot.java @@ -18,10 +18,12 @@ package com.cloud.storage; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Snapshot extends ControlledEntity { +public interface Snapshot extends ControlledEntity, Identity, InternalIdentity { public enum Type { MANUAL, RECURRING, @@ -69,9 +71,6 @@ public interface Snapshot extends ControlledEntity { public static final long MANUAL_POLICY_ID = 0L; - long getId(); - - @Override long getAccountId(); long getVolumeId(); diff --git a/api/src/com/cloud/storage/StoragePool.java b/api/src/com/cloud/storage/StoragePool.java index 4b7fe3a5c1a..79f3c46683b 100644 --- a/api/src/com/cloud/storage/StoragePool.java +++ b/api/src/com/cloud/storage/StoragePool.java @@ -19,25 +19,16 @@ package com.cloud.storage; import java.util.Date; import com.cloud.storage.Storage.StoragePoolType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface StoragePool { - - /** - * @return id of the pool. - */ - long getId(); +public interface StoragePool extends Identity, InternalIdentity { /** * @return name of the pool. */ String getName(); - /*** - * - * @return unique identifier - */ - String getUuid(); - /** * @return the type of pool. */ diff --git a/api/src/com/cloud/storage/StorageService.java b/api/src/com/cloud/storage/StorageService.java index 4fb3b55f057..ff8ec13e33b 100644 --- a/api/src/com/cloud/storage/StorageService.java +++ b/api/src/com/cloud/storage/StorageService.java @@ -17,26 +17,24 @@ package com.cloud.storage; import java.net.UnknownHostException; -import java.util.List; -import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; -import com.cloud.api.commands.CreateStoragePoolCmd; -import com.cloud.api.commands.CreateVolumeCmd; -import com.cloud.api.commands.DeletePoolCmd; -import com.cloud.api.commands.ListVolumesCmd; -import com.cloud.api.commands.UpdateStoragePoolCmd; -import com.cloud.api.commands.UploadVolumeCmd; +import org.apache.cloudstack.api.command.admin.storage.*; +import org.apache.cloudstack.api.command.admin.storage.CancelPrimaryStorageMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.storage.UpdateStoragePoolCmd; +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; public interface StorageService{ /** * Create StoragePool based on uri - * + * * @param cmd * the command object that specifies the zone, cluster/pod, URI, details, etc. to use to create the * storage pool. @@ -47,12 +45,12 @@ public interface StorageService{ * @throws ResourceUnavailableException * TODO */ - StoragePool createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, + StoragePool createPool(CreateStoragePoolCmd cmd) throws ResourceInUseException, IllegalArgumentException, UnknownHostException, ResourceUnavailableException; /** * Creates the database object for a volume based on the given criteria - * + * * @param cmd * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, * name) @@ -63,7 +61,7 @@ public interface StorageService{ /** * Creates the volume based on the given criteria - * + * * @param cmd * the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot, * name) @@ -71,11 +69,10 @@ public interface StorageService{ */ Volume createVolume(CreateVolumeCmd cmd); - boolean deleteVolume(long volumeId) throws ConcurrentOperationException; /** * Delete the storage pool - * + * * @param cmd * - the command specifying poolId * @return success or failure @@ -84,7 +81,7 @@ public interface StorageService{ /** * Enable maintenance for primary storage - * + * * @param cmd * - the command specifying primaryStorageId * @return the primary storage pool @@ -93,19 +90,19 @@ public interface StorageService{ * @throws InsufficientCapacityException * TODO */ - public StoragePool preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, + public StoragePool preparePrimaryStorageForMaintenance(Long primaryStorageId) throws ResourceUnavailableException, InsufficientCapacityException; /** * Complete maintenance for primary storage - * + * * @param cmd * - the command specifying primaryStorageId * @return the primary storage pool * @throws ResourceUnavailableException * TODO */ - public StoragePool cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) + public StoragePool cancelPrimaryStorageForMaintenance(CancelPrimaryStorageMaintenanceCmd cmd) throws ResourceUnavailableException; public StoragePool updateStoragePool(UpdateStoragePoolCmd cmd) throws IllegalArgumentException; @@ -114,15 +111,16 @@ public interface StorageService{ Volume migrateVolume(Long volumeId, Long storagePoolId) throws ConcurrentOperationException; - List searchForVolumes(ListVolumesCmd cmd); /** * Uploads the volume to secondary storage - * - * @param UploadVolumeCmd cmd - * + * + * @param UploadVolumeCmd cmd + * * @return Volume object */ Volume uploadVolume(UploadVolumeCmd cmd) throws ResourceAllocationException; + boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException; + } diff --git a/api/src/com/cloud/storage/StorageStats.java b/api/src/com/cloud/storage/StorageStats.java index fe21c44b702..c30e1de10f6 100755 --- a/api/src/com/cloud/storage/StorageStats.java +++ b/api/src/com/cloud/storage/StorageStats.java @@ -22,7 +22,7 @@ public interface StorageStats { */ public long getByteUsed(); /** - * @return bytes capacity of the storage server + * @return bytes capacity of the storage server */ public long getCapacityBytes(); } diff --git a/api/src/com/cloud/storage/Swift.java b/api/src/com/cloud/storage/Swift.java index 54a670cefe1..9cd3a34cd59 100644 --- a/api/src/com/cloud/storage/Swift.java +++ b/api/src/com/cloud/storage/Swift.java @@ -17,10 +17,13 @@ package com.cloud.storage; import com.cloud.agent.api.to.SwiftTO; +import org.apache.cloudstack.api.InternalIdentity; -public interface Swift { +public interface Swift extends InternalIdentity { public long getId(); + public String getUuid(); + public String getUrl(); public String getAccount(); diff --git a/api/src/com/cloud/storage/Upload.java b/api/src/com/cloud/storage/Upload.java index d73a9d8604c..a20faf1dc34 100755 --- a/api/src/com/cloud/storage/Upload.java +++ b/api/src/com/cloud/storage/Upload.java @@ -16,9 +16,12 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface Upload { +public interface Upload extends InternalIdentity, Identity { public static enum Status { UNKNOWN, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, NOT_COPIED, COPY_IN_PROGRESS, COPY_ERROR, COPY_COMPLETE, DOWNLOAD_URL_CREATED, DOWNLOAD_URL_NOT_CREATED, ERROR @@ -34,8 +37,6 @@ public interface Upload { long getHostId(); - long getId(); - Date getCreated(); Date getLastUpdated(); diff --git a/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java b/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java index 6c49352073b..a404ea4b6e3 100644 --- a/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java +++ b/api/src/com/cloud/storage/VMTemplateStorageResourceAssoc.java @@ -16,9 +16,12 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface VMTemplateStorageResourceAssoc { +public interface VMTemplateStorageResourceAssoc extends InternalIdentity { public static enum Status { UNKNOWN, DOWNLOAD_ERROR, NOT_DOWNLOADED, DOWNLOAD_IN_PROGRESS, DOWNLOADED, ABANDONED, UPLOADED, NOT_UPLOADED, UPLOAD_ERROR, UPLOAD_IN_PROGRESS, CREATING, CREATED } @@ -35,8 +38,6 @@ public interface VMTemplateStorageResourceAssoc { void setDownloadState(Status downloadState); - long getId(); - Date getCreated(); Date getLastUpdated(); diff --git a/api/src/com/cloud/storage/Volume.java b/api/src/com/cloud/storage/Volume.java index 18edbc3a1b3..e241851dbf5 100755 --- a/api/src/com/cloud/storage/Volume.java +++ b/api/src/com/cloud/storage/Volume.java @@ -18,12 +18,14 @@ package com.cloud.storage; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.template.BasedOn; import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Volume extends ControlledEntity, BasedOn, StateObject { +public interface Volume extends ControlledEntity, Identity, InternalIdentity, BasedOn, StateObject { enum Type { UNKNOWN, ROOT, SWAP, DATADISK, ISO }; @@ -94,8 +96,6 @@ public interface Volume extends ControlledEntity, BasedOn, StateObject listSnapshots(ListSnapshotsCmd cmd); + Pair, Integer> listSnapshots(ListSnapshotsCmd cmd); /** * Delete specified snapshot from the specified. If no other policies are assigned it calls destroy snapshot. This * will be * used for manual snapshots too. - * + * * @param snapshotId * TODO */ @@ -54,7 +56,7 @@ public interface SnapshotService { * Creates a policy with specified schedule. maxSnaps specifies the number of most recent snapshots that are to be * retained. * If the number of snapshots go beyond maxSnaps the oldest snapshot is deleted - * + * * @param cmd * the command that * @param policyOwner @@ -65,7 +67,7 @@ public interface SnapshotService { /** * Get the recurring snapshots scheduled for this volume currently along with the time at which they are scheduled - * + * * @param cmd * the command wrapping the volumeId (volume for which the snapshots are required) and policyId (to show * snapshots for only this policy). @@ -75,7 +77,7 @@ public interface SnapshotService { /** * list all snapshot policies assigned to the specified volume - * + * * @param cmd * the command that specifies the volume criteria * @return list of snapshot policies @@ -88,13 +90,19 @@ public interface SnapshotService { /** * Create a snapshot of a volume - * + * * @param snapshotOwner * TODO * @param cmd * the API command wrapping the parameters for creating the snapshot (mainly volumeId) - * + * * @return the Snapshot that was created */ Snapshot createSnapshot(Long volumeId, Long policyId, Long snapshotId, Account snapshotOwner); + + /** + * @param vol + * @return + */ + Long getHostIdForSnapshotOperation(Volume vol); } diff --git a/api/src/com/cloud/template/BasedOn.java b/api/src/com/cloud/template/BasedOn.java index 25d409e7679..a95c69729bf 100644 --- a/api/src/com/cloud/template/BasedOn.java +++ b/api/src/com/cloud/template/BasedOn.java @@ -20,7 +20,7 @@ package com.cloud.template; * BasedOn is implemented by all objects that are based on a certain template. */ public interface BasedOn { - + /** * @return the template id that the volume is based on. */ diff --git a/api/src/com/cloud/template/TemplateService.java b/api/src/com/cloud/template/TemplateService.java index e45f43d5f9c..93e8a2576b6 100755 --- a/api/src/com/cloud/template/TemplateService.java +++ b/api/src/com/cloud/template/TemplateService.java @@ -19,15 +19,15 @@ package com.cloud.template; import java.net.URISyntaxException; import java.util.List; -import com.cloud.api.commands.CopyTemplateCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.*; +import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd; +import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.exception.InternalErrorException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.StorageUnavailableException; @@ -48,7 +48,7 @@ public interface TemplateService { /** * Deletes a template - * + * * @param cmd * - the command specifying templateId */ @@ -56,7 +56,7 @@ public interface TemplateService { /** * Deletes a template - * + * * @param cmd * - the command specifying isoId * @return true if deletion is successful, false otherwise @@ -65,7 +65,7 @@ public interface TemplateService { /** * Extracts an ISO - * + * * @param cmd * - the command specifying the mode and id of the ISO * @return extractId. @@ -74,7 +74,7 @@ public interface TemplateService { /** * Extracts a Template - * + * * @param cmd * - the command specifying the mode and id of the template * @return extractId @@ -83,7 +83,7 @@ public interface TemplateService { VirtualMachineTemplate getTemplate(long templateId); - List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd); + List listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd); - boolean updateTemplateOrIsoPermissions(UpdateTemplateOrIsoPermissionsCmd cmd); + boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd); } diff --git a/api/src/com/cloud/template/VirtualMachineTemplate.java b/api/src/com/cloud/template/VirtualMachineTemplate.java index 00a41434d13..23f5a3cc9e9 100755 --- a/api/src/com/cloud/template/VirtualMachineTemplate.java +++ b/api/src/com/cloud/template/VirtualMachineTemplate.java @@ -19,12 +19,14 @@ package com.cloud.template; import java.util.Date; import java.util.Map; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface VirtualMachineTemplate extends ControlledEntity { +public interface VirtualMachineTemplate extends ControlledEntity, Identity, InternalIdentity { public static enum BootloaderType { PyGrub, HVM, External, CD @@ -40,11 +42,6 @@ public interface VirtualMachineTemplate extends ControlledEntity { all // all templates (only usable by admins) } - /** - * @return id. - */ - long getId(); - boolean isFeatured(); /** diff --git a/api/src/com/cloud/user/Account.java b/api/src/com/cloud/user/Account.java index 18f585be75b..a5b3e87156d 100755 --- a/api/src/com/cloud/user/Account.java +++ b/api/src/com/cloud/user/Account.java @@ -18,9 +18,11 @@ package com.cloud.user; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface Account extends ControlledEntity { +public interface Account extends ControlledEntity, InternalIdentity, Identity { public enum Type { Normal, Admin, @@ -35,6 +37,7 @@ public interface Account extends ControlledEntity { locked } + public static final short ACCOUNT_TYPE_NORMAL = 0; public static final short ACCOUNT_TYPE_ADMIN = 1; public static final short ACCOUNT_TYPE_DOMAIN_ADMIN = 2; @@ -48,8 +51,6 @@ public interface Account extends ControlledEntity { public static final long ACCOUNT_ID_SYSTEM = 1; - public long getId(); - public String getAccountName(); public short getType(); @@ -59,6 +60,7 @@ public interface Account extends ControlledEntity { public Date getRemoved(); public String getNetworkDomain(); - + public Long getDefaultZoneId(); + } diff --git a/api/src/com/cloud/user/AccountService.java b/api/src/com/cloud/user/AccountService.java index 53383d3c7c3..ce16f5ee063 100755 --- a/api/src/com/cloud/user/AccountService.java +++ b/api/src/com/cloud/user/AccountService.java @@ -19,14 +19,14 @@ package com.cloud.user; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; + import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; @@ -37,7 +37,7 @@ public interface AccountService { /** * Creates a new user and account, stores the password as is so encrypted passwords are recommended. - * + * * @param userName * TODO * @param password @@ -58,7 +58,7 @@ public interface AccountService { * TODO * @param networkDomain * TODO - * + * * @return the user if created successfully, null otherwise */ UserAccount createUserAccount(String userName, String password, String firstName, String lastName, String email, String timezone, String accountName, short accountType, Long domainId, String networkDomain, @@ -66,17 +66,17 @@ public interface AccountService { /** * Deletes a user by userId - * + * * @param accountId * - id of the account do delete - * + * * @return true if delete was successful, false otherwise */ boolean deleteUserAccount(long accountId); /** * Disables a user by userId - * + * * @param userId * - the userId * @return UserAccount object @@ -85,7 +85,7 @@ public interface AccountService { /** * Enables a user - * + * * @param userId * - the userId * @return UserAccount object @@ -95,7 +95,7 @@ public interface AccountService { /** * Locks a user by userId. A locked user cannot access the API, but will still have running VMs/IP addresses * allocated/etc. - * + * * @param userId * @return UserAccount object */ @@ -103,7 +103,7 @@ public interface AccountService { /** * Update a user by userId - * + * * @param userId * @return UserAccount object */ @@ -111,7 +111,7 @@ public interface AccountService { /** * Disables an account by accountName and domainId - * + * * @param accountName * TODO * @param domainId @@ -125,7 +125,7 @@ public interface AccountService { /** * Enables an account by accountId - * + * * @param accountName * - the enableAccount command defining the accountId to be deleted. * @param domainId @@ -139,7 +139,7 @@ public interface AccountService { * Locks an account by accountId. A locked account cannot access the API, but will still have running VMs/IP * addresses * allocated/etc. - * + * * @param accountName * - the LockAccount command defining the accountId to be locked. * @param domainId @@ -151,7 +151,7 @@ public interface AccountService { /** * Updates an account name - * + * * @param cmd * - the parameter containing accountId * @return updated account object @@ -191,13 +191,8 @@ public interface AccountService { public String[] createApiKeyAndSecretKey(RegisterCmd cmd); - List searchForAccounts(ListAccountsCmd cmd); - - List searchForUsers(ListUsersCmd cmd) - throws PermissionDeniedException; - UserAccount getUserByApiKey(String apiKey); - + void checkAccess(Account account, Domain domain) throws PermissionDeniedException; void checkAccess(Account account, AccessType accessType, boolean sameOwner, ControlledEntity... entities) throws PermissionDeniedException; diff --git a/api/src/com/cloud/user/DomainService.java b/api/src/com/cloud/user/DomainService.java index 362f87ea0be..6fbe1b9a8db 100644 --- a/api/src/com/cloud/user/DomainService.java +++ b/api/src/com/cloud/user/DomainService.java @@ -18,10 +18,11 @@ package com.cloud.user; import java.util.List; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import com.cloud.domain.Domain; import com.cloud.exception.PermissionDeniedException; +import com.cloud.utils.Pair; public interface DomainService { @@ -31,7 +32,7 @@ public interface DomainService { /** * Return whether a domain is a child domain of a given domain. - * + * * @param parentId * @param childId */ @@ -39,10 +40,10 @@ public interface DomainService { boolean deleteDomain(long domainId, Boolean cleanup); - List searchForDomains(ListDomainsCmd cmd) + Pair, Integer> searchForDomains(ListDomainsCmd cmd) throws PermissionDeniedException; - List searchForDomainChildren(ListDomainChildrenCmd cmd) + Pair, Integer> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException; } diff --git a/api/src/com/cloud/user/ResourceLimitService.java b/api/src/com/cloud/user/ResourceLimitService.java index 98dfc11319a..bec65d5b7e8 100644 --- a/api/src/com/cloud/user/ResourceLimitService.java +++ b/api/src/com/cloud/user/ResourceLimitService.java @@ -28,7 +28,7 @@ public interface ResourceLimitService { /** * Updates an existing resource limit with the specified details. If a limit doesn't exist, will create one. - * + * * @param accountId * TODO * @param domainId @@ -37,14 +37,14 @@ public interface ResourceLimitService { * TODO * @param max * TODO - * + * * @return the updated/created resource limit */ ResourceLimit updateResourceLimit(Long accountId, Long domainId, Integer resourceType, Long max); /** * Updates an existing resource count details for the account/domain - * + * * @param accountId * TODO * @param domainId @@ -57,7 +57,7 @@ public interface ResourceLimitService { /** * Search for resource limits for the given id and/or account and/or type and/or domain. - * + * * @param id * TODO * @param accountId @@ -73,17 +73,27 @@ public interface ResourceLimitService { /** * Finds the resource limit for a specified account and type. If the account has an infinite limit, will check * the account's parent domain, and if that limit is also infinite, will return the ROOT domain's limit. - * + * * @param account * @param type * @return resource limit */ public long findCorrectResourceLimitForAccount(Account account, ResourceType type); + /** + * This call should be used when we have already queried resource limit for an account. This is to handle + * some corner cases where queried limit may be null. + * @param accountType + * @param limit + * @param type + * @return + */ + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type); + /** * Finds the resource limit for a specified domain and type. If the domain has an infinite limit, will check * up the domain hierarchy - * + * * @param account * @param type * @return resource limit @@ -92,7 +102,7 @@ public interface ResourceLimitService { /** * Increments the resource count - * + * * @param accountId * @param type * @param delta @@ -101,7 +111,7 @@ public interface ResourceLimitService { /** * Decrements the resource count - * + * * @param accountId * @param type * @param delta @@ -110,7 +120,7 @@ public interface ResourceLimitService { /** * Checks if a limit has been exceeded for an account - * + * * @param account * @param type * @param count @@ -122,7 +132,7 @@ public interface ResourceLimitService { /** * Gets the count of resources for a resource type and account - * + * * @param account * @param type * @return count of resources diff --git a/api/src/com/cloud/user/SSHKeyPair.java b/api/src/com/cloud/user/SSHKeyPair.java index 494f74f5a7a..aa20c17eb07 100644 --- a/api/src/com/cloud/user/SSHKeyPair.java +++ b/api/src/com/cloud/user/SSHKeyPair.java @@ -16,14 +16,10 @@ // under the License. package com.cloud.user; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.InternalIdentity; -public interface SSHKeyPair extends ControlledEntity { - - /** - * @return The id of the key pair. - */ - public long getId(); +public interface SSHKeyPair extends ControlledEntity, InternalIdentity { /** * @return The given name of the key pair. diff --git a/api/src/com/cloud/user/User.java b/api/src/com/cloud/user/User.java index c625c168d0d..36a7c6543b0 100644 --- a/api/src/com/cloud/user/User.java +++ b/api/src/com/cloud/user/User.java @@ -16,13 +16,17 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface User extends OwnedBy { +public interface User extends OwnedBy, InternalIdentity { public static final long UID_SYSTEM = 1; public long getId(); + public String getUuid(); + public Date getCreated(); public Date getRemoved(); diff --git a/api/src/com/cloud/user/UserAccount.java b/api/src/com/cloud/user/UserAccount.java index 2a6bd4f33e3..c09b5c0fac5 100644 --- a/api/src/com/cloud/user/UserAccount.java +++ b/api/src/com/cloud/user/UserAccount.java @@ -16,10 +16,12 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface UserAccount { - Long getId(); +public interface UserAccount extends InternalIdentity { + long getId(); String getUsername(); diff --git a/api/src/com/cloud/uservm/UserVm.java b/api/src/com/cloud/uservm/UserVm.java index 866d849748d..a587666bc8b 100755 --- a/api/src/com/cloud/uservm/UserVm.java +++ b/api/src/com/cloud/uservm/UserVm.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.uservm; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.vm.VirtualMachine; /** diff --git a/api/src/com/cloud/vm/InstanceGroup.java b/api/src/com/cloud/vm/InstanceGroup.java index 98fac593d9b..6560b4afe81 100644 --- a/api/src/com/cloud/vm/InstanceGroup.java +++ b/api/src/com/cloud/vm/InstanceGroup.java @@ -18,10 +18,11 @@ package com.cloud.vm; import java.util.Date; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; -public interface InstanceGroup extends ControlledEntity { - long getId(); +public interface InstanceGroup extends ControlledEntity, Identity, InternalIdentity { String getName(); diff --git a/api/src/com/cloud/vm/Nic.java b/api/src/com/cloud/vm/Nic.java index 3beff0a5ada..84c0034b430 100644 --- a/api/src/com/cloud/vm/Nic.java +++ b/api/src/com/cloud/vm/Nic.java @@ -25,17 +25,19 @@ import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.Mode; import com.cloud.utils.fsm.FiniteState; import com.cloud.utils.fsm.StateMachine; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; /** * Nic represents one nic on the VM. */ -public interface Nic { +public interface Nic extends Identity, InternalIdentity { enum Event { ReservationRequested, ReleaseRequested, CancelRequested, OperationCompleted, OperationFailed, } public enum State implements FiniteState { - Allocated("Resource is allocated but not reserved"), Reserving("Resource is being reserved right now"), + Allocated("Resource is allocated but not reserved"), Reserving("Resource is being reserved right now"), Reserved("Resource has been reserved."), Releasing("Resource is being released"), Deallocating( "Resource is being deallocated"); @@ -86,11 +88,6 @@ public interface Nic { PlaceHolder, Create, Start, Managed; } - /** - * @return id in the CloudStack database - */ - long getId(); - /** * @return reservation id returned by the allocation source. This can be the String version of the database id if * the diff --git a/api/src/com/cloud/vm/NicProfile.java b/api/src/com/cloud/vm/NicProfile.java index c5ffbeaa502..32e3f212e99 100644 --- a/api/src/com/cloud/vm/NicProfile.java +++ b/api/src/com/cloud/vm/NicProfile.java @@ -24,8 +24,9 @@ import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; import com.cloud.vm.Nic.ReservationStrategy; +import org.apache.cloudstack.api.InternalIdentity; -public class NicProfile { +public class NicProfile implements InternalIdentity { long id; long networkId; BroadcastDomainType broadcastType; @@ -207,7 +208,7 @@ public class NicProfile { return strategy; } - public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, + public NicProfile(Nic nic, Network network, URI broadcastUri, URI isolationUri, Integer networkRate, boolean isSecurityGroupEnabled, String name) { this.id = nic.getId(); this.networkId = network.getId(); diff --git a/api/src/com/cloud/vm/RunningOn.java b/api/src/com/cloud/vm/RunningOn.java index a04e28edc3d..cb642939f3d 100644 --- a/api/src/com/cloud/vm/RunningOn.java +++ b/api/src/com/cloud/vm/RunningOn.java @@ -17,7 +17,7 @@ package com.cloud.vm; /** - * + * */ public interface RunningOn { diff --git a/api/src/com/cloud/vm/UserVmService.java b/api/src/com/cloud/vm/UserVmService.java index 6635657042f..b1ebe10596d 100755 --- a/api/src/com/cloud/vm/UserVmService.java +++ b/api/src/com/cloud/vm/UserVmService.java @@ -21,22 +21,21 @@ import java.util.Map; import javax.naming.InsufficientResourcesException; -import com.cloud.api.commands.AssignVMCmd; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.CreateVMGroupCmd; -import com.cloud.api.commands.DeleteVMGroupCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DestroyVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.ListVMsCmd; -import com.cloud.api.commands.RebootVMCmd; -import com.cloud.api.commands.RecoverVMCmd; -import com.cloud.api.commands.ResetVMPasswordCmd; -import com.cloud.api.commands.RestoreVMCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpdateVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; + import com.cloud.dc.DataCenter; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -58,7 +57,7 @@ import com.cloud.utils.exception.ExecutionException; public interface UserVmService { /** * Destroys one virtual machine - * + * * @param userId * the id of the user performing the action * @param vmId @@ -70,7 +69,7 @@ public interface UserVmService { /** * Destroys one virtual machine - * + * * @param userId * the id of the user performing the action * @param vmId @@ -82,7 +81,7 @@ public interface UserVmService { /** * Resets the password of a virtual machine. - * + * * @param cmd * - the command specifying vmId, password * @return the VM if reset worked successfully, null otherwise @@ -91,7 +90,7 @@ public interface UserVmService { /** * Attaches the specified volume to the specified VM - * + * * @param cmd * - the command specifying volumeId and vmId * @return the Volume object if attach worked successfully. @@ -100,7 +99,7 @@ public interface UserVmService { /** * Detaches the specified volume from the VM it is currently attached to. - * + * * @param cmd * - the command specifying volumeId * @return the Volume object if detach worked successfully. @@ -112,13 +111,13 @@ public interface UserVmService { UserVm rebootVirtualMachine(RebootVMCmd cmd) throws InsufficientCapacityException, ResourceUnavailableException; - UserVm updateVirtualMachine(UpdateVMCmd cmd); + UserVm updateVirtualMachine(UpdateVMCmd cmd) throws ResourceUnavailableException, InsufficientCapacityException; UserVm recoverVirtualMachine(RecoverVMCmd cmd) throws ResourceAllocationException; /** * Create a template database record in preparation for creating a private template. - * + * * @param cmd * the command object that defines the name, display text, snapshot/volume, bits, public/private, etc. * for the @@ -132,7 +131,7 @@ public interface UserVmService { /** * Creates a private template from a snapshot of a VM - * + * * @param cmd * - the command specifying snapshotId, name, description * @return a template if successfully created, null otherwise @@ -141,7 +140,7 @@ public interface UserVmService { /** * Creates a Basic Zone User VM in the database and returns the VM to the caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -188,7 +187,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -204,7 +203,7 @@ public interface UserVmService { /** * Creates a User VM in Advanced Zone (Security Group feature is enabled) in the database and returns the VM to the * caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -253,7 +252,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -270,7 +269,7 @@ public interface UserVmService { /** * Creates a User VM in Advanced Zone (Security Group feature is disabled) in the database and returns the VM to the * caller. - * + * * @param zone * - availability zone for the virtual machine * @param serviceOffering @@ -317,7 +316,7 @@ public interface UserVmService { * - an optional domainId for the virtual machine. If the account parameter is used, domainId must also * be used * @return UserVm object if successful. - * + * * @throws InsufficientCapacityException * if there is insufficient capacity to deploy the VM. * @throws ConcurrentOperationException @@ -332,7 +331,7 @@ public interface UserVmService { /** * Starts the virtual machine created from createVirtualMachine. - * + * * @param cmd * Command to deploy. * @return UserVm object if successful. @@ -347,7 +346,7 @@ public interface UserVmService { /** * Creates a vm group. - * + * * @param name * - name of the group * @param accountId @@ -359,7 +358,7 @@ public interface UserVmService { /** * upgrade the service offering of the virtual machine - * + * * @param cmd * - the command specifying vmId and new serviceOfferingId * @return the vm @@ -370,15 +369,6 @@ public interface UserVmService { void deletePrivateTemplateRecord(Long templateId); - /** - * Obtains a list of virtual machines by the specified search criteria. Can search by: "userId", "name", "state", - * "dataCenterId", "podId", "hostId" - * - * @param cmd - * the API command that wraps the search criteria - * @return List of UserVMs. - */ - List searchForUserVMs(ListVMsCmd cmd); HypervisorType getHypervisorTypeOfUserVM(long vmid); @@ -391,7 +381,7 @@ public interface UserVmService { * Migrate the given VM to the destination host provided. The API returns the migrated VM if migration succeeds. * Only Root * Admin can migrate a VM. - * + * * @param destinationStorage * TODO * @param Long @@ -399,7 +389,7 @@ public interface UserVmService { * vmId of The VM to migrate * @param Host * destinationHost to migrate the VM - * + * * @return VirtualMachine migrated VM * @throws ManagementServerException * in case we get error finding the VM or host or access errors or other internal errors. diff --git a/api/src/com/cloud/vm/VirtualMachine.java b/api/src/com/cloud/vm/VirtualMachine.java index 82ff9370969..9c07cdc4803 100755 --- a/api/src/com/cloud/vm/VirtualMachine.java +++ b/api/src/com/cloud/vm/VirtualMachine.java @@ -19,17 +19,18 @@ package com.cloud.vm; import java.util.Date; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.fsm.StateMachine2; import com.cloud.utils.fsm.StateObject; +import org.apache.cloudstack.api.InternalIdentity; /** * VirtualMachine describes the properties held by a virtual machine * */ -public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, StateObject { +public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, InternalIdentity, StateObject { public enum State { Starting(true, "VM is being started. At this state, you should find host id filled which means it's being started on that host."), @@ -206,11 +207,6 @@ public interface VirtualMachine extends RunningOn, ControlledEntity, Identity, S */ public String getInstanceName(); - /** - * @return the id of this virtual machine. null means the id has not been set. - */ - public long getId(); - /** * @return the host name of the virtual machine. If the user did not * specify the host name when creating the virtual machine then it is diff --git a/api/src/com/cloud/vm/VirtualMachineProfile.java b/api/src/com/cloud/vm/VirtualMachineProfile.java index 57277db32f3..0fab4436807 100644 --- a/api/src/com/cloud/vm/VirtualMachineProfile.java +++ b/api/src/com/cloud/vm/VirtualMachineProfile.java @@ -30,7 +30,7 @@ import com.cloud.user.Account; * VirtualMachineProfile describes one virtual machine. This object * on what the virtual machine profile should look like before it is * actually started on the hypervisor. - * + * * @param * a VirtualMachine */ diff --git a/api/src/org/apache/cloudstack/acl/APIAccessChecker.java b/api/src/org/apache/cloudstack/acl/APIAccessChecker.java new file mode 100644 index 00000000000..3194bd11d17 --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/APIAccessChecker.java @@ -0,0 +1,32 @@ +// 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 org.apache.cloudstack.acl; + +import java.util.Properties; + +import com.cloud.exception.PermissionDeniedException; +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.utils.component.Adapter; + +/** + * APIAccessChecker checks the ownership and access control to API requests + */ +public interface APIAccessChecker extends Adapter { + // Interface for checking access to an API for an user + boolean canAccessAPI(User user, String apiCommandName) throws PermissionDeniedException; +} diff --git a/api/src/com/cloud/acl/ControlledEntity.java b/api/src/org/apache/cloudstack/acl/ControlledEntity.java similarity index 96% rename from api/src/com/cloud/acl/ControlledEntity.java rename to api/src/org/apache/cloudstack/acl/ControlledEntity.java index 190dd41eea4..3e0412623e2 100644 --- a/api/src/com/cloud/acl/ControlledEntity.java +++ b/api/src/org/apache/cloudstack/acl/ControlledEntity.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.acl; +package org.apache.cloudstack.acl; import com.cloud.domain.PartOf; import com.cloud.user.OwnedBy; @@ -22,7 +22,7 @@ import com.cloud.user.OwnedBy; /** * ControlledEntity defines an object for which the access from an * access must inherit this interface. - * + * */ public interface ControlledEntity extends OwnedBy, PartOf { public enum ACLType { diff --git a/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java b/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java new file mode 100644 index 00000000000..451c0c89ede --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/InfrastructureEntity.java @@ -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. +package org.apache.cloudstack.acl; + +public interface InfrastructureEntity { +} diff --git a/api/src/org/apache/cloudstack/acl/Role.java b/api/src/org/apache/cloudstack/acl/Role.java new file mode 100644 index 00000000000..d039a6f95ff --- /dev/null +++ b/api/src/org/apache/cloudstack/acl/Role.java @@ -0,0 +1,33 @@ +// 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 org.apache.cloudstack.acl; + +//metadata - consists of default dynamic roles in CS + any custom roles added by user +public interface Role { + + public static final short ROOT_ADMIN = 0; + public static final short DOMAIN_ADMIN = 1; + public static final short DOMAIN_USER = 2; + public static final short OWNER = 3; + public static final short PARENT_DOMAIN_ADMIN = 4; + public static final short PARENT_DOMAIN_USER = 5; + public static final short CHILD_DOMAIN_ADMIN = 6; + public static final short CHILD_DOMAIN_USER = 7; + + public long getId(); + public short getRoleType(); + } diff --git a/api/src/com/cloud/acl/SecurityChecker.java b/api/src/org/apache/cloudstack/acl/SecurityChecker.java similarity index 98% rename from api/src/com/cloud/acl/SecurityChecker.java rename to api/src/org/apache/cloudstack/acl/SecurityChecker.java index 3f76da97809..3a721fe7fcb 100644 --- a/api/src/com/cloud/acl/SecurityChecker.java +++ b/api/src/org/apache/cloudstack/acl/SecurityChecker.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.acl; +package org.apache.cloudstack.acl; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; @@ -39,7 +39,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the account owns the object. - * + * * @param caller * account to check against. * @param object @@ -52,7 +52,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the user belongs to an account that owns the object. - * + * * @param user * user to check against. * @param object @@ -65,7 +65,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the account can access the object. - * + * * @param caller * account to check against. * @param entity @@ -80,7 +80,7 @@ public interface SecurityChecker extends Adapter { /** * Checks if the user belongs to an account that can access the object. - * + * * @param user * user to check against. * @param entity diff --git a/api/src/com/cloud/api/IdentityMapper.java b/api/src/org/apache/cloudstack/api/ACL.java similarity index 87% rename from api/src/com/cloud/api/IdentityMapper.java rename to api/src/org/apache/cloudstack/api/ACL.java index 4515b805d05..3623d1ac523 100644 --- a/api/src/com/cloud/api/IdentityMapper.java +++ b/api/src/org/apache/cloudstack/api/ACL.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; @@ -24,6 +24,8 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) -public @interface IdentityMapper { - String entityTableName(); +public @interface ACL { + + boolean checkKeyAccess() default false; + boolean checkValueAccess() default false; } diff --git a/api/src/com/cloud/api/Implementation.java b/api/src/org/apache/cloudstack/api/APICommand.java similarity index 92% rename from api/src/com/cloud/api/Implementation.java rename to api/src/org/apache/cloudstack/api/APICommand.java index 6f0b965c3ec..4d024c15a5d 100644 --- a/api/src/com/cloud/api/Implementation.java +++ b/api/src/org/apache/cloudstack/api/APICommand.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.TYPE; @@ -22,13 +22,13 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.cloud.api.response.BaseResponse; - @Retention(RetentionPolicy.RUNTIME) @Target({ TYPE }) -public @interface Implementation { +public @interface APICommand { Class responseObject(); + String name() default ""; + String description() default ""; String usage() default ""; diff --git a/api/src/com/cloud/api/ApiConstants.java b/api/src/org/apache/cloudstack/api/ApiConstants.java old mode 100755 new mode 100644 similarity index 87% rename from api/src/com/cloud/api/ApiConstants.java rename to api/src/org/apache/cloudstack/api/ApiConstants.java index 067ddf73567..6d8400ae6fd --- a/api/src/com/cloud/api/ApiConstants.java +++ b/api/src/org/apache/cloudstack/api/ApiConstants.java @@ -14,7 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; + +import org.omg.CORBA.PUBLIC_MEMBER; public class ApiConstants { public static final String ACCOUNT = "account"; @@ -31,10 +33,10 @@ public class ApiConstants { public static final String BIND_DN = "binddn"; public static final String BIND_PASSWORD = "bindpass"; public static final String CATEGORY = "category"; - public static final String CERTIFICATE = "certificate"; - public static final String PRIVATE_KEY = "privatekey"; - public static final String DOMAIN_SUFFIX = "domainsuffix"; - public static final String DNS_SEARCH_ORDER = "dnssearchorder"; + public static final String CERTIFICATE = "certificate"; + public static final String PRIVATE_KEY = "privatekey"; + public static final String DOMAIN_SUFFIX = "domainsuffix"; + public static final String DNS_SEARCH_ORDER = "dnssearchorder"; public static final String CIDR = "cidr"; public static final String CIDR_LIST = "cidrlist"; public static final String CLEANUP = "cleanup"; @@ -104,7 +106,7 @@ public class ApiConstants { public static final String JOB_STATUS = "jobstatus"; public static final String LASTNAME = "lastname"; public static final String LEVEL = "level"; - public static final String LIMIT_CPU_USE = "limitcpuuse"; + public static final String LIMIT_CPU_USE = "limitcpuuse"; public static final String LOCK = "lock"; public static final String LUN = "lun"; public static final String LBID = "lbruleid"; @@ -137,9 +139,9 @@ public class ApiConstants { public static final String PORTAL = "portal"; public static final String PORT_FORWARDING_SERVICE_ID = "portforwardingserviceid"; public static final String PRIVATE_INTERFACE = "privateinterface"; - public static final String PRIVATE_IP = "privateip"; + public static final String PRIVATE_IP = "privateip"; public static final String PRIVATE_PORT = "privateport"; - public static final String PRIVATE_START_PORT = "privateport"; + public static final String PRIVATE_START_PORT = "privateport"; public static final String PRIVATE_END_PORT = "privateendport"; public static final String PRIVATE_ZONE = "privatezone"; public static final String PROTOCOL = "protocol"; @@ -147,7 +149,7 @@ public class ApiConstants { public static final String PUBLIC_IP_ID = "publicipid"; public static final String PUBLIC_IP = "publicip"; public static final String PUBLIC_PORT = "publicport"; - public static final String PUBLIC_START_PORT = "publicport"; + public static final String PUBLIC_START_PORT = "publicport"; public static final String PUBLIC_END_PORT = "publicendport"; public static final String PUBLIC_ZONE = "publiczone"; public static final String RECEIVED_BYTES = "receivedbytes"; @@ -171,7 +173,7 @@ public class ApiConstants { public static final String SNAPSHOT_ID = "snapshotid"; public static final String SNAPSHOT_POLICY_ID = "snapshotpolicyid"; public static final String SNAPSHOT_TYPE = "snapshottype"; - public static final String SOURCE_ZONE_ID = "sourcezoneid"; + public static final String SOURCE_ZONE_ID = "sourcezoneid"; public static final String START_DATE = "startdate"; public static final String START_IP = "startip"; public static final String START_PORT = "startport"; @@ -243,13 +245,13 @@ public class ApiConstants { public static final String PRIVATE_NETWORK_ID = "privatenetworkid"; public static final String ALLOCATION_STATE = "allocationstate"; public static final String MANAGED_STATE = "managedstate"; - public static final String STORAGE_ID="storageid"; + public static final String STORAGE_ID = "storageid"; public static final String PING_STORAGE_SERVER_IP = "pingstorageserverip"; public static final String PING_DIR = "pingdir"; public static final String TFTP_DIR = "tftpdir"; public static final String PING_CIFS_USERNAME = "pingcifsusername"; public static final String PING_CIFS_PASSWORD = "pingcifspassword"; - public static final String CHECKSUM="checksum"; + public static final String CHECKSUM = "checksum"; public static final String NETWORK_DEVICE_TYPE = "networkdevicetype"; public static final String NETWORK_DEVICE_PARAMETER_LIST = "networkdeviceparameterlist"; public static final String ZONE_TOKEN = "zonetoken"; @@ -265,8 +267,8 @@ public class ApiConstants { public static final String IP_NETWORK_LIST = "iptonetworklist"; public static final String PARAM_LIST = "param"; public static final String FOR_LOAD_BALANCING = "forloadbalancing"; - public static final String KEYBOARD="keyboard"; - public static final String OPEN_FIREWALL="openfirewall"; + public static final String KEYBOARD = "keyboard"; + public static final String OPEN_FIREWALL = "openfirewall"; public static final String TEMPLATE_TAG = "templatetag"; public static final String HYPERVISOR_VERSION = "hypervisorversion"; public static final String MAX_GUESTS_LIMIT = "maxguestslimit"; @@ -303,8 +305,8 @@ public class ApiConstants { public static final String SERVICE_LIST = "servicelist"; public static final String CAN_ENABLE_INDIVIDUAL_SERVICE = "canenableindividualservice"; public static final String SUPPORTED_SERVICES = "supportedservices"; - public static final String NSP_ID= "nspid"; - public static final String ACL_TYPE= "acltype"; + public static final String NSP_ID = "nspid"; + public static final String ACL_TYPE = "acltype"; public static final String SUBDOMAIN_ACCESS = "subdomainaccess"; public static final String LOAD_BALANCER_DEVICE_ID = "lbdeviceid"; public static final String LOAD_BALANCER_DEVICE_NAME = "lbdevicename"; @@ -382,21 +384,56 @@ public class ApiConstants { public static final String NICIRA_NVP_DEVICE_ID = "nvpdeviceid"; 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"; + public static final String AGGR_FUNCTION = "aggrfunction"; + public static final String AGGR_VALUE = "aggrvalue"; + public static final String THRESHOLD = "threshold"; + public static final String RELATIONAL_OPERATOR = "relationaloperator"; + public static final String OTHER_DEPLOY_PARAMS = "otherdeployparams"; + public static final String MIN_MEMBERS = "minmembers"; + public static final String MAX_MEMBERS = "maxmembers"; + public static final String AUTOSCALE_VM_DESTROY_TIME = "destroyvmgraceperiod"; + public static final String VMPROFILE_ID = "vmprofileid"; + public static final String VMGROUP_ID = "vmgroupid"; + public static final String CS_URL = "csurl"; + public static final String SCALEUP_POLICY_IDS = "scaleuppolicyids"; + public static final String SCALEDOWN_POLICY_IDS = "scaledownpolicyids"; + public static final String SCALEUP_POLICIES = "scaleuppolicies"; + public static final String SCALEDOWN_POLICIES = "scaledownpolicies"; + public static final String INTERVAL = "interval"; + public static final String QUIETTIME = "quiettime"; + public static final String ACTION = "action"; + public static final String CONDITION_ID = "conditionid"; + public static final String CONDITION_IDS = "conditionids"; + public static final String COUNTERPARAM_LIST = "counterparam"; + public static final String AUTOSCALE_USER_ID = "autoscaleuserid"; public enum HostDetails { all, capacity, events, stats, min; } - + public enum VMDetails { all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min; } - + public enum LDAPParams { hostname, port, usessl, queryfilter, searchbase, dn, passwd, truststore, truststorepass; - + @Override - public String toString(){ + public String toString() { return "ldap." + name(); } } diff --git a/api/src/com/cloud/api/BaseAsyncCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCmd.java similarity index 94% rename from api/src/com/cloud/api/BaseAsyncCmd.java rename to api/src/org/apache/cloudstack/api/BaseAsyncCmd.java index 2960e4878e9..fd67ed89675 100644 --- a/api/src/com/cloud/api/BaseAsyncCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCmd.java @@ -14,9 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; -import com.cloud.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; import com.cloud.async.AsyncJob; import com.cloud.user.User; import com.cloud.user.UserContext; @@ -25,10 +25,11 @@ import com.cloud.user.UserContext; * queryAsyncJobResult API command. */ public abstract class BaseAsyncCmd extends BaseCmd { + public static final String ipAddressSyncObject = "ipaddress"; public static final String networkSyncObject = "network"; public static final String vpcSyncObject = "vpc"; - + public static final String snapshotHostSyncObject = "snapshothost"; private AsyncJob job; @@ -39,7 +40,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { * For proper tracking of async commands through the system, events must be generated when the command is * scheduled, started, and completed. Commands should specify the type of event so that when the scheduled, * started, and completed events are saved to the events table, they have the proper type information. - * + * * @return a string representing the type of event, e.g. VM.START, VOLUME.CREATE. */ public abstract String getEventType(); @@ -48,7 +49,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { * For proper tracking of async commands through the system, events must be generated when the command is * scheduled, started, and completed. Commands should specify a description for these events so that when * the scheduled, started, and completed events are saved to the events table, they have a meaningful description. - * + * * @return a string representing a description of the event */ public abstract String getEventDescription(); @@ -56,7 +57,8 @@ public abstract class BaseAsyncCmd extends BaseCmd { public ResponseObject getResponse(long jobId) { AsyncJobResponse response = new AsyncJobResponse(); - response.setJobId(jobId); + AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); + response.setJobId(job.getUuid()); response.setResponseName(getCommandName()); return response; } @@ -76,7 +78,7 @@ public abstract class BaseAsyncCmd extends BaseCmd { /** * Async commands that want to be tracked as part of the listXXX commands need to * provide implementations of the two following methods, getInstanceId() and getInstanceType() - * + * * getObjectId() should return the id of the object the async command is executing on * getObjectType() should return a type from the AsyncJob.Type enumeration */ diff --git a/api/src/com/cloud/api/BaseAsyncCreateCmd.java b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java similarity index 88% rename from api/src/com/cloud/api/BaseAsyncCreateCmd.java rename to api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java index 586c9c9e023..ad9f4c6b31f 100644 --- a/api/src/com/cloud/api/BaseAsyncCreateCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseAsyncCreateCmd.java @@ -14,9 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; -import com.cloud.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; + +import com.cloud.async.AsyncJob; import com.cloud.exception.ResourceAllocationException; public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd { @@ -37,7 +39,8 @@ public abstract class BaseAsyncCreateCmd extends BaseAsyncCmd { public String getResponse(long jobId, long objectId, String objectEntityTable) { CreateCmdResponse response = new CreateCmdResponse(); - response.setJobId(jobId); + AsyncJob job = _entityMgr.findById(AsyncJob.class, jobId); + response.setJobId(job.getUuid()); response.setId(objectId); response.setIdEntityTable(objectEntityTable); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/BaseCmd.java b/api/src/org/apache/cloudstack/api/BaseCmd.java old mode 100755 new mode 100644 similarity index 86% rename from api/src/com/cloud/api/BaseCmd.java rename to api/src/org/apache/cloudstack/api/BaseCmd.java index 520d9f8a6a1..fbbee50b578 --- a/api/src/com/cloud/api/BaseCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseCmd.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -26,6 +26,7 @@ import java.util.List; import java.util.Map; import java.util.regex.Pattern; +import org.apache.cloudstack.query.QueryService; import org.apache.log4j.Logger; import com.cloud.configuration.ConfigurationService; @@ -42,6 +43,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.NetworkService; import com.cloud.network.StorageNetworkService; import com.cloud.network.VpcVirtualNetworkApplianceService; +import com.cloud.network.as.AutoScaleService; import com.cloud.network.firewall.FirewallService; import com.cloud.network.firewall.NetworkACLService; import com.cloud.network.lb.LoadBalancingRulesService; @@ -79,7 +81,7 @@ public abstract class BaseCmd { public static final String RESPONSE_TYPE_JSON = "json"; public enum CommandType { - BOOLEAN, DATE, FLOAT, INTEGER, SHORT, LIST, LONG, OBJECT, MAP, STRING, TZDATE + BOOLEAN, DATE, FLOAT, INTEGER, SHORT, LIST, LONG, OBJECT, MAP, STRING, TZDATE, UUID } // FIXME: Extract these out into a separate file @@ -126,6 +128,7 @@ public abstract class BaseCmd { public static ResponseGenerator _responseGenerator; public static EntityManager _entityMgr; public static RulesService _rulesService; + public static AutoScaleService _autoScaleService; public static LoadBalancingRulesService _lbService; public static RemoteAccessVpnService _ravService; public static BareMetalVmService _bareMetalVmService; @@ -140,47 +143,40 @@ public abstract class BaseCmd { public static NetworkACLService _networkACLService; public static Site2SiteVpnService _s2sVpnService; - static void setComponents(ResponseGenerator generator) { - _mgr = (ManagementService) ComponentContext.getCompanent(ManagementService.class); - _accountService = ComponentContext.getCompanent(AccountService.class); - _configService = ComponentContext.getCompanent(ConfigurationService.class); - - _userVmService = ComponentContext.getCompanent(UserVmService.class); - - // TODO, ugly and will change soon - // - Map svmServices = ComponentContext.getComponentsOfType(UserVmService.class); - _userVmService = svmServices.get("BareMetalVmManagerImpl"); - - _storageService = ComponentContext.getCompanent(StorageService.class); - _resourceService = ComponentContext.getCompanent(ResourceService.class); - _networkService = ComponentContext.getCompanent(NetworkService.class); - _templateService = ComponentContext.getCompanent(TemplateService.class); - - // TODO, will change to looking for primary component - // ugly binding to a specific implementation - Map _sgServices = ComponentContext.getComponentsOfType(SecurityGroupService.class); - _securityGroupService = _sgServices.get("SecurityGroupManagerImpl2"); - - _snapshotService = ComponentContext.getCompanent(SnapshotService.class); - _consoleProxyService = ComponentContext.getCompanent(ConsoleProxyService.class); - _routerService = ComponentContext.getCompanent(VpcVirtualNetworkApplianceService.class); - _entityMgr = ComponentContext.getCompanent(EntityManager.class); - _rulesService = ComponentContext.getCompanent(RulesService.class); - _lbService = ComponentContext.getCompanent(LoadBalancingRulesService.class); - _ravService = ComponentContext.getCompanent(RemoteAccessVpnService.class); + public static QueryService _queryService; + + public static void setComponents(ResponseGenerator generator) { + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + _mgr = (ManagementService) ComponentLocator.getComponent(ManagementService.Name); + _accountService = locator.getManager(AccountService.class); + _configService = locator.getManager(ConfigurationService.class); + _userVmService = locator.getManager(UserVmService.class); + _storageService = locator.getManager(StorageService.class); + _resourceService = locator.getManager(ResourceService.class); + _networkService = locator.getManager(NetworkService.class); + _templateService = locator.getManager(TemplateService.class); + _securityGroupService = locator.getManager(SecurityGroupService.class); + _snapshotService = locator.getManager(SnapshotService.class); + _consoleProxyService = locator.getManager(ConsoleProxyService.class); + _routerService = locator.getManager(VpcVirtualNetworkApplianceService.class); + _entityMgr = locator.getManager(EntityManager.class); + _rulesService = locator.getManager(RulesService.class); + _lbService = locator.getManager(LoadBalancingRulesService.class); + _autoScaleService = locator.getManager(AutoScaleService.class); + _ravService = locator.getManager(RemoteAccessVpnService.class); _responseGenerator = generator; - _bareMetalVmService = ComponentContext.getCompanent(BareMetalVmService.class); - _projectService = ComponentContext.getCompanent(ProjectService.class); - _firewallService = ComponentContext.getCompanent(FirewallService.class); - _domainService = ComponentContext.getCompanent(DomainService.class); - _resourceLimitService = ComponentContext.getCompanent(ResourceLimitService.class); - _identityService = ComponentContext.getCompanent(IdentityService.class); - _storageNetworkService = ComponentContext.getCompanent(StorageNetworkService.class); - _taggedResourceService = ComponentContext.getCompanent(TaggedResourceService.class); - _vpcService = ComponentContext.getCompanent(VpcService.class); - _networkACLService = ComponentContext.getCompanent(NetworkACLService.class); - _s2sVpnService = ComponentContext.getCompanent(Site2SiteVpnService.class); + _bareMetalVmService = locator.getManager(BareMetalVmService.class); + _projectService = locator.getManager(ProjectService.class); + _firewallService = locator.getManager(FirewallService.class); + _domainService = locator.getManager(DomainService.class); + _resourceLimitService = locator.getManager(ResourceLimitService.class); + _identityService = locator.getManager(IdentityService.class); + _storageNetworkService = locator.getManager(StorageNetworkService.class); + _taggedResourceService = locator.getManager(TaggedResourceService.class); + _vpcService = locator.getManager(VpcService.class); + _networkACLService = locator.getManager(NetworkACLService.class); + _s2sVpnService = locator.getManager(Site2SiteVpnService.class); + _queryService = locator.getManager(QueryService.class); } public abstract void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException, NetworkRuleConflictException; @@ -313,14 +309,14 @@ public abstract class BaseCmd { StringBuffer sb = new StringBuffer(); if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // JSON response - sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},"); + sb.append("{ \"" + getCommandName() + "\" : { " + "\"@attributes\":{\"cloudstack-version\":\"" + _mgr.getVersion() + "\"},"); sb.append("\"errorcode\" : \"" + apiException.getErrorCode() + "\", \"description\" : \"" + apiException.getDescription() + "\" } }"); } else { sb.append(""); sb.append("<" + getCommandName() + ">"); sb.append("" + apiException.getErrorCode() + ""); sb.append("" + escapeXml(apiException.getDescription()) + ""); - sb.append(""); + sb.append(""); } return sb.toString(); } @@ -331,10 +327,10 @@ public abstract class BaseCmd { // set up the return value with the name of the response if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { - prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloud-stack-version\":\"" + _mgr.getVersion() + "\"},"); + prefixSb.append("{ \"" + getCommandName() + "\" : { \"@attributes\":{\"cloudstack-version\":\"" + _mgr.getVersion() + "\"},"); } else { prefixSb.append(""); - prefixSb.append("<" + getCommandName() + " cloud-stack-version=\"" + _mgr.getVersion() + "\">"); + prefixSb.append("<" + getCommandName() + " cloudstack-version=\"" + _mgr.getVersion() + "\">"); } int i = 0; @@ -354,7 +350,7 @@ public abstract class BaseCmd { if (suffixSb.length() > 0) { if (RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { // append comma only if we have some suffix else -// not as per strict Json syntax. + // not as per strict Json syntax. prefixSb.append(","); } prefixSb.append(suffixSb); @@ -517,8 +513,9 @@ public abstract class BaseCmd { throw new PermissionDeniedException("Can't add resources to the account id=" + account.getId() + " in state=" + account.getState() + " as it's no longer active"); } } else { - List idList = new ArrayList(); - idList.add(new IdentityProxy("domain", domainId, "domainId")); + // idList is not used anywhere, so removed it now + //List idList = new ArrayList(); + //idList.add(new IdentityProxy("domain", domainId, "domainId")); throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain with specified id"); } } diff --git a/api/src/com/cloud/api/BaseListAccountResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java similarity index 97% rename from api/src/com/cloud/api/BaseListAccountResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java index 37010054526..038da63ec4c 100644 --- a/api/src/com/cloud/api/BaseListAccountResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListAccountResourcesCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public abstract class BaseListAccountResourcesCmd extends BaseListDomainResourcesCmd { diff --git a/api/src/com/cloud/api/BaseListCmd.java b/api/src/org/apache/cloudstack/api/BaseListCmd.java old mode 100755 new mode 100644 similarity index 98% rename from api/src/com/cloud/api/BaseListCmd.java rename to api/src/org/apache/cloudstack/api/BaseListCmd.java index d5ece6b14b3..58e83f70929 --- a/api/src/com/cloud/api/BaseListCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; @@ -62,7 +62,7 @@ public abstract class BaseListCmd extends BaseCmd { return pageSize; } - static void configure() { + public static void configure() { if (_configService.getDefaultPageSize().longValue() != PAGESIZE_UNLIMITED) { MAX_PAGESIZE = _configService.getDefaultPageSize(); } diff --git a/api/src/com/cloud/api/BaseListDomainResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java similarity index 72% rename from api/src/com/cloud/api/BaseListDomainResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java index 9571e1263c1..6e50a159f20 100644 --- a/api/src/com/cloud/api/BaseListDomainResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListDomainResourcesCmd.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; + +import org.apache.cloudstack.api.response.DomainResponse; public abstract class BaseListDomainResourcesCmd extends BaseListCmd { @Parameter(name = ApiConstants.LIST_ALL, type = CommandType.BOOLEAN, description = "If set to false, " + - "list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") + "list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "list only resources" + - " belonging to the domain specified") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list only resources belonging to the domain specified") private Long domainId; @Parameter(name = ApiConstants.IS_RECURSIVE, type = CommandType.BOOLEAN, description = "defaults to false," + - " but if true, lists all resources from the parent specified by the domainId till leaves.") + " but if true, lists all resources from the parent specified by the domainId till leaves.") private Boolean recursive; public boolean listAll() { diff --git a/api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java similarity index 80% rename from api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java index 78e70019c9b..836527fc7c7 100644 --- a/api/src/com/cloud/api/BaseListProjectAndAccountResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListProjectAndAccountResourcesCmd.java @@ -14,12 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; + +import org.apache.cloudstack.api.response.ProjectResponse; public abstract class BaseListProjectAndAccountResourcesCmd extends BaseListAccountResourcesCmd { - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list objects by project") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="list objects by project") private Long projectId; public Long getProjectId() { diff --git a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java b/api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java similarity index 98% rename from api/src/com/cloud/api/BaseListTaggedResourcesCmd.java rename to api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java index 9b188d8ed25..88176a536ea 100644 --- a/api/src/com/cloud/api/BaseListTaggedResourcesCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListTaggedResourcesCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.util.Collection; import java.util.HashMap; @@ -26,7 +26,7 @@ import com.cloud.exception.InvalidParameterValueException; public abstract class BaseListTaggedResourcesCmd extends BaseListProjectAndAccountResourcesCmd{ @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List resources by tags (key/value pairs)") private Map tags; - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { diff --git a/api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java index cacb41f405d..cde2d948686 100644 --- a/api/src/com/cloud/api/commands/ListTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseListTemplateOrIsoPermissionsCmd.java @@ -14,33 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="List template visibility and all accounts that have permissions to view this template.", responseObject=TemplatePermissionsResponse.class) -public class ListTemplateOrIsoPermissionsCmd extends BaseCmd { - public Logger s_logger = getLogger(); +public class BaseListTemplateOrIsoPermissionsCmd extends BaseCmd { + public Logger s_logger = getLogger(); protected String s_name = "listtemplatepermissionsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the template ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplatePermissionsResponse.class, + required=true, description="the template ID") private Long id; ///////////////////////////////////////////////////// @@ -68,23 +62,23 @@ public class ListTemplateOrIsoPermissionsCmd extends BaseCmd { public String getCommandName() { return s_name; } - + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return true; + return true; } - + public String getMediaType() { - return "templateOrIso"; + return "templateOrIso"; } - + protected Logger getLogger() { - return Logger.getLogger(UpdateTemplateOrIsoPermissionsCmd.class.getName()); + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); } - + @Override public void execute(){ List accountNames = _templateService.listTemplatePermissions(this); - + Account account = UserContext.current().getCaller(); boolean isAdmin = (isAdmin(account.getType())); diff --git a/api/src/com/cloud/api/response/BaseResponse.java b/api/src/org/apache/cloudstack/api/BaseResponse.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/response/BaseResponse.java rename to api/src/org/apache/cloudstack/api/BaseResponse.java index e343a104887..28ca6b8c2de --- a/api/src/com/cloud/api/response/BaseResponse.java +++ b/api/src/org/apache/cloudstack/api/BaseResponse.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.utils.IdentityProxy; -import com.cloud.api.ResponseObject; +import org.apache.cloudstack.api.ResponseObject; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public abstract class BaseResponse implements ResponseObject { private transient String responseName; private transient String objectName; - + @Override public String getResponseName() { return responseName; @@ -35,7 +35,7 @@ public abstract class BaseResponse implements ResponseObject { public void setResponseName(String responseName) { this.responseName = responseName; } - + @Override public String getObjectName() { return objectName; @@ -45,31 +45,30 @@ public abstract class BaseResponse implements ResponseObject { public void setObjectName(String objectName) { this.objectName = objectName; } - - public Long getObjectId() { - return null; + + public String getObjectId() { + return null; } - - // For use by list commands with pending async jobs - @SerializedName(ApiConstants.JOB_ID) @Param(description="the ID of the latest async job acting on this object") - protected IdentityProxy jobId = new IdentityProxy("async_job"); - + + @SerializedName(ApiConstants.JOB_ID) @Param(description="the UUID of the latest async job acting on this object") + protected String jobId; + @SerializedName(ApiConstants.JOB_STATUS) @Param(description="the current status of the latest async job acting on this object") private Integer jobStatus; - - public Long getJobId() { - return jobId.getValue(); + + public String getJobId() { + return jobId; } - - public void setJobId(Long jobId) { - this.jobId.setValue(jobId); + + public void setJobId(String jobId) { + this.jobId = jobId; } - + public Integer getJobStatus() { - return jobStatus; + return jobStatus; } - + public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; + this.jobStatus = jobStatus; } } diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java rename to api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java index 89c4ee93f5e..dd6ae007ab9 100755 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoCmd.java @@ -14,17 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; -public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { +public abstract class BaseUpdateTemplateOrIsoCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateIsoCmd.class.getName()); ///////////////////////////////////////////////////// @@ -37,23 +38,23 @@ public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the image", length=4096) private String displayText; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the image file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the image file") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the image file") private String templateName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS type that best represents the OS of this image.") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="the ID of the OS type that best represents the OS of this image.") private Long osTypeId; - + @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, description="the format for the image") private String format; - + @Parameter(name=ApiConstants.PASSWORD_ENABLED, type=CommandType.BOOLEAN, description="true if the image supports the password reset feature; default is false") private Boolean passwordEnabled; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the template, integer") private Integer sortKey; @@ -80,16 +81,16 @@ public abstract class UpdateTemplateOrIsoCmd extends BaseCmd { public Long getOsTypeId() { return osTypeId; } - + public Boolean isPasswordEnabled() { return passwordEnabled; } - + public String getFormat() { return format; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } } diff --git a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java index 38a2e394145..aacc6efa2e0 100755 --- a/api/src/com/cloud/api/commands/UpdateTemplateOrIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/BaseUpdateTemplateOrIsoPermissionsCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api; import java.util.List; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; -public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { +public abstract class BaseUpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Logger s_logger = getLogger(); protected String s_name = getResponseName(); @@ -39,8 +36,8 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNTS, type = CommandType.LIST, collectionType = CommandType.STRING, description = "a comma delimited list of accounts. If specified, \"op\" parameter has to be passed in.") private List accountNames; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the template ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = TemplateResponse.class, + required = true, description = "the template ID") private Long id; @Parameter(name = ApiConstants.IS_FEATURED, type = CommandType.BOOLEAN, description = "true for featured template/iso, false otherwise") @@ -48,15 +45,15 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { @Parameter(name = ApiConstants.IS_PUBLIC, type = CommandType.BOOLEAN, description = "true for public template/iso, false for private templates/isos") private Boolean isPublic; - + @Parameter(name = ApiConstants.IS_EXTRACTABLE, type = CommandType.BOOLEAN, description = "true if the template/iso is extractable, false other wise. Can be set only by root admin") private Boolean isExtractable; @Parameter(name = ApiConstants.OP, type = CommandType.STRING, description = "permission operator (add, remove, reset)") private String operation; - - @IdentityMapper(entityTableName="projects") - @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.LONG, description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") + + @Parameter(name = ApiConstants.PROJECT_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ProjectResponse.class, + description = "a comma delimited list of projects. If specified, \"op\" parameter has to be passed in.") private List projectIds; // /////////////////////////////////////////////////// @@ -65,10 +62,10 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public List getAccountNames() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); } - - return accountNames; + + return accountNames; } public Long getId() { @@ -82,18 +79,18 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public Boolean isExtractable() { return isExtractable; } - + public String getOperation() { return operation; } - + public List getProjectIds() { if (accountNames != null && projectIds != null) { - throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); + throw new InvalidParameterValueException("Accounts and projectIds can't be specified together"); } return projectIds; } @@ -112,7 +109,7 @@ public abstract class UpdateTemplateOrIsoPermissionsCmd extends BaseCmd { } protected Logger getLogger() { - return Logger.getLogger(UpdateTemplateOrIsoPermissionsCmd.class.getName()); + return Logger.getLogger(BaseUpdateTemplateOrIsoPermissionsCmd.class.getName()); } @Override diff --git a/api/src/org/apache/cloudstack/api/EntityReference.java b/api/src/org/apache/cloudstack/api/EntityReference.java new file mode 100644 index 00000000000..1de84cee5da --- /dev/null +++ b/api/src/org/apache/cloudstack/api/EntityReference.java @@ -0,0 +1,28 @@ +// 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 org.apache.cloudstack.api; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/* There is a one on one mapping between the EntityReference and the EntityResponse + * to the OTW layer. Value is the actual entity class it refers to. + */ +@Retention(RetentionPolicy.RUNTIME) +public @interface EntityReference { + Class[] value() default {}; +} diff --git a/api/src/com/cloud/api/Identity.java b/api/src/org/apache/cloudstack/api/Identity.java similarity index 96% rename from api/src/com/cloud/api/Identity.java rename to api/src/org/apache/cloudstack/api/Identity.java index 09ce7a8ac04..22d23b70017 100644 --- a/api/src/com/cloud/api/Identity.java +++ b/api/src/org/apache/cloudstack/api/Identity.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface Identity { String getUuid(); diff --git a/api/src/com/cloud/api/IdentityService.java b/api/src/org/apache/cloudstack/api/IdentityService.java similarity index 91% rename from api/src/com/cloud/api/IdentityService.java rename to api/src/org/apache/cloudstack/api/IdentityService.java index 1c53a1dfcd4..a2ccec2dae7 100644 --- a/api/src/com/cloud/api/IdentityService.java +++ b/api/src/org/apache/cloudstack/api/IdentityService.java @@ -14,12 +14,9 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface IdentityService { - Long getIdentityId(IdentityMapper mapper, String identityString); - Long getIdentityId(String tableName, String identityString); - String getIdentityUuid(String tableName, String identityString); } diff --git a/api/src/org/apache/cloudstack/api/InternalIdentity.java b/api/src/org/apache/cloudstack/api/InternalIdentity.java new file mode 100644 index 00000000000..1dfeb8c9091 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/InternalIdentity.java @@ -0,0 +1,26 @@ +// 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 org.apache.cloudstack.api; + +// This interface is a contract that getId() will give the internal +// ID of an entity which extends this interface +// Any class having an internal ID in db table/schema should extend this +// For example, all ControlledEntity, OwnedBy would have an internal ID + +public interface InternalIdentity { + long getId(); +} diff --git a/api/src/com/cloud/api/Parameter.java b/api/src/org/apache/cloudstack/api/Parameter.java similarity index 88% rename from api/src/com/cloud/api/Parameter.java rename to api/src/org/apache/cloudstack/api/Parameter.java index 2da3c400f07..6f64737ab83 100644 --- a/api/src/com/cloud/api/Parameter.java +++ b/api/src/org/apache/cloudstack/api/Parameter.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; @@ -22,7 +22,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.BaseCmd.CommandType; @Retention(RetentionPolicy.RUNTIME) @Target({ FIELD }) @@ -37,6 +37,8 @@ public @interface Parameter { CommandType collectionType() default CommandType.OBJECT; + Class[] entityType() default Object.class; + boolean expose() default true; boolean includeInApiDoc() default true; @@ -44,4 +46,6 @@ public @interface Parameter { int length() default 255; String since() default ""; + + String retrieveMethod() default "getById"; } diff --git a/api/src/com/cloud/api/PlugService.java b/api/src/org/apache/cloudstack/api/PlugService.java similarity index 97% rename from api/src/com/cloud/api/PlugService.java rename to api/src/org/apache/cloudstack/api/PlugService.java index 7df86f9394f..00032e3abdd 100644 --- a/api/src/com/cloud/api/PlugService.java +++ b/api/src/org/apache/cloudstack/api/PlugService.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.RetentionPolicy.RUNTIME; diff --git a/api/src/com/cloud/api/ResponseGenerator.java b/api/src/org/apache/cloudstack/api/ResponseGenerator.java old mode 100755 new mode 100644 similarity index 63% rename from api/src/com/cloud/api/ResponseGenerator.java rename to api/src/org/apache/cloudstack/api/ResponseGenerator.java index 996a5fcfd4b..e9f988ade60 --- a/api/src/com/cloud/api/ResponseGenerator.java +++ b/api/src/org/apache/cloudstack/api/ResponseGenerator.java @@ -14,77 +14,86 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; import java.text.DecimalFormat; import java.util.EnumSet; import java.util.List; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.CreateCmdResponse; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ExtractResponse; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.NetworkACLResponse; -import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.api.response.NetworkResponse; -import com.cloud.api.response.PhysicalNetworkResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.api.response.PrivateGatewayResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.ServiceOfferingResponse; -import com.cloud.api.response.ServiceResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; -import com.cloud.api.response.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StaticRouteResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.SwiftResponse; -import com.cloud.api.response.SystemVmInstanceResponse; -import com.cloud.api.response.SystemVmResponse; -import com.cloud.api.response.TemplatePermissionsResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.TrafficTypeResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; -import com.cloud.api.response.VlanIpRangeResponse; -import com.cloud.api.response.VolumeResponse; -import com.cloud.api.response.VpcOfferingResponse; -import com.cloud.api.response.VpcResponse; -import com.cloud.api.response.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ServiceResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SwiftResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +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.apache.cloudstack.api.response.S3Response; + import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.configuration.Configuration; @@ -110,6 +119,11 @@ import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VpnUser; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.Condition; +import com.cloud.network.as.Counter; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.LoadBalancer; @@ -117,7 +131,6 @@ import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.security.SecurityGroup; -import com.cloud.network.security.SecurityGroupRules; import com.cloud.network.security.SecurityRule; import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.StaticRoute; @@ -131,11 +144,14 @@ import com.cloud.projects.Project; 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; import com.cloud.storage.Volume; import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.User; @@ -225,7 +241,7 @@ public interface ResponseGenerator { List createTemplateResponses(long templateId, Long snapshotId, Long volumeId, boolean readyOnly); - ListResponse createSecurityGroupResponses(List networkGroups); + //ListResponse createSecurityGroupResponses(List networkGroups); SecurityGroupResponse createSecurityGroupResponseFromSecurityGroupRule(List SecurityRules); @@ -239,6 +255,8 @@ public interface ResponseGenerator { EventResponse createEventResponse(Event event); + //List createEventResponse(EventJoinVO... events); + TemplateResponse createIsoResponse(VirtualMachineTemplate result); List createCapacityResponse(List result, DecimalFormat format); @@ -253,6 +271,8 @@ public interface ResponseGenerator { UserResponse createUserResponse(User user); + //List createUserResponse(UserAccountJoinVO... users); + AccountResponse createUserAccountResponse(UserAccount user); Long getSecurityGroupId(String groupName, long accountId); @@ -261,6 +281,7 @@ public interface ResponseGenerator { ProjectResponse createProjectResponse(Project project); + List createIsoResponses(VirtualMachineTemplate iso, long zoneId, boolean readyOnly); List createTemplateResponses(long templateId, Long vmId); @@ -277,6 +298,8 @@ public interface ResponseGenerator { SwiftResponse createSwiftResponse(Swift swift); + S3Response createS3Response(S3 result); + PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result); ServiceResponse createNetworkServiceResponse(Service service); @@ -290,7 +313,7 @@ public interface ResponseGenerator { LDAPConfigResponse createLDAPConfigResponse(String hostname, Integer port, Boolean useSSL, String queryFilter, String baseSearch, String dn); StorageNetworkIpRangeResponse createStorageNetworkIpRangeResponse(StorageNetworkIpRange result); - + /** * @param tableName TODO * @param token @@ -305,8 +328,10 @@ public interface ResponseGenerator { */ ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly); + Site2SiteVpnGatewayResponse createSite2SiteVpnGatewayResponse(Site2SiteVpnGateway result); + /** * @param offering * @return @@ -340,4 +365,18 @@ public interface ResponseGenerator { Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result); Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result); + + CounterResponse createCounterResponse(Counter ctr); + + ConditionResponse createConditionResponse(Condition cndn); + + AutoScalePolicyResponse createAutoScalePolicyResponse(AutoScalePolicy policy); + + AutoScaleVmProfileResponse createAutoScaleVmProfileResponse(AutoScaleVmProfile profile); + + AutoScaleVmGroupResponse createAutoScaleVmGroupResponse(AutoScaleVmGroup vmGroup); + + GuestOSResponse createGuestOSResponse(GuestOS os); + + SnapshotScheduleResponse createSnapshotScheduleResponse(SnapshotSchedule sched); } diff --git a/api/src/com/cloud/api/ResponseObject.java b/api/src/org/apache/cloudstack/api/ResponseObject.java similarity index 88% rename from api/src/com/cloud/api/ResponseObject.java rename to api/src/org/apache/cloudstack/api/ResponseObject.java index 2d08fb975b5..c8bd45727c9 100644 --- a/api/src/com/cloud/api/ResponseObject.java +++ b/api/src/org/apache/cloudstack/api/ResponseObject.java @@ -14,64 +14,65 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; +package org.apache.cloudstack.api; public interface ResponseObject { /** * Get the name of the API response - * + * * @return the name of the API response */ String getResponseName(); /** * Set the name of the API response - * + * * @param name */ void setResponseName(String name); /** * Get the name of the API object - * + * * @return the name of the API object */ String getObjectName(); /** - * + * * @param name */ void setObjectName(String name); /** - * Returns the object Id + * Returns the object UUid */ - Long getObjectId(); + String getObjectId(); /** * Returns the job id - * + * * @return */ - Long getJobId(); + String getJobId(); + /** * Sets the job id - * + * * @param jobId */ - void setJobId(Long jobId); + void setJobId(String jobId); /** * Returns the job status - * + * * @return */ Integer getJobStatus(); /** - * + * * @param jobStatus */ void setJobStatus(Integer jobStatus); diff --git a/api/src/com/cloud/api/ServerApiException.java b/api/src/org/apache/cloudstack/api/ServerApiException.java similarity index 96% rename from api/src/com/cloud/api/ServerApiException.java rename to api/src/org/apache/cloudstack/api/ServerApiException.java index 721cf13d353..70fd34e5cf7 100644 --- a/api/src/com/cloud/api/ServerApiException.java +++ b/api/src/org/apache/cloudstack/api/ServerApiException.java @@ -14,8 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api; -import com.cloud.utils.IdentityProxy; +package org.apache.cloudstack.api; import com.cloud.utils.exception.RuntimeCloudException; @SuppressWarnings("serial") @@ -48,5 +47,5 @@ public class ServerApiException extends RuntimeCloudException { public void setDescription(String description) { _description = description; } - + } diff --git a/api/src/org/apache/cloudstack/api/Validate.java b/api/src/org/apache/cloudstack/api/Validate.java new file mode 100644 index 00000000000..deedda62273 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/Validate.java @@ -0,0 +1,30 @@ +// 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 org.apache.cloudstack.api; + +import static java.lang.annotation.ElementType.FIELD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ FIELD }) +public @interface Validate { + Class[] validators() default Object.class; + String description() default ""; +} diff --git a/api/src/com/cloud/api/commands/CreateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/commands/CreateAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java index 00e87761c5d..f93787b7bc5 --- a/api/src/com/cloud/api/commands/CreateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/CreateAccountCmd.java @@ -14,26 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import java.util.Collection; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Creates an account", responseObject=UserResponse.class) +@APICommand(name = "createAccount", description="Creates an account", responseObject=UserResponse.class) public class CreateAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateAccountCmd.class.getName()); @@ -49,8 +46,8 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.SHORT, required=true, description="Type of the account. Specify 0 for user, 1 for root admin, and 2 for domain admin") private Short accountType; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Creates the user under the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Creates the user under the specified domain.") private Long domainId; @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, required=true, description="email") @@ -70,12 +67,13 @@ public class CreateAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="Unique username.") private String userName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the account's networks") private String networkDomain; - @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") + @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -115,19 +113,19 @@ public class CreateAccountCmd extends BaseCmd { public String getUsername() { return userName; } - + public String getNetworkDomain() { return networkDomain; - } - + } + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } ///////////////////////////////////////////////////// @@ -138,12 +136,12 @@ public class CreateAccountCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); @@ -156,4 +154,4 @@ public class CreateAccountCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user account"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java old mode 100755 new mode 100644 similarity index 78% rename from api/src/com/cloud/api/commands/DeleteAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java index a7bfca78359..a1d9b6419cb --- a/api/src/com/cloud/api/commands/DeleteAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DeleteAccountCmd.java @@ -14,39 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Deletes a account, and all users associated with this account", responseObject=SuccessResponse.class) +@APICommand(name = "deleteAccount", description="Deletes a account, and all users associated with this account", responseObject=SuccessResponse.class) public class DeleteAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteAccountCmd.class.getName()); - private static final String s_name = "deleteaccountresponse"; + public static final Logger s_logger = Logger.getLogger(DeleteAccountCmd.class.getName()); + private static final String s_name = "deleteaccountresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + required=true, description="Account id") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,17 +49,16 @@ public class DeleteAccountCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - public static String getStaticName() { - return s_name; - } - + public static String getStaticName() { + return s_name; + } + @Override - public String getCommandName() { + public String getCommandName() { return s_name; } @@ -89,7 +82,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd { User user = _responseGenerator.findUserById(getId()); return (user != null ? ("deleting User " + user.getUsername() + " (id: " + user.getId() + ") and accountId = " + user.getAccountId()) : "user delete, but this user does not exist in the system"); } - + @Override public void execute(){ UserContext.current().setEventDetails("Account Id: "+getId()); @@ -101,7 +94,7 @@ public class DeleteAccountCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user account and all corresponding users"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; diff --git a/api/src/com/cloud/api/commands/DisableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DisableAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java index 7c5e5e38331..f0a5e7078b7 100644 --- a/api/src/com/cloud/api/commands/DisableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/DisableAccountCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -33,23 +30,23 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Disables an account", responseObject=AccountResponse.class) +@APICommand(name = "disableAccount", description="Disables an account", responseObject=AccountResponse.class) public class DisableAccountCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableAccountCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DisableAccountCmd.class.getName()); private static final String s_name = "disableaccountresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Disables specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Disables specified account in this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Disables specified account in this domain.") private Long domainId; @Parameter(name=ApiConstants.LOCK, type=CommandType.BOOLEAN, required=true, description="If true, only lock the account; else disable the account") @@ -62,7 +59,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -91,7 +88,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { if (account != null) { return account.getAccountId(); } - + account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); if (account != null) { return account.getAccountId(); @@ -108,11 +105,11 @@ public class DisableAccountCmd extends BaseAsyncCmd { @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException{ UserContext.current().setEventDetails("Account Name: "+getAccountName()+", Domain Id:"+getDomainId()); - Account result = null; - if(lockRequested) - result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); - else - result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); + Account result = null; + if(lockRequested) + result = _accountService.lockAccount(getAccountName(), getDomainId(), getId()); + else + result = _accountService.disableAccount(getAccountName(), getDomainId(), getId()); if (result != null){ AccountResponse response = _responseGenerator.createAccountResponse(result); response.setResponseName(getCommandName()); @@ -121,7 +118,7 @@ public class DisableAccountCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, lockRequested == true ? "Failed to lock account" : "Failed to disable account" ); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; diff --git a/api/src/com/cloud/api/commands/EnableAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/EnableAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java index 576f9354892..4aa1e4fc1b9 100644 --- a/api/src/com/cloud/api/commands/EnableAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/EnableAccountCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Enables an account", responseObject=AccountResponse.class) +@APICommand(name = "enableAccount", description="Enables an account", responseObject=AccountResponse.class) public class EnableAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(EnableAccountCmd.class.getName()); private static final String s_name = "enableaccountresponse"; @@ -35,15 +36,15 @@ public class EnableAccountCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Enables specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Enables specified account in this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Enables specified account in this domain.") private Long domainId; ///////////////////////////////////////////////////// @@ -53,7 +54,7 @@ public class EnableAccountCmd extends BaseCmd { public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -70,14 +71,14 @@ public class EnableAccountCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _entityMgr.findById(Account.class, getId()); if (account != null) { return account.getAccountId(); } - + account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); if (account != null) { return account.getAccountId(); diff --git a/api/src/com/cloud/api/commands/LockAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/LockAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java index 8c47dbc9d83..34e9e53b84d 100644 --- a/api/src/com/cloud/api/commands/LockAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/LockAccountCmd.java @@ -14,19 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Locks an account", responseObject=AccountResponse.class) +@APICommand(name = "lockAccount", description="Locks an account", responseObject=AccountResponse.class) public class LockAccountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LockAccountCmd.class.getName()); @@ -39,8 +40,8 @@ public class LockAccountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Locks the specified account.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="Locks the specified account on this domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="Locks the specified account on this domain.") private Long domainId; ///////////////////////////////////////////////////// @@ -58,12 +59,12 @@ public class LockAccountCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _accountService.getActiveAccountByName(getAccountName(), getDomainId()); diff --git a/api/src/com/cloud/api/commands/UpdateAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/UpdateAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java index 8e3ef4364b3..f1340464d6b --- a/api/src/com/cloud/api/commands/UpdateAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/account/UpdateAccountCmd.java @@ -14,49 +14,50 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.account; import java.util.Collection; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; + import com.cloud.user.Account; -@Implementation(description="Updates account information for the authenticated user", responseObject=AccountResponse.class) +@APICommand(name = "updateAccount", description="Updates account information for the authenticated user", responseObject=AccountResponse.class) public class UpdateAccountCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(UpdateAccountCmd.class.getName()); private static final String s_name = "updateaccountresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Account id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=AccountResponse.class, + description="Account id") private Long id; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the current account name") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain where the account exists") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the domain where the account exists") private Long domainId; @Parameter(name=ApiConstants.NEW_NAME, type=CommandType.STRING, required=true, description="new name for the account") private String newName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the account's networks; empty string will update domainName with NULL value") private String networkDomain; - - @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") + + @Parameter(name = ApiConstants.ACCOUNT_DETAILS, type = CommandType.MAP, description = "details for account used to store specific parameters") private Map details; ///////////////////////////////////////////////////// @@ -66,7 +67,7 @@ public class UpdateAccountCmd extends BaseCmd{ public Long getId() { return id; } - + public String getAccountName() { return accountName; } @@ -78,19 +79,19 @@ public class UpdateAccountCmd extends BaseCmd{ public String getNewName() { return newName; } - + public String getNetworkDomain() { return networkDomain; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } ///////////////////////////////////////////////////// @@ -101,7 +102,7 @@ public class UpdateAccountCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = _entityMgr.findById(Account.class, getId()); @@ -115,7 +116,7 @@ public class UpdateAccountCmd extends BaseCmd{ return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ Account result = _accountService.updateAccount(this); diff --git a/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java new file mode 100644 index 00000000000..7369a6f6d08 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/CreateCounterCmd.java @@ -0,0 +1,120 @@ +// 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 org.apache.cloudstack.api.command.admin.autoscale; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CounterResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.Counter; +import com.cloud.user.Account; + +@APICommand(name = "createCounter", description = "Adds metric counter", responseObject = CounterResponse.class) +public class CreateCounterCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(CreateCounterCmd.class.getName()); + private static final String s_name = "counterresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "Name of the counter.") + private String name; + + @Parameter(name = ApiConstants.SOURCE, type = CommandType.STRING, required = true, description = "Source of the counter.") + private String source; + + @Parameter(name = ApiConstants.VALUE, type = CommandType.STRING, required = true, description = "Value of the counter e.g. oid in case of snmp.") + private String value; + + // ///////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public String getName() { + return name; + } + + public String getSource() { + return source; + } + + public String getValue() { + return value; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public void create() { + Counter ctr = null; + ctr = _autoScaleService.createCounter(this); + + if (ctr != null) { + this.setEntityId(ctr.getId()); + CounterResponse response = _responseGenerator.createCounterResponse(ctr); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Counter with name " + getName()); + } + } + + @Override + public void execute() { + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.Counter; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_COUNTER_CREATE; + } + + @Override + public String getEventDescription() { + return "creating a new Counter"; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public String getEntityTable() { + return "counter"; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java new file mode 100644 index 00000000000..9304eeb7b93 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/autoscale/DeleteCounterCmd.java @@ -0,0 +1,103 @@ +// 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 org.apache.cloudstack.api.command.admin.autoscale; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceInUseException; +import com.cloud.user.Account; + +@APICommand(name = "deleteCounter", description = "Deletes a counter", responseObject = SuccessResponse.class) +public class DeleteCounterCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteCounterCmd.class.getName()); + private static final String s_name = "deletecounterresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=CounterResponse.class, + required=true, description="the ID of the counter") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + boolean result = false; + try { + result = _autoScaleService.deleteCounter(getId()); + } catch (ResourceInUseException ex) { + s_logger.warn("Exception: ", ex); + throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage()); + } + + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + s_logger.warn("Failed to delete counter with Id: " + getId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete counter."); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public Long getId() { + return id; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.Counter; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_COUNTER_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting a counter."; + } +} diff --git a/api/src/com/cloud/api/commands/AddClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/AddClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java index 0ff77e01c51..28bf72ddba7 --- a/api/src/com/cloud/api/commands/AddClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/AddClusterCmd.java @@ -15,41 +15,39 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.exception.DiscoveryException; import com.cloud.exception.ResourceInUseException; import com.cloud.org.Cluster; import com.cloud.user.Account; -import com.cloud.utils.IdentityProxy; - -@Implementation(description="Adds a new cluster", responseObject=ClusterResponse.class) -public class AddClusterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); - - private static final String s_name = "addclusterresponse"; - - @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, required=true, description="the cluster name") - private String clusterName; - - @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=false, description="the password for the host") - private String password; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, required=true, description="the Pod ID for the host") +@APICommand(name = "addCluster", description="Adds a new cluster", responseObject=ClusterResponse.class) +public class AddClusterCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); + + private static final String s_name = "addclusterresponse"; + + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, required=true, description="the cluster name") + private String clusterName; + + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=false, description="the password for the host") + private String password; + + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the URL") @@ -58,20 +56,19 @@ public class AddClusterCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=false, description="the username for the cluster") private String username; - @IdentityMapper(entityTableName="data_center") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID for the cluster") + private Long zoneId; - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the cluster") - private Long zoneId; - - @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator") - private String hypervisor; - - @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, required=true, description="type of the cluster: CloudManaged, ExternalManaged") - private String clusterType; - - @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") + @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the cluster: XenServer,KVM,VMware,Hyperv,BareMetal,Simulator") + private String hypervisor; + + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, required=true, description="type of the cluster: CloudManaged, ExternalManaged") + private String clusterType; + + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name = ApiConstants.VSM_USERNAME, type = CommandType.STRING, required = false, description = "the username for the VSM associated with this cluster") private String vsmusername; @@ -80,7 +77,7 @@ public class AddClusterCmd extends BaseCmd { @Parameter(name = ApiConstants.VSM_IPADDRESS, type = CommandType.STRING, required = false, description = "the ipaddress of the VSM associated with this cluster") private String vsmipaddress; - + public String getVSMIpaddress() { return vsmipaddress; } @@ -92,90 +89,90 @@ public class AddClusterCmd extends BaseCmd { public String getVSMUsername() { return vsmusername; } - - public String getClusterName() { - return clusterName; - } - - public String getPassword() { - return password; - } - - public Long getPodId() { - return podId; - } - - public String getUrl() { - return url; - } - - public String getUsername() { - return username; - } - - public Long getZoneId() { - return zoneId; - } - - public String getHypervisor() { - return hypervisor; - } - - @Override - public String getCommandName() { - return s_name; - } - - public String getClusterType() { - return clusterType; - } - - public void setClusterType(String type) { - this.clusterType = type; - } - - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } - - public String getAllocationState() { - return allocationState; - } - - public void setAllocationState(String allocationState) { - this.allocationState = allocationState; - } - - @Override - public void execute(){ - try { - List result = _resourceService.discoverCluster(this); - ListResponse response = new ListResponse(); - List clusterResponses = new ArrayList(); - if (result != null) { - for (Cluster cluster : result) { - ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); - clusterResponses.add(clusterResponse); - } - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add cluster"); - } - - response.setResponses(clusterResponses); - response.setResponseName(getCommandName()); - - this.setResponseObject(response); - } catch (DiscoveryException ex) { - s_logger.warn("Exception: ", ex); + + public String getClusterName() { + return clusterName; + } + + public String getPassword() { + return password; + } + + public Long getPodId() { + return podId; + } + + public String getUrl() { + return url; + } + + public String getUsername() { + return username; + } + + public Long getZoneId() { + return zoneId; + } + + public String getHypervisor() { + return hypervisor; + } + + @Override + public String getCommandName() { + return s_name; + } + + public String getClusterType() { + return clusterType; + } + + public void setClusterType(String type) { + this.clusterType = type; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + + public String getAllocationState() { + return allocationState; + } + + public void setAllocationState(String allocationState) { + this.allocationState = allocationState; + } + + @Override + public void execute(){ + try { + List result = _resourceService.discoverCluster(this); + ListResponse response = new ListResponse(); + List clusterResponses = new ArrayList(); + if (result != null && result.size() > 0) { + for (Cluster cluster : result) { + ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); + clusterResponses.add(clusterResponse); + } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add cluster"); + } + + response.setResponses(clusterResponses); + response.setResponseName(getCommandName()); + + this.setResponseObject(response); + } catch (DiscoveryException ex) { + s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (ResourceInUseException ex) { s_logger.warn("Exception: ", ex); ServerApiException e = new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - for (IdentityProxy proxyObj : ex.getIdProxyList()) { - e.addProxyObject(proxyObj.getTableName(), proxyObj.getValue(), proxyObj.getidFieldName()); + for (String proxyObj : ex.getIdProxyList()) { + e.addProxyObject(proxyObj); } throw e; - } - } + } + } } diff --git a/api/src/com/cloud/api/commands/DeleteClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/DeleteClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java index 2e08b1c9100..f0b40cb6b03 --- a/api/src/com/cloud/api/commands/DeleteClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/DeleteClusterCmd.java @@ -14,21 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; - -@Implementation(description="Deletes a cluster.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteCluster", description="Deletes a cluster.", responseObject=SuccessResponse.class) public class DeleteClusterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteClusterCmd.class.getName()); @@ -38,11 +37,10 @@ public class DeleteClusterCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the cluster ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + required=true, description="the cluster ID") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +49,6 @@ public class DeleteClusterCmd extends BaseCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +57,12 @@ public class DeleteClusterCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _resourceService.deleteCluster(this); diff --git a/api/src/com/cloud/api/commands/ListClustersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListClustersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java index e3e2e5096ba..95ab0bff4f3 --- a/api/src/com/cloud/api/commands/ListClustersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/ListClustersCmd.java @@ -14,23 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.PodResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.org.Cluster; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="Lists clusters.", responseObject=ClusterResponse.class) +import com.cloud.org.Cluster; +import com.cloud.utils.Pair; + +@APICommand(name = "listClusters", description="Lists clusters.", responseObject=ClusterResponse.class) public class ListClustersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); @@ -40,19 +44,19 @@ public class ListClustersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists clusters by the cluster ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="lists clusters by the cluster ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="lists clusters by the cluster name") private String clusterName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists clusters by Pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="lists clusters by Pod ID") private Long podId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists clusters by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="lists clusters by Zone ID") private Long zoneId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="lists clusters by hypervisor type") @@ -60,13 +64,13 @@ public class ListClustersCmd extends BaseListCmd { @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="lists clusters by cluster type") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="lists clusters by allocation state") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the clusters") private Boolean showCapacities; @@ -89,19 +93,19 @@ public class ListClustersCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getHypervisorType() { - return hypervisorType; + return hypervisorType; } - + public String getClusterType() { - return clusterType; + return clusterType; } public String getAllocationState() { - return allocationState; + return allocationState; } - + public String getManagedstate() { return managedState; @@ -113,30 +117,30 @@ public class ListClustersCmd extends BaseListCmd { public Boolean getShowCapacities() { - return showCapacities; - } + return showCapacities; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _mgr.searchForClusters(this); + Pair, Integer> result = _mgr.searchForClusters(this); ListResponse response = new ListResponse(); List clusterResponses = new ArrayList(); - for (Cluster cluster : result) { + for (Cluster cluster : result.first()) { ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster,showCapacities); clusterResponse.setObjectName("cluster"); clusterResponses.add(clusterResponse); } - response.setResponses(clusterResponses); + response.setResponses(clusterResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateClusterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/UpdateClusterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java index 9a2d66865b4..03b43def3ca --- a/api/src/com/cloud/api/commands/UpdateClusterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/cluster/UpdateClusterCmd.java @@ -14,46 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.cluster; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ClusterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.org.Cluster; import com.cloud.user.Account; -@Implementation(description="Updates an existing cluster", responseObject=ClusterResponse.class) +@APICommand(name = "updateCluster", description="Updates an existing cluster", responseObject=ClusterResponse.class) public class UpdateClusterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddClusterCmd.class.getName()); private static final String s_name = "updateclusterresponse"; - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Cluster") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ClusterResponse.class, + required=true, description="the ID of the Cluster") private Long id; - + @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name") private String clusterName; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="hypervisor type of the cluster") private String hypervisor; - + @Parameter(name=ApiConstants.CLUSTER_TYPE, type=CommandType.STRING, description="hypervisor type of the cluster") private String clusterType; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.MANAGED_STATE, type=CommandType.STRING, description="whether this cluster is managed by cloudstack") private String managedState; - + public String getClusterName() { return clusterName; } @@ -63,34 +62,34 @@ public class UpdateClusterCmd extends BaseCmd { } public String getHypervisor() { - return hypervisor; + return hypervisor; } - + @Override public String getCommandName() { - return s_name; + return s_name; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String type) { - this.clusterType = type; + this.clusterType = type; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; - } + this.allocationState = allocationState; + } public String getManagedstate() { return managedState; @@ -102,11 +101,11 @@ public class UpdateClusterCmd extends BaseCmd { @Override public void execute(){ - Cluster cluster = _resourceService.getCluster(getId()); + Cluster cluster = _resourceService.getCluster(getId()); if (cluster == null) { throw new InvalidParameterValueException("Unable to find the cluster by id=" + getId()); } - + Cluster result = _resourceService.updateCluster(cluster, getClusterType(), getHypervisor(), getAllocationState(), getManagedstate()); if (result != null) { ClusterResponse clusterResponse = _responseGenerator.createClusterResponse(cluster, false); diff --git a/api/src/com/cloud/api/commands/ListCfgsByCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/ListCfgsByCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java index 8dc740f00bd..16010fdb495 100644 --- a/api/src/com/cloud/api/commands/ListCfgsByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/ListCfgsByCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.configuration.Configuration; +import com.cloud.utils.Pair; -@Implementation(description = "Lists all configurations.", responseObject = ConfigurationResponse.class) +@APICommand(name = "listConfigurations", description = "Lists all configurations.", responseObject = ConfigurationResponse.class) public class ListCfgsByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListCfgsByCmd.class.getName()); @@ -78,16 +79,16 @@ public class ListCfgsByCmd extends BaseListCmd { @Override public void execute() { - List result = _mgr.searchForConfigurations(this); + Pair, Integer> result = _mgr.searchForConfigurations(this); ListResponse response = new ListResponse(); List configResponses = new ArrayList(); - for (Configuration cfg : result) { + for (Configuration cfg : result.first()) { ConfigurationResponse cfgResponse = _responseGenerator.createConfigurationResponse(cfg); cfgResponse.setObjectName("configuration"); configResponses.add(cfgResponse); } - response.setResponses(configResponses); + response.setResponses(configResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java index 0cda15a8368..b69e9eab597 100644 --- a/api/src/com/cloud/api/commands/ListHypervisorCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/ListHypervisorCapabilitiesCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.HypervisorCapabilities; +import com.cloud.utils.Pair; -@Implementation(description="Lists all hypervisor capabilities.", responseObject=HypervisorCapabilitiesResponse.class, since="3.0.0") +@APICommand(name = "listHypervisorCapabilities", description="Lists all hypervisor capabilities.", responseObject=HypervisorCapabilitiesResponse.class, since="3.0.0") public class ListHypervisorCapabilitiesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListHypervisorCapabilitiesCmd.class.getName()); @@ -41,14 +41,13 @@ public class ListHypervisorCapabilitiesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="hypervisor_capabilities") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the hypervisor capability") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HypervisorCapabilitiesResponse.class, + description="ID of the hypervisor capability") private Long id; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -76,16 +75,17 @@ public class ListHypervisorCapabilitiesCmd extends BaseListCmd { @Override public void execute(){ - List hpvCapabilities = _mgr.listHypervisorCapabilities(getId(), getHypervisor(), getKeyword(), this.getStartIndex(), this.getPageSizeVal()); + Pair, Integer> hpvCapabilities = _mgr.listHypervisorCapabilities(getId(), + getHypervisor(), getKeyword(), this.getStartIndex(), this.getPageSizeVal()); ListResponse response = new ListResponse(); List hpvCapabilitiesResponses = new ArrayList(); - for (HypervisorCapabilities capability : hpvCapabilities) { + for (HypervisorCapabilities capability : hpvCapabilities.first()) { HypervisorCapabilitiesResponse hpvCapabilityResponse = _responseGenerator.createHypervisorCapabilitiesResponse(capability); hpvCapabilityResponse.setObjectName("hypervisorCapabilities"); hpvCapabilitiesResponses.add(hpvCapabilityResponse); } - response.setResponses(hpvCapabilitiesResponses); + response.setResponses(hpvCapabilitiesResponses, hpvCapabilities.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateCfgCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/UpdateCfgCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java index f2d9fe92cac..79693e76f84 100644 --- a/api/src/com/cloud/api/commands/UpdateCfgCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateCfgCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; -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.ConfigurationResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ConfigurationResponse; import com.cloud.configuration.Configuration; import com.cloud.user.Account; -@Implementation(description="Updates a configuration.", responseObject=ConfigurationResponse.class) +@APICommand(name = "updateConfiguration", description="Updates a configuration.", responseObject=ConfigurationResponse.class) public class UpdateCfgCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateCfgCmd.class.getName()); private static final String s_name = "updateconfigurationresponse"; @@ -62,12 +62,12 @@ public class UpdateCfgCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Configuration cfg = _configService.updateConfiguration(this); diff --git a/api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java index 3173775891a..82880c1fbae 100644 --- a/api/src/com/cloud/api/commands/UpdateHypervisorCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/config/UpdateHypervisorCapabilitiesCmd.java @@ -14,25 +14,21 @@ // 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 java.util.UUID; +package org.apache.cloudstack.api.command.admin.config; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.user.Account; - -@Implementation(description="Updates a hypervisor capabilities.", responseObject=ServiceOfferingResponse.class, since="3.0.0") +@APICommand(name = "updateHypervisorCapabilities", description="Updates a hypervisor capabilities.", responseObject=ServiceOfferingResponse.class, since="3.0.0") public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHypervisorCapabilitiesCmd.class.getName()); private static final String s_name = "updatehypervisorcapabilitiesresponse"; @@ -41,8 +37,8 @@ public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="hypervisor_capabilities") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the hypervisor capability") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HypervisorCapabilitiesResponse.class, + description="ID of the hypervisor capability") private Long id; @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="set true to enable security group for this hypervisor.") @@ -67,8 +63,6 @@ public class UpdateHypervisorCapabilitiesCmd extends BaseCmd { return maxGuestsLimit; } - - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/CreateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/CreateDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java index 92ee7ecefe9..0e6ae32583b 100644 --- a/api/src/com/cloud/api/commands/CreateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/CreateDomainCmd.java @@ -14,22 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a domain", responseObject=DomainResponse.class) +@APICommand(name = "createDomain", description="Creates a domain", responseObject=DomainResponse.class) public class CreateDomainCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateDomainCmd.class.getName()); @@ -42,8 +38,8 @@ public class CreateDomainCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="creates domain with this name") private String domainName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.PARENT_DOMAIN_ID, type=CommandType.LONG, description="assigns new domain a parent domain by domain ID of the parent. If no parent domain is specied, the ROOT domain is assumed.") + @Parameter(name=ApiConstants.PARENT_DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="assigns new domain a parent domain by domain ID of the parent. If no parent domain is specied, the ROOT domain is assumed.") private Long parentDomainId; @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for networks in the domain") @@ -63,7 +59,7 @@ public class CreateDomainCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; - } + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -73,12 +69,12 @@ public class CreateDomainCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Name: "+getDomainName()+((getParentDomainId()!=null)?", Parent DomainId :"+getParentDomainId():"")); diff --git a/api/src/com/cloud/api/commands/DeleteDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeleteDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java index 3908256a192..7009e70ca32 100644 --- a/api/src/com/cloud/api/commands/DeleteDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/DeleteDomainCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a specified domain", responseObject=SuccessResponse.class) +@APICommand(name = "deleteDomain", description="Deletes a specified domain", responseObject=SuccessResponse.class) public class DeleteDomainCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteDomainCmd.class.getName()); private static final String s_name = "deletedomainresponse"; @@ -40,8 +36,8 @@ public class DeleteDomainCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of domain to delete") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="ID of domain to delete") private Long id; @Parameter(name=ApiConstants.CLEANUP, type=CommandType.BOOLEAN, description="true if all domain resources (child domains, accounts) have to be cleaned up, false otherwise") @@ -88,7 +84,7 @@ public class DeleteDomainCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting domain: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ListDomainChildrenCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListDomainChildrenCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java index d5b3f6cbc44..4bc05d1c0f9 100644 --- a/api/src/com/cloud/api/commands/ListDomainChildrenCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainChildrenCmd.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.domain.Domain; +import com.cloud.utils.Pair; -@Implementation(description="Lists all children domains belonging to a specified domain", responseObject=DomainResponse.class) +@APICommand(name = "listDomainChildren", description="Lists all children domains belonging to a specified domain", responseObject=DomainResponse.class) public class ListDomainChildrenCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainChildrenCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListDomainChildrenCmd.class.getName()); private static final String s_name = "listdomainchildrenresponse"; @@ -40,16 +40,16 @@ public class ListDomainChildrenCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list children domain by parent domain ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list children domain by parent domain ID.") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list children domains by name") private String domainName; - + @Parameter(name=ApiConstants.IS_RECURSIVE, type=CommandType.BOOLEAN, description="to return the entire tree, use the value \"true\". To return the first level children, use the value \"false\".") private Boolean recursive; - + @Parameter(name=ApiConstants.LIST_ALL, type=CommandType.BOOLEAN, description="If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; @@ -64,11 +64,11 @@ public class ListDomainChildrenCmd extends BaseListCmd { public String getDomainName() { return domainName; } - + public boolean listAll() { return listAll == null ? false : listAll; } - + public boolean isRecursive() { return recursive == null ? false : recursive; } @@ -81,19 +81,19 @@ public class ListDomainChildrenCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _domainService.searchForDomainChildren(this); + Pair, Integer> result = _domainService.searchForDomainChildren(this); ListResponse response = new ListResponse(); List domainResponses = new ArrayList(); - for (Domain domain : result) { + for (Domain domain : result.first()) { DomainResponse domainResponse = _responseGenerator.createDomainResponse(domain); domainResponse.setObjectName("domain"); domainResponses.add(domainResponse); } - response.setResponses(domainResponses); + response.setResponses(domainResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListDomainsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListDomainsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java index 9cefe9b48dd..9b9e200abcd 100644 --- a/api/src/com/cloud/api/commands/ListDomainsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/ListDomainsCmd.java @@ -14,34 +14,34 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.domain.Domain; +import com.cloud.utils.Pair; -@Implementation(description="Lists domains and provides detailed information for listed domains", responseObject=DomainResponse.class) +@APICommand(name = "listDomains", description="Lists domains and provides detailed information for listed domains", responseObject=DomainResponse.class) public class ListDomainsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(ListDomainsCmd.class.getName()); + private static final String s_name = "listdomainsresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List domain by domain ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="List domain by domain ID.") private Long id; @Parameter(name=ApiConstants.LEVEL, type=CommandType.INTEGER, description="List domains by domain level.") @@ -49,7 +49,7 @@ public class ListDomainsCmd extends BaseListCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="List domain by domain name.") private String domainName; - + @Parameter(name=ApiConstants.LIST_ALL, type=CommandType.BOOLEAN, description="If set to false, list only resources belonging to the command's caller; if set to true - list resources that the caller is authorized to see. Default value is false") private Boolean listAll; @@ -68,7 +68,7 @@ public class ListDomainsCmd extends BaseListCmd { public String getDomainName() { return domainName; } - + public boolean listAll() { return listAll == null ? false : listAll; } @@ -84,16 +84,16 @@ public class ListDomainsCmd extends BaseListCmd { @Override public void execute(){ - List result = _domainService.searchForDomains(this); + Pair, Integer> result = _domainService.searchForDomains(this); ListResponse response = new ListResponse(); List domainResponses = new ArrayList(); - for (Domain domain : result) { + for (Domain domain : result.first()) { DomainResponse domainResponse = _responseGenerator.createDomainResponse(domain); domainResponse.setObjectName("domain"); domainResponses.add(domainResponse); } - response.setResponses(domainResponses); + response.setResponses(domainResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateDomainCmd.java b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateDomainCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java index 739ae87ca05..cc5926cace1 100644 --- a/api/src/com/cloud/api/commands/UpdateDomainCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/domain/UpdateDomainCmd.java @@ -14,22 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.domain; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import com.cloud.domain.Domain; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates a domain with a new name", responseObject=DomainResponse.class) +@APICommand(name = "updateDomain", description="Updates a domain with a new name", responseObject=DomainResponse.class) public class UpdateDomainCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateDomainCmd.class.getName()); private static final String s_name = "updatedomainresponse"; @@ -38,13 +34,13 @@ public class UpdateDomainCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of domain to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="ID of domain to update") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates domain with this name") private String domainName; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="Network domain for the domain's networks; empty string will update domainName with NULL value") private String networkDomain; @@ -59,7 +55,7 @@ public class UpdateDomainCmd extends BaseCmd { public String getDomainName() { return domainName; } - + public String getNetworkDomain() { return networkDomain; } @@ -72,12 +68,12 @@ public class UpdateDomainCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Domain Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/AddHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/AddHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java index a4646a26904..0a0a98c1c45 --- a/api/src/com/cloud/api/commands/AddHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddHostCmd.java @@ -14,37 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; -@Implementation(description="Adds a new host.", responseObject=HostResponse.class) +@APICommand(name = "addHost", description="Adds a new host.", responseObject=HostResponse.class) public class AddHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddHostCmd.class.getName()); private static final String s_name = "addhostresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="the cluster ID for the host") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="the cluster ID for the host") private Long clusterId; @Parameter(name=ApiConstants.CLUSTER_NAME, type=CommandType.STRING, description="the cluster name for the host") @@ -53,8 +55,8 @@ public class AddHostCmd extends BaseCmd { @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the password for the host") private String password; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, required=true, type=CommandType.LONG, description="the Pod ID for the host") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the host URL") @@ -63,13 +65,13 @@ public class AddHostCmd extends BaseCmd { @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host") private String username; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the host") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID for the host") private Long zoneId; - + @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, required=true, description="hypervisor type of the host") private String hypervisor; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Host for allocation of new resources") private String allocationState; @@ -107,33 +109,33 @@ public class AddHostCmd extends BaseCmd { public Long getZoneId() { return zoneId; } - + public String getHypervisor() { - return hypervisor; + return hypervisor; } - + public List getHostTags() { return hostTags; } - + public String getAllocationState() { - return allocationState; - } - + return allocationState; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { @@ -151,7 +153,7 @@ public class AddHostCmd extends BaseCmd { response.setResponses(hostResponses); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } catch (DiscoveryException ex) { s_logger.warn("Exception: ", ex); diff --git a/api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java index 04f84c148f2..579e286f884 100644 --- a/api/src/com/cloud/api/commands/AddSecondaryStorageCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/AddSecondaryStorageCmd.java @@ -14,28 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.DiscoveryException; import com.cloud.host.Host; import com.cloud.user.Account; -@Implementation(description="Adds secondary storage.", responseObject=HostResponse.class) +@APICommand(name = "addSecondaryStorage", description="Adds secondary storage.", responseObject=HostResponse.class) public class AddSecondaryStorageCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddSecondaryStorageCmd.class.getName()); private static final String s_name = "addsecondarystorageresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -43,8 +40,8 @@ public class AddSecondaryStorageCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL for the secondary storage") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the secondary storage") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID for the secondary storage") private Long zoneId; ///////////////////////////////////////////////////// @@ -65,14 +62,14 @@ public class AddSecondaryStorageCmd extends BaseCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/CancelMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java index def0c2d75cd..93dca9140f9 100644 --- a/api/src/com/cloud/api/commands/CancelMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/CancelMaintenanceCmd.java @@ -14,25 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Cancels host maintenance.", responseObject=HostResponse.class) +@APICommand(name = "cancelHostMaintenance", description="Cancels host maintenance.", responseObject=HostResponse.class) public class CancelMaintenanceCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CancelMaintenanceCmd.class.getName()); @@ -42,11 +41,10 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=HostResponse.class, + required=true, description="the host ID") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +53,6 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,9 +61,9 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -88,17 +85,17 @@ public class CancelMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "canceling maintenance for host: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ Host result = _resourceService.cancelMaintenance(this); diff --git a/api/src/com/cloud/api/commands/DeleteHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java index 60e61b99f30..5103f986e10 100644 --- a/api/src/com/cloud/api/commands/DeleteHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/DeleteHostCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description = "Deletes a host.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteHost", description = "Deletes a host.", responseObject = SuccessResponse.class) public class DeleteHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteHostCmd.class.getName()); @@ -37,13 +37,13 @@ public class DeleteHostCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the host ID") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = HostResponse.class, + required = true, description = "the host ID") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, description = "Force delete the host. All HA enabled vms running on the host will be put to HA; HA disabled ones will be stopped") private Boolean forced; - + @Parameter(name = ApiConstants.FORCED_DESTROY_LOCAL_STORAGE, type = CommandType.BOOLEAN, description = "Force destroy local storage on this host. All VMs created on this local storage will be destroyed") private Boolean forceDestroyLocalStorage; @@ -58,7 +58,7 @@ public class DeleteHostCmd extends BaseCmd { public boolean isForced() { return (forced != null) ? forced : false; } - + public boolean isForceDestoryLocalStorage() { return (forceDestroyLocalStorage != null) ? forceDestroyLocalStorage : true; } @@ -87,4 +87,4 @@ public class DeleteHostCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete host"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListHostsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java old mode 100755 new mode 100644 similarity index 65% rename from api/src/com/cloud/api/commands/ListHostsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java index 87f13302a97..82f329f4b7e --- a/api/src/com/cloud/api/commands/ListHostsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/ListHostsCmd.java @@ -14,28 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.utils.Pair; -@Implementation(description="Lists hosts.", responseObject=HostResponse.class) +@APICommand(name = "listHosts", description="Lists hosts.", responseObject=HostResponse.class) public class ListHostsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListHostsCmd.class.getName()); @@ -45,19 +48,19 @@ public class ListHostsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="lists hosts existing in particular cluster") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + description="lists hosts existing in particular cluster") private Long clusterId; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the host") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + description="the id of the host") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the host") private String hostName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID for the host") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID for the host") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the host") @@ -66,23 +69,23 @@ public class ListHostsCmd extends BaseListCmd { @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the host type") private String type; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the host") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID for the host") private Long zoneId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=false, description="lists hosts in the same cluster as this VM and flag hosts with enough CPU/RAm to host this VM") private Long virtualMachineId; - + @Parameter(name=ApiConstants.RESOURCE_STATE, type=CommandType.STRING, description="list hosts by resource state. Resource state represents current state determined by admin of host, valule can be one of [Enabled, Disabled, Unmanaged, PrepareForMaintenance, ErrorInMaintenance, Maintenance, Error]") - private String resourceState; - + private String resourceState; + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, value can be a list of [ min, all, capacity, events, stats]" ) private List viewDetails; - + @Parameter(name=ApiConstants.HA_HOST, type=CommandType.BOOLEAN, description="if true, list only hosts dedicated to HA") private Boolean haHost; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -110,7 +113,7 @@ public class ListHostsCmd extends BaseListCmd { public String getType() { return type; } - + public Boolean getHaHost() { return haHost; } @@ -122,7 +125,7 @@ public class ListHostsCmd extends BaseListCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -142,9 +145,9 @@ public class ListHostsCmd extends BaseListCmd { } return dv; } - + public String getResourceState() { - return resourceState; + return resourceState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -154,39 +157,42 @@ public class ListHostsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } @Override public void execute(){ - List result = new ArrayList(); - List hostsWithCapacity = new ArrayList(); - - if(getVirtualMachineId() != null){ - Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), this.getStartIndex(), this.getPageSizeVal()); + ListResponse response = null; + if (getVirtualMachineId() == null) { + response = _queryService.searchForServers(this); + } else { + List result = new ArrayList(); + List hostsWithCapacity = new ArrayList(); + + Pair, List> hostsForMigration = _mgr.listHostsForMigrationOfVM(getVirtualMachineId(), + this.getStartIndex(), this.getPageSizeVal()); result = hostsForMigration.first(); hostsWithCapacity = hostsForMigration.second(); - }else{ - result = _mgr.searchForServers(this); - } - ListResponse response = new ListResponse(); - List hostResponses = new ArrayList(); - for (Host host : result) { - HostResponse hostResponse = _responseGenerator.createHostResponse(host, getDetails()); - Boolean suitableForMigration = false; - if(hostsWithCapacity.contains(host)){ - suitableForMigration = true; + response = new ListResponse(); + List hostResponses = new ArrayList(); + for (Host host : result) { + HostResponse hostResponse = _responseGenerator.createHostResponse(host, getDetails()); + Boolean suitableForMigration = false; + if (hostsWithCapacity.contains(host)) { + suitableForMigration = true; + } + hostResponse.setSuitableForMigration(suitableForMigration); + hostResponse.setObjectName("host"); + hostResponses.add(hostResponse); } - hostResponse.setSuitableForMigration(suitableForMigration); - hostResponse.setObjectName("host"); - hostResponses.add(hostResponse); - } - response.setResponses(hostResponses); + response.setResponses(hostResponses); + } response.setResponseName(getCommandName()); this.setResponseObject(response); + } } diff --git a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java index 5a4abd0c244..385e2aef415 100644 --- a/api/src/com/cloud/api/commands/PrepareForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/PrepareForMaintenanceCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Prepares a host for maintenance.", responseObject=HostResponse.class) +@APICommand(name = "prepareHostForMaintenance", description="Prepares a host for maintenance.", responseObject=HostResponse.class) public class PrepareForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PrepareForMaintenanceCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(PrepareForMaintenanceCmd.class.getName()); + private static final String s_name = "preparehostformaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the host ID") private Long id; ///////////////////////////////////////////////////// @@ -62,9 +61,9 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -86,17 +85,17 @@ public class PrepareForMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "preparing host: " + getId() + " for maintenance"; } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ Host result = _resourceService.maintain(this); diff --git a/api/src/com/cloud/api/commands/ReconnectHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/ReconnectHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java index b74ac70f882..99e867bbebd --- a/api/src/com/cloud/api/commands/ReconnectHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/ReconnectHostCmd.java @@ -14,28 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; -import com.cloud.exception.AgentUnavailableException; import com.cloud.host.Host; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Reconnects a host.", responseObject=HostResponse.class) +@APICommand(name = "reconnectHost", description="Reconnects a host.", responseObject=HostResponse.class) public class ReconnectHostCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ReconnectHostCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ReconnectHostCmd.class.getName()); private static final String s_name = "reconnecthostresponse"; @@ -43,8 +41,8 @@ public class ReconnectHostCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the host ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the host ID") private Long id; ///////////////////////////////////////////////////// @@ -63,9 +61,9 @@ public class ReconnectHostCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "host"; + return "host"; } @Override @@ -87,15 +85,15 @@ public class ReconnectHostCmd extends BaseAsyncCmd { public String getEventDescription() { return "reconnecting host: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Host; + return AsyncJob.Type.Host; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/UpdateHostCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/UpdateHostCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java index fae596f9015..9ab27178838 --- a/api/src/com/cloud/api/commands/UpdateHostCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.HostResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; +import org.apache.cloudstack.api.response.HostResponse; import com.cloud.host.Host; import com.cloud.user.Account; -import com.cloud.utils.fsm.NoTransitionException; -@Implementation(description="Updates a host.", responseObject=HostResponse.class) +@APICommand(name = "updateHost", description="Updates a host.", responseObject=HostResponse.class) public class UpdateHostCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHostCmd.class.getName()); private static final String s_name = "updatehostresponse"; @@ -40,12 +39,12 @@ public class UpdateHostCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the host to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required=true, description="the ID of the host to update") private Long id; - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.LONG, description="the id of Os category to update the host with") + @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="the id of Os category to update the host with") private Long osCategoryId; @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Change resource state of host, valid values are [Enable, Disable]. Operation may failed if host in states not allowing Enable/Disable") @@ -53,7 +52,7 @@ public class UpdateHostCmd extends BaseCmd { @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="list of tags to be added to the host") private List hostTags; - + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="the new uri for the secondary storage: nfs://host/path") private String url; @@ -75,10 +74,10 @@ public class UpdateHostCmd extends BaseCmd { public List getHostTags() { return hostTags; - } - + } + public String getUrl() { - return url; + return url; } ///////////////////////////////////////////////////// @@ -103,13 +102,13 @@ public class UpdateHostCmd extends BaseCmd { public void execute(){ Host result; try { - result = _resourceService.updateHost(this); + result = _resourceService.updateHost(this); HostResponse hostResponse = _responseGenerator.createHostResponse(result); hostResponse.setResponseName(getCommandName()); this.setResponseObject(hostResponse); } catch (Exception e) { - s_logger.debug("Failed to update host:" + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); + s_logger.debug("Failed to update host:" + getId(), e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update host:" + getId() + "," + e.getMessage()); } } } diff --git a/api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java index 426b51c0ed0..dd9e4559b9d 100644 --- a/api/src/com/cloud/api/commands/UpdateHostPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/host/UpdateHostPasswordCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.host; import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description = "Update password of a host/pool on management server.", responseObject = SuccessResponse.class) +@APICommand(name = "updateHostPassword", description = "Update password of a host/pool on management server.", responseObject = SuccessResponse.class) public class UpdateHostPasswordCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateHostPasswordCmd.class.getName()); @@ -37,18 +37,17 @@ public class UpdateHostPasswordCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - // TO DO - this is of no use currently. Probably need to remove it. - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID") private Long hostId; - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="the cluster ID") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType=ClusterResponse.class, + description="the cluster ID") private Long clusterId; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="the username for the host/cluster") private String username; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="the new password for the host/cluster") private String password; @@ -59,7 +58,7 @@ public class UpdateHostPasswordCmd extends BaseCmd { public Long getHostId() { return hostId; } - + public Long getClusterId() { return clusterId; } @@ -71,7 +70,7 @@ public class UpdateHostPasswordCmd extends BaseCmd { public String getUsername() { return username; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -92,4 +91,4 @@ public class UpdateHostPasswordCmd extends BaseCmd { _resourceService.updateHostPassword(this); this.setResponseObject(new SuccessResponse(getCommandName())); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/LDAPConfigCmd.java b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java similarity index 91% rename from api/src/com/cloud/api/commands/LDAPConfigCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java index d7ff5b5a8de..b71ba73405f 100644 --- a/api/src/com/cloud/api/commands/LDAPConfigCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPConfigCmd.java @@ -14,26 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.ldap; import javax.naming.NamingException; import org.apache.log4j.Logger; -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.LDAPConfigResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.LDAPConfigResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Configure the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.0") +@APICommand(name = "ldapConfig", description="Configure the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.0") public class LDAPConfigCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LDAPConfigCmd.class.getName()); @@ -45,10 +45,10 @@ public class LDAPConfigCmd extends BaseCmd { @Parameter(name=ApiConstants.HOST_NAME, type=CommandType.STRING, required=true, description="Hostname or ip address of the ldap server eg: my.ldap.com") private String hostname; - + @Parameter(name=ApiConstants.PORT, type=CommandType.INTEGER, description="Specify the LDAP port if required, default is 389.") private Integer port=0; - + @Parameter(name=ApiConstants.USE_SSL, type=CommandType.BOOLEAN, description="Check Use SSL if the external LDAP server is configured for LDAP over SSL.") private Boolean useSSL; @@ -60,10 +60,10 @@ public class LDAPConfigCmd extends BaseCmd { @Parameter(name=ApiConstants.BIND_DN, type=CommandType.STRING, description="Specify the distinguished name of a user with the search permission on the directory.") private String bindDN; - + @Parameter(name=ApiConstants.BIND_PASSWORD, type=CommandType.STRING, description="Enter the password.") private String bindPassword; - + @Parameter(name=ApiConstants.TRUST_STORE, type=CommandType.STRING, description="Enter the path to trust certificates store.") private String trustStore; @@ -132,14 +132,14 @@ public class LDAPConfigCmd extends BaseCmd { catch (NamingException ne){ ne.printStackTrace(); } - + } @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/LDAPRemoveCmd.java b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/LDAPRemoveCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java index 43d9a0a399c..6bf5f4ff851 100644 --- a/api/src/com/cloud/api/commands/LDAPRemoveCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/ldap/LDAPRemoveCmd.java @@ -14,28 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.ldap; -import javax.naming.NamingException; - +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -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.BaseResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.LDAPRemoveResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LDAPRemoveResponse; import com.cloud.user.Account; -@Implementation(description="Remove the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.1") +@APICommand(name = "ldapRemove", description="Remove the LDAP context for this site.", responseObject=LDAPConfigResponse.class, since="3.0.1") public class LDAPRemoveCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LDAPRemoveCmd.class.getName()); @@ -45,12 +35,12 @@ public class LDAPRemoveCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,10 +50,10 @@ public class LDAPRemoveCmd extends BaseCmd { public void execute(){ boolean result = _configService.removeLDAP(this); if (result){ - LDAPRemoveResponse lr = new LDAPRemoveResponse(); + LDAPRemoveResponse lr = new LDAPRemoveResponse(); lr.setObjectName("ldapremove"); lr.setResponseName(getCommandName()); - this.setResponseObject(lr); + this.setResponseObject(lr); } } @@ -71,7 +61,7 @@ public class LDAPRemoveCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java new file mode 100644 index 00000000000..3e1d74df405 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkDeviceCmd.java @@ -0,0 +1,95 @@ +// 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 org.apache.cloudstack.api.command.admin.network; + +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import com.cloud.server.ManagementService; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "addNetworkDevice", description="Adds a network device of one of the following types: ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer", responseObject = NetworkDeviceResponse.class) +public class AddNetworkDeviceCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(AddNetworkDeviceCmd.class); + private static final String s_name = "addnetworkdeviceresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") + private String type; + + @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") + private Map paramList; + + + public String getDeviceType() { + return type; + } + + public Map getParamList() { + return paramList; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + Host device = nwDeviceMgr.addNetworkDevice(this); + NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(device); + response.setObjectName("networkdevice"); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + // TODO Auto-generated method stub + return 0; + } + +} diff --git a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java index 1e4339766c0..b6518d8eb59 100644 --- a/api/src/com/cloud/api/commands/AddNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/AddNetworkServiceProviderCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -35,7 +35,7 @@ import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "addNetworkServiceProvider", description="Adds a network serviceProvider to a physical network", responseObject=ProviderResponse.class, since="3.0.0") public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddNetworkServiceProviderCmd.class.getName()); @@ -44,18 +44,18 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID to add the provider to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID to add the provider to") private Long physicalNetworkId; - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.DEST_PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the destination Physical Network ID to bridge to") + @Parameter(name=ApiConstants.DEST_PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="the destination Physical Network ID to bridge to") private Long destinationPhysicalNetworkId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name for the physical network service provider") private String name; - + @Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider") private List enabledServices; @@ -67,7 +67,7 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getPhysicalNetworkId() { return physicalNetworkId; } @@ -92,12 +92,12 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network ServiceProvider Id: "+getEntityId()); @@ -118,19 +118,19 @@ public class AddNetworkServiceProviderCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add service provider entity to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_SERVICE_PROVIDER_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network ServiceProvider: " + getEntityId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java index 748f96eb263..b97f85ec1ba 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateNetworkOfferingCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.Collection; @@ -23,15 +23,12 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Service; @@ -39,7 +36,7 @@ import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; import com.cloud.user.Account; -@Implementation(description="Creates a network offering.", responseObject=NetworkOfferingResponse.class, since="3.0.0") +@APICommand(name = "createNetworkOffering", description="Creates a network offering.", responseObject=NetworkOfferingResponse.class, since="3.0.0") public class CreateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateNetworkOfferingCmd.class.getName()); private static final String _name = "createnetworkofferingresponse"; @@ -50,55 +47,55 @@ public class CreateNetworkOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the traffic type for the network offering. Supported type in current release is GUEST only") private String traffictype; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the network offering.", length=4096) - private String tags; - + private String tags; + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="true if network offering supports vlans") - private Boolean specifyVlan; - + private Boolean specifyVlan; + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Optional") - private String availability; - + private String availability; + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed") private Integer networkRate; - + @Parameter(name=ApiConstants.CONSERVE_MODE, type=CommandType.BOOLEAN, description="true if the network offering is IP conserve mode enabled") private Boolean conserveMode; - - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, description="the service offering ID used by virtual router provider") + + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the service offering ID used by virtual router provider") private Long serviceOfferingId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, required=true, description="guest type of the network offering: Shared or Isolated") private String guestIptype; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the network offering") private List supportedServices; - + @Parameter(name = ApiConstants.SERVICE_PROVIDER_LIST, type = CommandType.MAP, description = "provider to service mapping. If not specified, the provider for the service will be mapped to the default provider on the physical network") private Map serviceProviderList; @Parameter(name = ApiConstants.SERVICE_CAPABILITY_LIST, type = CommandType.MAP, description = "desired service capabilities as part of network offering") private Map serviceCapabilitystList; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to false if not specified") private Boolean specifyIpRanges; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } @@ -110,7 +107,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getTraffictype() { return traffictype; } - + public Boolean getSpecifyVlan() { return specifyVlan == null ? false : specifyVlan; } @@ -118,7 +115,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getAvailability() { return availability == null ? Availability.Optional.toString() : availability; } - + public Integer getNetworkRate() { return networkRate; } @@ -130,18 +127,18 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public Long getServiceOfferingId() { return serviceOfferingId; } - - public List getSupportedServices() { - return supportedServices; - } - public String getGuestIpType() { + public List getSupportedServices() { + return supportedServices; + } + + public String getGuestIpType() { return guestIptype; } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges == null ? false : specifyIpRanges; - } + + public Boolean getSpecifyIpRanges() { + return specifyIpRanges == null ? false : specifyIpRanges; + } public Boolean getConserveMode() { if (conserveMode == null) { @@ -170,7 +167,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { serviceProviderMap.put(service, providerList); } } - + return serviceProviderMap; } @@ -199,7 +196,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { if (svc.equalsIgnoreCase(service.getName())) { capabilityMap.put(capability, capabilityValue); } else { - //throw new InvalidParameterValueException("Service is not equal ") + //throw new InvalidParameterValueException("Service is not equal ") } } } @@ -214,7 +211,7 @@ public class CreateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java index 537b9bec56d..dd3f3231351 100644 --- a/api/src/com/cloud/api/commands/CreatePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreatePhysicalNetworkCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -35,7 +36,7 @@ import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "createPhysicalNetwork", description="Creates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePhysicalNetworkCmd.class.getName()); @@ -44,9 +45,9 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the physical network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType= ZoneResponse.class, + required=true, description="the Zone ID for the physical network") private Long zoneId; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") @@ -55,25 +56,25 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") private String speed; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a physical network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="domain ID of the account owning a physical network") private Long domainId; - + @Parameter(name=ApiConstants.BROADCAST_DOMAIN_RANGE, type=CommandType.STRING, description="the broadcast domain range for the physical network[Pod or Zone]. In Acton release it can be Zone only in Advance zone, and Pod in Basic") private String broadcastDomainRange; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") private List tags; - + @Parameter(name=ApiConstants.ISOLATION_METHODS, type=CommandType.LIST, collectionType=CommandType.STRING, description="the isolation method for the physical network[VLAN/L3/GRE]") private List isolationMethods; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the physical network") private String networkName; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public List getTags() { return tags; } @@ -102,25 +103,25 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public List getIsolationMethods() { return isolationMethods; } - + public String getNetworkSpeed() { return speed; } - + public String getNetworkName() { - return networkName; - } - - @Override + return networkName; + } + + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_CREATE; @@ -140,7 +141,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating Physical Network. Id: "+getEntityId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -167,7 +168,7 @@ public class CreatePhysicalNetworkCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create physical network entity"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java new file mode 100644 index 00000000000..ccd92e19d67 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/CreateStorageNetworkIpRangeCmd.java @@ -0,0 +1,127 @@ +// 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 org.apache.cloudstack.api.command.admin.network; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; + +@APICommand(name = "createStorageNetworkIpRange", description="Creates a Storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +public class CreateStorageNetworkIpRangeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(CreateStorageNetworkIpRangeCmd.class); + + private static final String s_name = "createstoragenetworkiprangeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="UUID of pod where the ip range belongs to") + private Long podId; + + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address") + private String startIp; + + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") + private String endIp; + + @Parameter(name = ApiConstants.VLAN, type = CommandType.INTEGER, description = "Optional. The vlan the ip range sits on, default to Null when it is not specificed which means you network is not on any Vlan. This is mainly for Vmware as other hypervisors can directly reterive bridge from pyhsical network traffic type table") + private Integer vlan; + + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for storage network") + private String netmask; + + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for storage network") + private String gateway; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getEndIp() { + return endIp; + } + + public Long getPodId() { + return podId; + } + + public String getStartIp() { + return startIp; + } + + public Integer getVlan() { + return vlan; + } + + public String getNetmask() { + return netmask; + } + + public String getGateWay() { + return gateway; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_CREATE; + } + + @Override + public String getEventDescription() { + return "Creating storage ip range from " + getStartIp() + " to " + getEndIp() + " with vlan " + getVlan(); + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + StorageNetworkIpRange result = _storageNetworkService.createIpRange(this); + StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Create storage network IP range failed", e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java new file mode 100644 index 00000000000..09451242daf --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkDeviceCmd.java @@ -0,0 +1,89 @@ +// 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 org.apache.cloudstack.api.command.admin.network; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.server.ManagementService; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "deleteNetworkDevice", description="Deletes network device.", responseObject=SuccessResponse.class) +public class DeleteNetworkDeviceCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(DeleteNetworkDeviceCmd.class); + private static final String s_name = "deletenetworkdeviceresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = HostResponse.class, + required=true, description = "Id of network device to delete") + private Long id; + + public Long getId() { + return id; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + boolean result = nwDeviceMgr.deleteNetworkDevice(this); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network device:" + getId()); + } + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + // TODO Auto-generated method stub + return 0; + } + +} diff --git a/api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java index 9d60e34e201..c13088f6123 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkOfferingCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes a network offering.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteNetworkOffering", description="Deletes a network offering.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteNetworkOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteNetworkOfferingCmd.class.getName()); private static final String s_name = "deletenetworkofferingresponse"; @@ -36,11 +36,10 @@ public class DeleteNetworkOfferingCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + required=true, description="the ID of the network offering") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -58,12 +57,12 @@ public class DeleteNetworkOfferingCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteNetworkOffering(this); diff --git a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java index 815657bd9dc..bc744399a33 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteNetworkServiceProviderCmd.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteNetworkServiceProvider", description="Deletes a Network Service Provider.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetworkServiceProviderCmd.class.getName()); @@ -41,11 +41,10 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network_service_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network service provider") - private Long id; + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProviderResponse.class, + required=true, description="the ID of the network service provider") + private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -55,7 +54,6 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +62,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -86,7 +84,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } + } } @@ -100,7 +98,7 @@ public class DeleteNetworkServiceProviderCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Physical network ServiceProvider: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java index c2814386a36..5f86efa9ad8 100644 --- a/api/src/com/cloud/api/commands/DeletePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeletePhysicalNetworkCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Physical Network.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deletePhysicalNetwork", description="Deletes a Physical Network.", responseObject=SuccessResponse.class, since="3.0.0") public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePhysicalNetworkCmd.class.getName()); @@ -40,11 +36,10 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Physical network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="the ID of the Physical network") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,7 +48,6 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -62,7 +56,7 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -85,12 +79,12 @@ public class DeletePhysicalNetworkCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Physical network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_DELETE; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java old mode 100755 new mode 100644 similarity index 50% rename from api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java index cfecd5e1f84..1873fc7d6ef --- a/api/src/com/cloud/api/commands/DeleteStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/DeleteStorageNetworkIpRangeCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,20 +29,20 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Deletes a storage network IP Range.", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteStorageNetworkIpRange", description="Deletes a storage network IP Range.", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteStorageNetworkIpRangeCmd.class); - - private static final String s_name = "deletestoragenetworkiprangeresponse"; - + public static final Logger s_logger = Logger.getLogger(DeleteStorageNetworkIpRangeCmd.class); + + private static final String s_name = "deletestoragenetworkiprangeresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the uuid of the storage network ip range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + required=true, description="the uuid of the storage network ip range") private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,38 +50,38 @@ public class DeleteStorageNetworkIpRangeCmd extends BaseAsyncCmd { public Long getId() { return id; } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_DELETE; - } - @Override - public String getEventDescription() { - return "Deleting storage ip range " + getId(); - } + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_DELETE; + } - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - _storageNetworkService.deleteIpRange(this); + @Override + public String getEventDescription() { + return "Deleting storage ip range " + getId(); + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + _storageNetworkService.deleteIpRange(this); SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Failed to delete storage network ip range " + getId(), e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } - } + } catch (Exception e) { + s_logger.warn("Failed to delete storage network ip range " + getId(), e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } } diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java new file mode 100644 index 00000000000..742ff1f74af --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkDeviceCmd.java @@ -0,0 +1,99 @@ +// 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 org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.host.Host; +import com.cloud.server.ManagementService; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; + +@APICommand(name = "listNetworkDevice", description="List network devices", responseObject = NetworkDeviceResponse.class) +public class ListNetworkDeviceCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListNetworkDeviceCmd.class); + private static final String s_name = "listnetworkdevice"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") + private String type; + + @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") + private Map paramList; + + public String getDeviceType() { + return type; + } + + public Map getParamList() { + return paramList; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + ExternalNetworkDeviceManager nwDeviceMgr; + ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); + nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); + List devices = nwDeviceMgr.listNetworkDevice(this); + List nwdeviceResponses = new ArrayList(); + ListResponse listResponse = new ListResponse(); + for (Host d : devices) { + NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(d); + response.setObjectName("networkdevice"); + response.setResponseName(getCommandName()); + nwdeviceResponses.add(response); + } + + listResponse.setResponses(nwdeviceResponses); + listResponse.setResponseName(getCommandName()); + this.setResponseObject(listResponse); + } catch (InvalidParameterValueException ipve) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); + } catch (CloudRuntimeException cre) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + +} diff --git a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java index c973b35b711..06a0518af20 100644 --- a/api/src/com/cloud/api/commands/ListNetworkServiceProvidersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListNetworkServiceProvidersCmd.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; +import com.cloud.utils.Pair; - -@Implementation(description="Lists network serviceproviders for a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "listNetworkServiceProviders", description="Lists network serviceproviders for a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") public class ListNetworkServiceProvidersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkServiceProvidersCmd.class.getName()); private static final String _name = "listnetworkserviceprovidersresponse"; @@ -40,21 +40,21 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list providers by name") private String name; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list providers by state") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } @@ -64,14 +64,14 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { } public String getName() { - return name; - } + return name; + } - public String getState() { - return state; - } + public String getState() { + return state; + } - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override @@ -83,18 +83,19 @@ public class ListNetworkServiceProvidersCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - List serviceProviders = _networkService.listNetworkServiceProviders(getPhysicalNetworkId(), getName(), getState(), this.getStartIndex(), this.getPageSizeVal()); + Pair, Integer> serviceProviders = _networkService.listNetworkServiceProviders(getPhysicalNetworkId(), + getName(), getState(), this.getStartIndex(), this.getPageSizeVal()); ListResponse response = new ListResponse(); List serviceProvidersResponses = new ArrayList(); - for (PhysicalNetworkServiceProvider serviceProvider : serviceProviders) { + for (PhysicalNetworkServiceProvider serviceProvider : serviceProviders.first()) { ProviderResponse serviceProviderResponse = _responseGenerator.createNetworkServiceProviderResponse(serviceProvider); serviceProvidersResponses.add(serviceProviderResponse); } - response.setResponses(serviceProvidersResponses); + response.setResponses(serviceProvidersResponses, serviceProviders.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java index e1ec427d718..a301ac004ea 100644 --- a/api/src/com/cloud/api/commands/ListPhysicalNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListPhysicalNetworksCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; +import com.cloud.utils.Pair; -@Implementation(description="Lists physical networks", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "listPhysicalNetworks", description="Lists physical networks", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class ListPhysicalNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListPhysicalNetworksCmd.class.getName()); @@ -42,22 +43,22 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list physical network by id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + description="list physical network by id") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the physical network") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID for the physical network") private Long zoneId; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="search by name") private String networkName; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -65,11 +66,11 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getNetworkName() { - return networkName; + return networkName; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -78,23 +79,24 @@ public class ListPhysicalNetworksCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - List result = _networkService.searchPhysicalNetworks(getId(),getZoneId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getNetworkName()); + Pair, Integer> result = _networkService.searchPhysicalNetworks(getId(),getZoneId(), + this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getNetworkName()); if (result != null) { ListResponse response = new ListResponse(); List networkResponses = new ArrayList(); - for (PhysicalNetwork network : result) { + for (PhysicalNetwork network : result.first()) { PhysicalNetworkResponse networkResponse = _responseGenerator.createPhysicalNetworkResponse(network); networkResponses.add(networkResponse); } - response.setResponses(networkResponses); + response.setResponses(networkResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); }else { diff --git a/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java new file mode 100644 index 00000000000..8fcaf4958b1 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListStorageNetworkIpRangeCmd.java @@ -0,0 +1,105 @@ +// 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 org.apache.cloudstack.api.command.admin.network; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import com.cloud.dc.StorageNetworkIpRange; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; + +@APICommand(name = "listStorageNetworkIpRange", description="List a storage network IP range.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +public class ListStorageNetworkIpRangeCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListStorageNetworkIpRangeCmd.class); + + String s_name = "liststoragenetworkiprangeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + description="optional parameter. Storaget network IP range uuid, if specicied, using it to search the range.") + private Long rangeId; + + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="optional parameter. Pod uuid, if specicied and range uuid is absent, using it to search the range.") + private Long podId; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="optional parameter. Zone uuid, if specicied and both pod uuid and range uuid are absent, using it to search the range.") + private Long zoneId; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public Long getRangeId() { + return rangeId; + } + + public Long getPodId() { + return podId; + } + + public Long getZoneId() { + return zoneId; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + List results = _storageNetworkService.listIpRange(this); + ListResponse response = new ListResponse(); + List resList = new ArrayList(results.size()); + for (StorageNetworkIpRange r : results) { + StorageNetworkIpRangeResponse resp = _responseGenerator.createStorageNetworkIpRangeResponse(r); + resList.add(resp); + } + response.setResponses(resList); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Failed to list storage network ip range for rangeId=" + getRangeId() + " podId=" + getPodId() + " zoneId=" + getZoneId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } + +} diff --git a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java index ef949da8fa3..f7407a108e0 100644 --- a/api/src/com/cloud/api/commands/ListSupportedNetworkServicesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/ListSupportedNetworkServicesCmd.java @@ -14,44 +14,44 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ServiceResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; import com.cloud.network.Network.Service; import com.cloud.user.Account; -@Implementation(description="Lists all network services provided by CloudStack or for the given Provider.", responseObject=ServiceResponse.class, since="3.0.0") +@APICommand(name = "listSupportedNetworkServices", description="Lists all network services provided by CloudStack or for the given Provider.", responseObject=ServiceResponse.class, since="3.0.0") public class ListSupportedNetworkServicesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSupportedNetworkServicesCmd.class.getName()); private static final String _name = "listsupportednetworkservicesresponse"; - + @Parameter(name=ApiConstants.PROVIDER, type=CommandType.STRING, description="network service provider name") private String providerName; - + @Parameter(name=ApiConstants.SERVICE, type=CommandType.STRING, description="network service name to list providers and capabilities of") private String serviceName; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setProviderName(String providerName) { this.providerName = providerName; @@ -78,10 +78,10 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - List services; + List services; if(getServiceName() != null){ Network.Service service = null; if(serviceName != null){ @@ -96,14 +96,14 @@ public class ListSupportedNetworkServicesCmd extends BaseListCmd { }else{ services = _networkService.listNetworkServices(getProviderName()); } - + ListResponse response = new ListResponse(); List servicesResponses = new ArrayList(); for (Network.Service service : services) { - //skip gateway service - if (service == Service.Gateway) { - continue; - } + //skip gateway service + if (service == Service.Gateway) { + continue; + } ServiceResponse serviceResponse = _responseGenerator.createNetworkServiceResponse(service); servicesResponses.add(serviceResponse); } diff --git a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java index c30361944cb..dc2f3099206 --- a/api/src/com/cloud/api/commands/UpdateNetworkOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkOfferingCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; -@Implementation(description="Updates a network offering.", responseObject=NetworkOfferingResponse.class) +@APICommand(name = "updateNetworkOffering", description="Updates a network offering.", responseObject=NetworkOfferingResponse.class) public class UpdateNetworkOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkOfferingCmd.class.getName()); private static final String _name = "updatenetworkofferingresponse"; @@ -36,21 +32,21 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the network offering") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=NetworkOfferingResponse.class, + description="the id of the network offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the network offering") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the network offering") private String displayText; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering." + - " Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering") + " Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering") private String availability; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the network offering, integer") private Integer sortKey; @@ -60,15 +56,15 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } @@ -80,9 +76,9 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { public String getState() { return state; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } ///////////////////////////////////////////////////// @@ -92,7 +88,7 @@ public class UpdateNetworkOfferingCmd extends BaseCmd { public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java index bd52f35c48b..b770ea26c12 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkServiceProviderCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateNetworkServiceProviderCmd.java @@ -14,26 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProviderResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.user.Account; -@Implementation(description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "updateNetworkServiceProvider", description="Updates a network serviceProvider of a physical network", responseObject=ProviderResponse.class, since="3.0.0") public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkServiceProviderCmd.class.getName()); @@ -44,14 +43,14 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled/Shutdown the physical network service provider") private String state; - - @IdentityMapper(entityTableName="physical_network_service_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="network service provider id") - private Long id; + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProviderResponse.class, + required=true, description="network service provider id") + private Long id; @Parameter(name=ApiConstants.SERVICE_LIST, type=CommandType.LIST, collectionType = CommandType.STRING, description="the list of services to be enabled for this physical network service provider") private List enabledServices; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -59,14 +58,14 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getState() { return state; } - + private Long getId() { return id; - } - + } + public List getEnabledServices() { return enabledServices; - } + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -75,12 +74,12 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetworkServiceProvider result = _networkService.updateNetworkServiceProvider(getId(), getState(), getEnabledServices()); @@ -102,7 +101,7 @@ public class UpdateNetworkServiceProviderCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating physical network ServiceProvider: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetworkServiceProvider; diff --git a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java index a6abc039042..d9a3e044c73 100644 --- a/api/src/com/cloud/api/commands/UpdatePhysicalNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdatePhysicalNetworkCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetwork; import com.cloud.user.Account; -@Implementation(description="Updates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") +@APICommand(name = "updatePhysicalNetwork", description="Updates a physical network", responseObject=PhysicalNetworkResponse.class, since="3.0.0") public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdatePhysicalNetworkCmd.class.getName()); @@ -40,8 +39,8 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="physical network id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PhysicalNetworkResponse.class, + required=true, description="physical network id") private Long id; @Parameter(name=ApiConstants.NETWORK_SPEED, type=CommandType.STRING, description="the speed for the physical network[1G/10G]") @@ -49,17 +48,17 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="Tag the physical network") private List tags; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="Enabled/Disabled") private String state; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the VLAN for the physical network") private String vlan; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public List getTags() { return tags; } @@ -67,7 +66,7 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getNetworkSpeed() { return speed; } - + public String getState() { return state; } @@ -79,7 +78,7 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getVlan() { return vlan; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -88,12 +87,12 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetwork result = _networkService.updatePhysicalNetwork(getId(),getNetworkSpeed(), getTags(), getVlan(), getState()); @@ -106,12 +105,12 @@ public class UpdatePhysicalNetworkCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating Physical network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PHYSICAL_NETWORK_UPDATE; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PhysicalNetwork; diff --git a/api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java old mode 100755 new mode 100644 similarity index 53% rename from api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java index 7e0b05bad23..d6d0b92e4b7 --- a/api/src/com/cloud/api/commands/UpdateStorageNetworkIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/network/UpdateStorageNetworkIpRangeCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,30 +29,30 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Update a Storage network IP range, only allowed when no IPs in this range have been allocated.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") +@APICommand(name = "updateStorageNetworkIpRange", description="Update a Storage network IP range, only allowed when no IPs in this range have been allocated.", responseObject=StorageNetworkIpRangeResponse.class, since="3.0.0") public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UpdateStorageNetworkIpRangeCmd.class); - private static final String s_name = "updatestoragenetworkiprangeresponse"; - + public static final Logger s_logger = Logger.getLogger(UpdateStorageNetworkIpRangeCmd.class); + private static final String s_name = "updatestoragenetworkiprangeresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="dc_storage_network_ip_range") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="UUID of storage network ip range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StorageNetworkIpRangeResponse.class, + required=true, description="UUID of storage network ip range") private Long id; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address") private String startIp; @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address") private String endIp; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.INTEGER, description="Optional. the vlan the ip range sits on") private Integer vlan; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask for storage network") private String netmask; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -72,49 +67,49 @@ public class UpdateStorageNetworkIpRangeCmd extends BaseAsyncCmd { public Integer getVlan() { return vlan; } - + public String getNetmask() { - return netmask; + return netmask; } public Long getId() { - return id; + return id; } - - @Override - public String getEventType() { - return EventTypes.EVENT_STORAGE_IP_RANGE_UPDATE; - } - @Override - public String getEventDescription() { - return "Update storage ip range " + getId() + " [StartIp=" + getStartIp() + ", EndIp=" + getEndIp() + ", vlan=" + getVlan() + ", netmask=" + getNetmask() + ']'; - } + @Override + public String getEventType() { + return EventTypes.EVENT_STORAGE_IP_RANGE_UPDATE; + } - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this); - StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (Exception e) { - s_logger.warn("Update storage network IP range failed", e); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + @Override + public String getEventDescription() { + return "Update storage ip range " + getId() + " [StartIp=" + getStartIp() + ", EndIp=" + getEndIp() + ", vlan=" + getVlan() + ", netmask=" + getNetmask() + ']'; + } - } + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + try { + StorageNetworkIpRange result = _storageNetworkService.updateIpRange(this); + StorageNetworkIpRangeResponse response = _responseGenerator.createStorageNetworkIpRangeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } catch (Exception e) { + s_logger.warn("Update storage network IP range failed", e); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); + } - @Override - public String getCommandName() { - return s_name; - } + } - @Override - public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; - } + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } } diff --git a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java index 779221ee416..08101dc4137 --- a/api/src/com/cloud/api/commands/CreateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateDiskOfferingCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Creates a disk offering.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "createDiskOffering", description="Creates a disk offering.", responseObject=DiskOfferingResponse.class) public class CreateDiskOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateDiskOfferingCmd.class.getName()); @@ -53,10 +53,10 @@ public class CreateDiskOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.CUSTOMIZED, type=CommandType.BOOLEAN, description="whether disk offering is custom or not") private Boolean customized; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public offerings") - private Long domainId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public offerings") + private Long domainId; @Parameter(name=ApiConstants.STORAGE_TYPE, type=CommandType.STRING, description="the storage type of the disk offering. Values are local and shared.") private String storageType = ServiceOffering.StorageType.shared.toString(); @@ -82,11 +82,11 @@ public class CreateDiskOfferingCmd extends BaseCmd { } public Boolean isCustomized(){ - return customized; + return customized; } - + public Long getDomainId(){ - return domainId; + return domainId; } public String getStorageType() { @@ -101,12 +101,12 @@ public class CreateDiskOfferingCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ DiskOffering offering = _configService.createDiskOffering(this); @@ -116,6 +116,6 @@ public class CreateDiskOfferingCmd extends BaseCmd { this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create disk offering"); - } + } } } diff --git a/api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java index 1aa43e67dc3..f93c2a88ce2 100644 --- a/api/src/com/cloud/api/commands/CreateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/CreateServiceOfferingCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Creates a service offering.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "createServiceOffering", description="Creates a service offering.", responseObject=ServiceOfferingResponse.class) public class CreateServiceOfferingCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); - private static final String _name = "createserviceofferingresponse"; + public static final Logger s_logger = Logger.getLogger(CreateServiceOfferingCmd.class.getName()); + private static final String _name = "createserviceofferingresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// @@ -64,10 +64,10 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for this service offering.") private String tags; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public offerings") - private Long domainId; - + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public offerings") + private Long domainId; + @Parameter(name=ApiConstants.HOST_TAGS, type=CommandType.STRING, description="the host tag for this service offering.") private String hostTag; @@ -76,10 +76,10 @@ public class CreateServiceOfferingCmd extends BaseCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"domainrouter\", \"consoleproxy\" and \"secondarystoragevm\".") private String systemVmType; - + @Parameter(name=ApiConstants.NETWORKRATE, type=CommandType.INTEGER, description="data transfer rate in megabits per second allowed. Supported only for non-System offering and system offerings having \"domainrouter\" systemvmtype") private Integer networkRate; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -109,7 +109,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { } public Boolean GetLimitCpuUse() { - return limitCpuUse; + return limitCpuUse; } public String getStorageType() { @@ -121,8 +121,8 @@ public class CreateServiceOfferingCmd extends BaseCmd { } public Long getDomainId() { - return domainId; - } + return domainId; + } public String getHostTag() { return hostTag; @@ -135,7 +135,7 @@ public class CreateServiceOfferingCmd extends BaseCmd { public String getSystemVmType() { return systemVmType; } - + public Integer getNetworkRate() { return networkRate; } @@ -144,11 +144,11 @@ public class CreateServiceOfferingCmd extends BaseCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { - return _name; - } - + return _name; + } + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java index 12fcac7ac1a..85e034f6191 100644 --- a/api/src/com/cloud/api/commands/DeleteDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteDiskOfferingCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Updates a disk offering.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteDiskOffering", description="Updates a disk offering.", responseObject=SuccessResponse.class) public class DeleteDiskOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteDiskOfferingCmd.class.getName()); private static final String s_name = "deletediskofferingresponse"; @@ -36,8 +36,8 @@ public class DeleteDiskOfferingCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="ID of the disk offering") private Long id; @@ -57,12 +57,12 @@ public class DeleteDiskOfferingCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteDiskOffering(this); diff --git a/api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java index b76ad0cc5ea..d1ea4de0504 100644 --- a/api/src/com/cloud/api/commands/DeleteServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/DeleteServiceOfferingCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes a service offering.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteServiceOffering", description="Deletes a service offering.", responseObject=SuccessResponse.class) public class DeleteServiceOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteServiceOfferingCmd.class.getName()); private static final String s_name = "deleteserviceofferingresponse"; @@ -36,8 +33,8 @@ public class DeleteServiceOfferingCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the service offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering") private Long id; @@ -58,12 +55,12 @@ public class DeleteServiceOfferingCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteServiceOffering(this); diff --git a/api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java index 882f90e090b..8db731d3b31 --- a/api/src/com/cloud/api/commands/UpdateDiskOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateDiskOfferingCmd.java @@ -14,20 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import com.cloud.offering.DiskOffering; import com.cloud.user.Account; -@Implementation(description="Updates a disk offering.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "updateDiskOffering", description="Updates a disk offering.", responseObject=DiskOfferingResponse.class) public class UpdateDiskOfferingCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(UpdateDiskOfferingCmd.class.getName()); private static final String s_name = "updatediskofferingresponse"; @@ -39,13 +38,13 @@ public class UpdateDiskOfferingCmd extends BaseCmd{ @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="updates alternate display text of the disk offering with this value", length=4096) private String displayText; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="ID of the disk offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="updates name of the disk offering with this value") private String diskOfferingName; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the disk offering, integer") private Integer sortKey; @@ -64,26 +63,26 @@ public class UpdateDiskOfferingCmd extends BaseCmd{ public String getDiskOfferingName() { return diskOfferingName; } - + public Integer getSortKey() { - return sortKey; + return sortKey; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ DiskOffering result = _configService.updateDiskOffering(this); diff --git a/api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java index b7c2cf69fbd..38220b90673 --- a/api/src/com/cloud/api/commands/UpdateServiceOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/offering/UpdateServiceOfferingCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.offering; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; -@Implementation(description="Updates a service offering.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "updateServiceOffering", description="Updates a service offering.", responseObject=ServiceOfferingResponse.class) public class UpdateServiceOfferingCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateServiceOfferingCmd.class.getName()); private static final String s_name = "updateserviceofferingresponse"; @@ -36,16 +32,16 @@ public class UpdateServiceOfferingCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the service offering to be updated") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering to be updated") private Long id; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the service offering to be updated") private String displayText; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the service offering to be updated") private String serviceOfferingName; - + @Parameter(name=ApiConstants.SORT_KEY, type=CommandType.INTEGER, description="sort key of the service offering, integer") private Integer sortKey; ///////////////////////////////////////////////////// @@ -65,19 +61,19 @@ public class UpdateServiceOfferingCmd extends BaseCmd { } public Integer getSortKey() { - return sortKey; + return sortKey; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -85,8 +81,8 @@ public class UpdateServiceOfferingCmd extends BaseCmd { @Override public void execute(){ - //Note - //Once an offering is created, we cannot update the domainId field (keeping consistent with zones logic) + //Note + //Once an offering is created, we cannot update the domainId field (keeping consistent with zones logic) ServiceOffering result = _configService.updateServiceOffering(this); if (result != null){ ServiceOfferingResponse response = _responseGenerator.createServiceOfferingResponse(result); diff --git a/api/src/com/cloud/api/commands/CreatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java old mode 100755 new mode 100644 similarity index 85% rename from api/src/com/cloud/api/commands/CreatePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java index 99a161bb211..331968b00db --- a/api/src/com/cloud/api/commands/CreatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/CreatePodCmd.java @@ -14,21 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PodResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.dc.Pod; import com.cloud.user.Account; -@Implementation(description="Creates a new Pod.", responseObject=PodResponse.class) +@APICommand(name = "createPod", description="Creates a new Pod.", responseObject=PodResponse.class) public class CreatePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreatePodCmd.class.getName()); @@ -39,23 +37,23 @@ public class CreatePodCmd extends BaseCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the Pod") private String podName; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID in which the Pod will be created ") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the Zone ID in which the Pod will be created") private Long zoneId; @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the starting IP address for the Pod") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address for the Pod") private String endIp; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask for the Pod") private String netmask; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway for the Pod") private String gateway; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Pod for allocation of new resources") private String allocationState; @@ -88,9 +86,9 @@ public class CreatePodCmd extends BaseCmd { } public String getAllocationState() { - return allocationState; + return allocationState; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -99,7 +97,7 @@ public class CreatePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeletePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeletePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java index ed951242ab3..8c64a8dad33 100644 --- a/api/src/com/cloud/api/commands/DeletePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/DeletePodCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.SuccessResponse; + import com.cloud.user.Account; -@Implementation(description="Deletes a Pod.", responseObject=SuccessResponse.class) +@APICommand(name = "deletePod", description="Deletes a Pod.", responseObject=SuccessResponse.class) public class DeletePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeletePodCmd.class.getName()); @@ -37,11 +38,10 @@ public class DeletePodCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Pod") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the ID of the Pod") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -57,7 +57,7 @@ public class DeletePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/ListPodsByCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListPodsByCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java index b1270bbf192..a64ecdde9b5 --- a/api/src/com/cloud/api/commands/ListPodsByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/ListPodsByCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.dc.Pod; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="Lists all Pods.", responseObject=PodResponse.class) +import com.cloud.dc.Pod; +import com.cloud.utils.Pair; + +@APICommand(name = "listPods", description="Lists all Pods.", responseObject=PodResponse.class) public class ListPodsByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListPodsByCmd.class.getName()); @@ -41,23 +42,23 @@ public class ListPodsByCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list Pods by ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + description="list Pods by ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list Pods by name") private String podName; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list Pods by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="list Pods by Zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="list pods by allocation state") - private String allocationState; - + private String allocationState; + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the pods") private Boolean showCapacities; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -73,15 +74,15 @@ public class ListPodsByCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public String getAllocationState() { - return allocationState; - } + return allocationState; + } public Boolean getShowCapacities() { - return showCapacities; - } - + return showCapacities; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -93,16 +94,16 @@ public class ListPodsByCmd extends BaseListCmd { @Override public void execute(){ - List result = _mgr.searchForPods(this); + Pair, Integer> result = _mgr.searchForPods(this); ListResponse response = new ListResponse(); List podResponses = new ArrayList(); - for (Pod pod : result) { + for (Pod pod : result.first()) { PodResponse podResponse = _responseGenerator.createPodResponse(pod, showCapacities); podResponse.setObjectName("pod"); podResponses.add(podResponse); } - response.setResponses(podResponses); + response.setResponses(podResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdatePodCmd.java b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java old mode 100755 new mode 100644 similarity index 85% rename from api/src/com/cloud/api/commands/UpdatePodCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java index f575c7cf1dd..ca5e03953a3 --- a/api/src/com/cloud/api/commands/UpdatePodCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/pod/UpdatePodCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.pod; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PodResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PodResponse; + import com.cloud.dc.Pod; import com.cloud.user.Account; -@Implementation(description="Updates a Pod.", responseObject=PodResponse.class) +@APICommand(name = "updatePod", description="Updates a Pod.", responseObject=PodResponse.class) public class UpdatePodCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdatePodCmd.class.getName()); @@ -38,8 +35,8 @@ public class UpdatePodCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Pod") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PodResponse.class, + required=true, description="the ID of the Pod") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the Pod") @@ -47,16 +44,16 @@ public class UpdatePodCmd extends BaseCmd { @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the starting IP address for the Pod") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address for the Pod") private String endIp; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the Pod") private String netmask; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway for the Pod") private String gateway; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; @@ -89,7 +86,7 @@ public class UpdatePodCmd extends BaseCmd { } public String getAllocationState() { - return allocationState; + return allocationState; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -99,12 +96,12 @@ public class UpdatePodCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Pod result = _configService.editPod(this); diff --git a/api/src/com/cloud/api/commands/ListAlertsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListAlertsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java index 15040936195..db7a20b02a3 100644 --- a/api/src/com/cloud/api/commands/ListAlertsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListAlertsCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; import com.cloud.alert.Alert; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AlertResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AlertResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.utils.Pair; -@Implementation(description = "Lists all alerts.", responseObject = AlertResponse.class) +@APICommand(name = "listAlerts", description = "Lists all alerts.", responseObject = AlertResponse.class) public class ListAlertsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListAlertsCmd.class.getName()); @@ -41,8 +41,8 @@ public class ListAlertsCmd extends BaseListCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="alert") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the alert") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AlertResponse.class, + description = "the ID of the alert") private Long id; @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "list by alert type") @@ -71,12 +71,12 @@ public class ListAlertsCmd extends BaseListCmd { @Override public void execute() { - List result = _mgr.searchForAlerts(this); + Pair, Integer> result = _mgr.searchForAlerts(this); ListResponse response = new ListResponse(); List alertResponseList = new ArrayList(); - for (Alert alert : result) { + for (Alert alert : result.first()) { AlertResponse alertResponse = new AlertResponse(); - alertResponse.setId(alert.getId()); + alertResponse.setId(alert.getUuid()); alertResponse.setAlertType(alert.getType()); alertResponse.setDescription(alert.getSubject()); alertResponse.setLastSent(alert.getLastSent()); @@ -85,7 +85,7 @@ public class ListAlertsCmd extends BaseListCmd { alertResponseList.add(alertResponse); } - response.setResponses(alertResponseList); + response.setResponses(alertResponseList, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListCapacityCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java old mode 100755 new mode 100644 similarity index 59% rename from api/src/com/cloud/api/commands/ListCapacityCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java index 5e3ca5e1511..ce20a3e27de --- a/api/src/com/cloud/api/commands/ListCapacityCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/ListCapacityCmd.java @@ -14,24 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; import java.text.DecimalFormat; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.capacity.Capacity; import com.cloud.exception.InvalidParameterValueException; -@Implementation(description="Lists all the system wide capacities.", responseObject=CapacityResponse.class) +@APICommand(name = "listCapacity", description="Lists all the system wide capacities.", responseObject=CapacityResponse.class) public class ListCapacityCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListCapacityCmd.class.getName()); @@ -42,36 +44,36 @@ public class ListCapacityCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists capacity by the Zone ID") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="lists capacity by the Zone ID") private Long zoneId; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="lists capacity by the Pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="lists capacity by the Pod ID") private Long podId; - - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, since="3.0.0", description="lists capacity by the Cluster ID") + + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + since="3.0.0", description="lists capacity by the Cluster ID") private Long clusterId; @Parameter(name=ApiConstants.FETCH_LATEST, type=CommandType.BOOLEAN, since="3.0.0", description="recalculate capacities and fetch the latest") private Boolean fetchLatest; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.INTEGER, description="lists capacity by type" + - "* CAPACITY_TYPE_MEMORY = 0" + - "* CAPACITY_TYPE_CPU = 1" + - "* CAPACITY_TYPE_STORAGE = 2" + - "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + - "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + - "* CAPACITY_TYPE_PRIVATE_IP = 5" + - "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + - "* CAPACITY_TYPE_VLAN = 7" + - "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + - "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") + "* CAPACITY_TYPE_MEMORY = 0" + + "* CAPACITY_TYPE_CPU = 1" + + "* CAPACITY_TYPE_STORAGE = 2" + + "* CAPACITY_TYPE_STORAGE_ALLOCATED = 3" + + "* CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP = 4" + + "* CAPACITY_TYPE_PRIVATE_IP = 5" + + "* CAPACITY_TYPE_SECONDARY_STORAGE = 6" + + "* CAPACITY_TYPE_VLAN = 7" + + "* CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP = 8" + + "* CAPACITY_TYPE_LOCAL_STORAGE = 9.") private Integer type; - + @Parameter(name=ApiConstants.SORT_BY, type=CommandType.STRING, since="3.0.0", description="Sort the results. Available values: Usage") private String sortBy; @@ -82,23 +84,23 @@ public class ListCapacityCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getPodId() { return podId; } public Long getClusterId() { - return clusterId; - } + return clusterId; + } - public Boolean getFetchLatest() { - return fetchLatest; - } + public Boolean getFetchLatest() { + return fetchLatest; + } - public Integer getType() { + public Integer getType() { return type; } - + public String getSortBy() { if (sortBy != null) { if (sortBy.equalsIgnoreCase("usage")) { @@ -107,7 +109,7 @@ public class ListCapacityCmd extends BaseListCmd { throw new InvalidParameterValueException("Only value supported for sortBy parameter is : usage"); } } - + return null; } @@ -119,7 +121,7 @@ public class ListCapacityCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = null; @@ -128,7 +130,7 @@ public class ListCapacityCmd extends BaseListCmd { } else { result = _mgr.listCapacities(this); } - + ListResponse response = new ListResponse(); List capacityResponses = _responseGenerator.createCapacityResponse(result, s_percentFormat); response.setResponses(capacityResponses); diff --git a/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java index 44219d1684c..0e559189904 100644 --- a/api/src/com/cloud/api/commands/UploadCustomCertificateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/resource/UploadCustomCertificateCmd.java @@ -14,59 +14,55 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.resource; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -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.CustomCertificateResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.CustomCertificateResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(responseObject=CustomCertificateResponse.class, description="Uploads custom certificate") +@APICommand(name = "uploadCustomCertificate", responseObject=CustomCertificateResponse.class, description="Uploads a custom certificate for the console proxy VMs to use for SSL. Can be used to upload a single certificate signed by a known CA. Can also be used, through multiple calls, to upload a chain of certificates from CA to the custom certificate itself.") public class UploadCustomCertificateCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UploadCustomCertificateCmd.class.getName()); private static final String s_name = "uploadcustomcertificateresponse"; - @Parameter(name=ApiConstants.CERTIFICATE,type=CommandType.STRING,required=true,description="the custom cert to be uploaded", length=65535) + @Parameter(name=ApiConstants.CERTIFICATE,type=CommandType.STRING,required=true,description="The certificate to be uploaded.", length=65535) private String certificate; - - @Parameter(name=ApiConstants.ID,type=CommandType.INTEGER,required=false,description="the custom cert id in the chain") + + @Parameter(name=ApiConstants.ID,type=CommandType.INTEGER,required=false,description="An integer providing the location in a chain that the certificate will hold. Usually, this can be left empty. When creating a chain, the top level certificate should have an ID of 1, with each step in the chain incrementing by one. Example, CA with id = 1, Intermediate CA with id = 2, Site certificate with ID = 3") private Integer index; - - @Parameter(name=ApiConstants.NAME,type=CommandType.STRING,required=false,description="the alias of the certificate") + + @Parameter(name=ApiConstants.NAME,type=CommandType.STRING,required=false,description="A name / alias for the certificate.") private String alias; - @Parameter(name=ApiConstants.PRIVATE_KEY,type=CommandType.STRING,required=false,description="the private key for the certificate", length=65535) + @Parameter(name=ApiConstants.PRIVATE_KEY,type=CommandType.STRING,required=false,description="The private key for the attached certificate.", length=65535) private String privateKey; - @Parameter(name=ApiConstants.DOMAIN_SUFFIX,type=CommandType.STRING,required=true,description="DNS domain suffix that the certificate is granted for") + @Parameter(name=ApiConstants.DOMAIN_SUFFIX,type=CommandType.STRING,required=true,description="DNS domain suffix that the certificate is granted for.") private String domainSuffix; - + public String getCertificate() { return certificate; } - + public String getPrivateKey() { - return privateKey; + return privateKey; } - + public String getDomainSuffix() { - return domainSuffix; + return domainSuffix; } - + public Integer getCertIndex() { - return index; + return index; } - + public String getAlias() { - return alias; + return alias; } @Override @@ -78,21 +74,21 @@ public class UploadCustomCertificateCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Uploading custom certificate to the db, and applying it to all the cpvms in the system"); } - + @Override public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "certificate"; + return "certificate"; } @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ String result = _mgr.uploadCertificate(this); diff --git a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java index 967994051bb..be6be26a36f 100644 --- a/api/src/com/cloud/api/commands/ConfigureVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ConfigureVirtualRouterElementCmd.java @@ -14,19 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.element.VirtualRouterElementService; import com.cloud.async.AsyncJob; @@ -37,11 +36,11 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=VirtualRouterProviderResponse.class, description="Configures a virtual router element.") +@APICommand(name = "configureVirtualRouterElement", responseObject=VirtualRouterProviderResponse.class, description="Configures a virtual router element.") public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ConfigureVirtualRouterElementCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ConfigureVirtualRouterElementCmd.class.getName()); private static final String s_name = "configurevirtualrouterelementresponse"; - + @PlugService private VirtualRouterElementService _service; @@ -49,14 +48,13 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "virtual_router_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the virtual router provider") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VirtualRouterProviderResponse.class, + required=true, description="the ID of the virtual router provider") private Long id; - @IdentityMapper(entityTableName = "physical_network_service_providers") @Parameter(name=ApiConstants.ENABLED, type=CommandType.BOOLEAN, required=true, description="Enabled/Disabled the service provider") private Boolean enabled; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -85,11 +83,11 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "boolean"; + return "boolean"; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -104,15 +102,15 @@ public class ConfigureVirtualRouterElementCmd extends BaseAsyncCmd { public String getEventDescription() { return "configuring virtual router provider: " + id; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.None; + return AsyncJob.Type.None; } - + public Long getInstanceId() { return id; } - + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Virtual router element: " + id); diff --git a/api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java index 2c44663a382..545218f0364 100644 --- a/api/src/com/cloud/api/commands/CreateVirtualRouterElementCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/CreateVirtualRouterElementCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProviderResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.VirtualRouterProvider; @@ -35,11 +30,11 @@ import com.cloud.network.element.VirtualRouterElementService; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=VirtualRouterProviderResponse.class, description="Create a virtual router element.") +@APICommand(name = "createVirtualRouterElement", responseObject=VirtualRouterProviderResponse.class, description="Create a virtual router element.") public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVirtualRouterElementCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVirtualRouterElementCmd.class.getName()); private static final String s_name = "createvirtualrouterelementresponse"; - + @PlugService private VirtualRouterElementService _service; @@ -47,8 +42,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.NETWORK_SERVICE_PROVIDER_ID, type=CommandType.LONG, required=true, description="the network service provider ID of the virtual router element") - @IdentityMapper(entityTableName="physical_network_service_providers") + @Parameter(name=ApiConstants.NETWORK_SERVICE_PROVIDER_ID, type=CommandType.UUID, entityType = ProviderResponse.class, required=true, description="the network service provider ID of the virtual router element") private Long nspId; ///////////////////////////////////////////////////// @@ -67,7 +61,7 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { public Long getNspId() { return nspId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -76,12 +70,12 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("Virtual router element Id: "+getEntityId()); @@ -102,14 +96,14 @@ public class CreateVirtualRouterElementCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add Virtual Router entity to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_SERVICE_PROVIDER_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network ServiceProvider Virtual Router: " + getEntityId(); diff --git a/api/src/com/cloud/api/commands/DestroyRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DestroyRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java index 2026e8727c3..1157aaa7b93 100644 --- a/api/src/com/cloud/api/commands/DestroyRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/DestroyRouterCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +33,7 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Destroys a router.", responseObject = DomainRouterResponse.class) +@APICommand(name = "destroyRouter", description = "Destroys a router.", responseObject = DomainRouterResponse.class) public class DestroyRouterCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroyRouterCmd.class.getName()); private static final String s_name = "destroyrouterresponse"; @@ -43,8 +42,8 @@ public class DestroyRouterCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the router") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainRouterResponse.class, + required = true, description = "the ID of the router") private Long id; // /////////////////////////////////////////////////// @@ -96,8 +95,10 @@ public class DestroyRouterCmd extends BaseAsyncCmd { @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException { - UserContext.current().setEventDetails("Router Id: "+getId()); - VirtualRouter result = _routerService.destroyRouter(getId()); + UserContext ctx = UserContext.current(); + ctx.setEventDetails("Router Id: "+getId()); + + VirtualRouter result = _routerService.destroyRouter(getId(), ctx.getCaller(), ctx.getCallerUserId()); if (result != null) { DomainRouterResponse response = _responseGenerator.createDomainRouterResponse(result); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ListRoutersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java similarity index 59% rename from api/src/com/cloud/api/commands/ListRoutersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java index 72a9144edda..198d8766b21 100644 --- a/api/src/com/cloud/api/commands/ListRoutersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListRoutersCmd.java @@ -14,24 +14,26 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.async.AsyncJob; -import com.cloud.network.router.VirtualRouter; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="List routers.", responseObject=DomainRouterResponse.class) +import com.cloud.async.AsyncJob; + +@APICommand(name = "listRouters", description="List routers.", responseObject=DomainRouterResponse.class) public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListRoutersCmd.class.getName()); @@ -41,36 +43,36 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID of the router") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID of the router") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the disk router") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the router") private String routerName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the router") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the Pod ID of the router") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the router") private String state; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the router") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID of the router") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType=NetworkResponse.class, + description="list by network id") private Long networkId; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="List networks by VPC") private Long vpcId; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="if true is passed for this parameter, list only VPC routers") private Boolean forVpc; @@ -85,7 +87,7 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public Long getId() { return id; } - + public String getRouterName() { return routerName; } @@ -101,15 +103,15 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public Long getZoneId() { return zoneId; } - + public Long getNetworkId() { return networkId; } - + public Long getVpcId() { return vpcId; } - + public Boolean getForVpc() { return forVpc; } @@ -122,23 +124,15 @@ public class ListRoutersCmd extends BaseListProjectAndAccountResourcesCmd { public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; + return AsyncJob.Type.DomainRouter; } @Override public void execute(){ - List result = _mgr.searchForRouters(this); - ListResponse response = new ListResponse(); - List routerResponses = new ArrayList(); - for (VirtualRouter router : result) { - DomainRouterResponse routerResponse = _responseGenerator.createDomainRouterResponse(router); - routerResponse.setObjectName("router"); - routerResponses.add(routerResponse); - } - - response.setResponses(routerResponses); + ListResponse response = _queryService.searchForRouters(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java index 937a01e2d80..0a93ea5ab3e 100644 --- a/api/src/com/cloud/api/commands/ListVirtualRouterElementsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/ListVirtualRouterElementsCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.response.ProviderResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -37,32 +38,32 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.element.VirtualRouterElementService; -@Implementation(description="Lists all available virtual router elements.", responseObject=VirtualRouterProviderResponse.class) +@APICommand(name = "listVirtualRouterElements", description="Lists all available virtual router elements.", responseObject=VirtualRouterProviderResponse.class) public class ListVirtualRouterElementsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); private static final String _name = "listvirtualrouterelementsresponse"; @PlugService private VirtualRouterElementService _service; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "virtual_router_providers") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list virtual router elements by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VirtualRouterProviderResponse.class, + description="list virtual router elements by id") private Long id; - - @IdentityMapper(entityTableName = "physical_network_service_providers") - @Parameter(name=ApiConstants.NSP_ID, type=CommandType.LONG, description="list virtual router elements by network service provider id") + + @Parameter(name=ApiConstants.NSP_ID, type=CommandType.UUID, entityType = ProviderResponse.class, + description="list virtual router elements by network service provider id") private Long nspId; - + @Parameter(name=ApiConstants.ENABLED, type=CommandType.BOOLEAN, description="list network offerings by enabled state") private Boolean enabled; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setId(Long id) { this.id = id; } @@ -91,7 +92,7 @@ public class ListVirtualRouterElementsCmd extends BaseListCmd { public String getCommandName() { return _name; } - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, ResourceAllocationException { List providers = _service.searchForVirtualRouterElement(this); diff --git a/api/src/com/cloud/api/commands/RebootRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/RebootRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java index 58577b7ffb9..9c50d2ffb0f 100644 --- a/api/src/com/cloud/api/commands/RebootRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/RebootRouterCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,17 +30,17 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Starts a router.", responseObject=DomainRouterResponse.class) +@APICommand(name = "rebootRouter", description="Starts a router.", responseObject=DomainRouterResponse.class) public class RebootRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(RebootRouterCmd.class.getName()); private static final String s_name = "rebootrouterresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DomainRouterResponse.class, + required=true, description="the ID of the router") private Long id; ///////////////////////////////////////////////////// @@ -64,7 +59,7 @@ public class RebootRouterCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -84,16 +79,16 @@ public class RebootRouterCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting router: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; - } - - public Long getInstanceId() { - return getId(); + return AsyncJob.Type.DomainRouter; } - + public Long getInstanceId() { + return getId(); + } + + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Router Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StartRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/StartRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java index 233e34f0a05..f1f3f681829 100644 --- a/api/src/com/cloud/api/commands/StartRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StartRouterCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,10 +30,9 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; - -@Implementation(responseObject=DomainRouterResponse.class, description="Starts a router.") +@APICommand(name = "startRouter", responseObject=DomainRouterResponse.class, description="Starts a router.") public class StartRouterCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StartRouterCmd.class.getName()); private static final String s_name = "startrouterresponse"; @@ -46,8 +40,8 @@ public class StartRouterCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=DomainRouterResponse.class, + required=true, description="the ID of the router") private Long id; ///////////////////////////////////////////////////// @@ -66,11 +60,11 @@ public class StartRouterCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "router"; + return "router"; } - + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -90,15 +84,15 @@ public class StartRouterCmd extends BaseAsyncCmd { public String getEventDescription() { return "starting router: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.DomainRouter; + return AsyncJob.Type.DomainRouter; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Router Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StopRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/StopRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java index 84a8bc50d52..2d1b609aa5d 100644 --- a/api/src/com/cloud/api/commands/StopRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/StopRouterCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +33,7 @@ import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Stops a router.", responseObject = DomainRouterResponse.class) +@APICommand(name = "stopRouter", description = "Stops a router.", responseObject = DomainRouterResponse.class) public class StopRouterCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopRouterCmd.class.getName()); private static final String s_name = "stoprouterresponse"; @@ -43,8 +42,8 @@ public class StopRouterCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the router") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = DomainRouterResponse.class, + required = true, description = "the ID of the router") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM. The caller knows the VM is stopped.") diff --git a/api/src/com/cloud/api/commands/UpgradeRouterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/UpgradeRouterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java index a5168761d8f..e2b020e09f9 100644 --- a/api/src/com/cloud/api/commands/UpgradeRouterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/router/UpgradeRouterCmd.java @@ -14,35 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.router; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainRouterResponse; import com.cloud.network.router.VirtualRouter; import com.cloud.user.Account; -@Implementation(description="Upgrades domain router to a new service offering", responseObject=DomainRouterResponse.class) +@APICommand(name = "changeServiceForRouter", description="Upgrades domain router to a new service offering", responseObject=DomainRouterResponse.class) public class UpgradeRouterCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); - private static final String s_name = "changeserviceforrouterresponse"; + public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); + private static final String s_name = "changeserviceforrouterresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the router") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DomainRouterResponse.class, + required=true, description="The ID of the router") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the service offering ID to apply to the domain router") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType = DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the domain router") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -61,11 +58,11 @@ public class UpgradeRouterCmd extends BaseCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } + @Override public long getEntityOwnerId() { VirtualRouter router = _entityMgr.findById(VirtualRouter.class, getId()); @@ -75,7 +72,7 @@ public class UpgradeRouterCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualRouter router = _routerService.upgradeRouter(this); diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/AddS3Cmd.java new file mode 100644 index 00000000000..13f066a6e57 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/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 org.apache.cloudstack.api.command.admin.storage; + +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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.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; + +@APICommand(name = "addS3", 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/CancelPrimaryStorageMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java index c4d97aeb985..24ef48be222 100644 --- a/api/src/com/cloud/api/commands/CancelPrimaryStorageMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CancelPrimaryStorageMaintenanceCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; @@ -33,18 +32,18 @@ import com.cloud.storage.StoragePool; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Cancels maintenance for primary storage", responseObject=StoragePoolResponse.class) +@APICommand(name = "cancelStorageMaintenance", description="Cancels maintenance for primary storage", responseObject=StoragePoolResponse.class) public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CancelPrimaryStorageMaintenanceCmd.class.getName()); - + public static final Logger s_logger = Logger.getLogger(CancelPrimaryStorageMaintenanceCmd.class.getName()); + private static final String s_name = "cancelprimarystoragemaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the primary storage ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="the primary storage ID") private Long id; @@ -65,16 +64,16 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "primarystorage"; + return "primarystorage"; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } - + @Override public Long getInstanceId() { return getId(); @@ -99,7 +98,7 @@ public class CancelPrimaryStorageMaintenanceCmd extends BaseAsyncCmd { public String getEventDescription() { return "canceling maintenance for primary storage pool: " + getId(); } - + @Override public void execute() throws ResourceUnavailableException{ StoragePool result = _storageService.cancelPrimaryStorageForMaintenance(this); diff --git a/api/src/com/cloud/api/commands/CreateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/CreateStoragePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java index 69c1bb5f671..78a142ac449 100644 --- a/api/src/com/cloud/api/commands/CreateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/CreateStoragePoolCmd.java @@ -14,27 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.net.UnknownHostException; import java.util.Map; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.storage.StoragePool; import com.cloud.user.Account; @SuppressWarnings("rawtypes") -@Implementation(description="Creates a storage pool.", responseObject=StoragePoolResponse.class) +@APICommand(name = "createStoragePool", description="Creates a storage pool.", responseObject=StoragePoolResponse.class) public class CreateStoragePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateStoragePoolCmd.class.getName()); @@ -44,8 +43,8 @@ public class CreateStoragePoolCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="the cluster ID for the storage pool") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + required=true, description="the cluster ID for the storage pool") private Long clusterId; @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the storage pool") @@ -54,8 +53,8 @@ public class CreateStoragePoolCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name for the storage pool") private String storagePoolName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID for the storage pool") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + required=true, description="the Pod ID for the storage pool") private Long podId; @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="the tags for the storage pool") @@ -64,8 +63,8 @@ public class CreateStoragePoolCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of the storage pool") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the storage pool") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the Zone ID for the storage pool") private Long zoneId; ///////////////////////////////////////////////////// @@ -103,12 +102,12 @@ public class CreateStoragePoolCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/DeletePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeletePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java index ba2f73fdb24..1510f7822f7 100644 --- a/api/src/com/cloud/api/commands/DeletePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/DeletePoolCmd.java @@ -14,22 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.StoragePoolResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolStatus; import com.cloud.user.Account; -@Implementation(description = "Deletes a storage pool.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteStoragePool", description = "Deletes a storage pool.", responseObject = SuccessResponse.class) public class DeletePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeletePoolCmd.class.getName()); private static final String s_name = "deletestoragepoolresponse"; @@ -38,10 +35,10 @@ public class DeletePoolCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "Storage pool id") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = StoragePoolResponse.class, + required = true, description = "Storage pool id") private Long id; - + @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force destroy storage pool " + "(force expunge volumes in Destroyed state as a part of pool removal)") private Boolean forced; @@ -53,7 +50,7 @@ public class DeletePoolCmd extends BaseCmd { public Long getId() { return id; } - + public boolean isForced() { return (forced != null) ? forced : false; } diff --git a/api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java new file mode 100644 index 00000000000..d0f6d722179 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/ListS3sCmd.java @@ -0,0 +1,75 @@ +/* + * 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 org.apache.cloudstack.api.command.admin.storage; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.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; + +@APICommand(name = "listS3s", description = "Lists S3s", responseObject = S3Response.class, since = "4.0.0") +public final class ListS3sCmd extends BaseListCmd { + + private static final String COMMAND_NAME = "lists3sresponse"; + + @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 String getCommandName() { + return COMMAND_NAME; + } + +} diff --git a/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/ListStoragePoolsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java index 6208dcd5691..3723f8b3996 100644 --- a/api/src/com/cloud/api/commands/ListStoragePoolsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/ListStoragePoolsCmd.java @@ -14,25 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.storage.StoragePool; +import com.cloud.utils.Pair; -@Implementation(description="Lists storage pools.", responseObject=StoragePoolResponse.class) +@APICommand(name = "listStoragePools", description="Lists storage pools.", responseObject=StoragePoolResponse.class) public class ListStoragePoolsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListStoragePoolsCmd.class.getName()); @@ -42,8 +44,8 @@ public class ListStoragePoolsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, description="list storage pools belongig to the specific cluster") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + description="list storage pools belongig to the specific cluster") private Long clusterId; @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the IP address for the storage pool") @@ -55,16 +57,16 @@ public class ListStoragePoolsCmd extends BaseListCmd { @Parameter(name=ApiConstants.PATH, type=CommandType.STRING, description="the storage pool path") private String path; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID for the storage pool") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID for the storage pool") private Long podId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID for the storage pool") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID for the storage pool") private Long zoneId; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the storage pool") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + description="the ID of the storage pool") private Long id; ///////////////////////////////////////////////////// @@ -94,9 +96,9 @@ public class ListStoragePoolsCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getId() { - return id; + return id; } ///////////////////////////////////////////////////// @@ -107,23 +109,23 @@ public class ListStoragePoolsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } @Override public void execute(){ - List pools = _mgr.searchForStoragePools(this); + Pair, Integer> pools = _mgr.searchForStoragePools(this); ListResponse response = new ListResponse(); List poolResponses = new ArrayList(); - for (StoragePool pool : pools) { + for (StoragePool pool : pools.first()) { StoragePoolResponse poolResponse = _responseGenerator.createStoragePoolResponse(pool); poolResponse.setObjectName("storagepool"); poolResponses.add(poolResponse); } - response.setResponses(poolResponses); + response.setResponses(poolResponses, pools.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java index 31e181e56d7..6a4175516cc 100644 --- a/api/src/com/cloud/api/commands/PreparePrimaryStorageForMaintenanceCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/PreparePrimaryStorageForMaintenanceCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -34,17 +33,17 @@ import com.cloud.storage.StoragePool; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Puts storage pool into maintenance state", responseObject=StoragePoolResponse.class) +@APICommand(name = "enableStorageMaintenance", description="Puts storage pool into maintenance state", responseObject=StoragePoolResponse.class) public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(PreparePrimaryStorageForMaintenanceCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(PreparePrimaryStorageForMaintenanceCmd.class.getName()); private static final String s_name = "prepareprimarystorageformaintenanceresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Primary storage ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="Primary storage ID") private Long id; ///////////////////////////////////////////////////// @@ -63,16 +62,16 @@ public class PreparePrimaryStorageForMaintenanceCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "primarystorage"; + return "primarystorage"; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StoragePool; } - + @Override public Long getInstanceId() { return getId(); diff --git a/api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java index 52b5a047dbf..806df561397 100644 --- a/api/src/com/cloud/api/commands/UpdateStoragePoolCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/storage/UpdateStoragePoolCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.storage; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.StoragePoolResponse; import com.cloud.storage.StoragePool; import com.cloud.user.Account; -@Implementation(description="Updates a storage pool.", responseObject=StoragePoolResponse.class, since="3.0.0") +@APICommand(name = "updateStoragePool", description="Updates a storage pool.", responseObject=StoragePoolResponse.class, since="3.0.0") public class UpdateStoragePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateStoragePoolCmd.class.getName()); @@ -40,13 +36,13 @@ public class UpdateStoragePoolCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the Id of the storage pool") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StoragePoolResponse.class, + required=true, description="the Id of the storage pool") private Long id; @Parameter(name=ApiConstants.TAGS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma-separated list of tags for the storage pool") private List tags; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -68,12 +64,12 @@ public class UpdateStoragePoolCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ StoragePool result = _storageService.updateStoragePool(this); diff --git a/api/src/com/cloud/api/commands/AddSwiftCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/AddSwiftCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java index 0be4d5ffde8..23a00ca04dc 100644 --- a/api/src/com/cloud/api/commands/AddSwiftCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/AddSwiftCmd.java @@ -14,26 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.swift; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -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.HostResponse; -import com.cloud.api.response.SwiftResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.exception.DiscoveryException; import com.cloud.storage.Swift; import com.cloud.user.Account; -@Implementation(description = "Adds Swift.", responseObject = HostResponse.class, since="3.0.0") +@APICommand(name = "addSwift", description = "Adds Swift.", responseObject = HostResponse.class, since="3.0.0") public class AddSwiftCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddSwiftCmd.class.getName()); private static final String s_name = "addswiftresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -76,14 +73,14 @@ public class AddSwiftCmd extends BaseCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/ListSwiftsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/ListSwiftsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java index 587ceee10b9..d7c151188e7 100644 --- a/api/src/com/cloud/api/commands/ListSwiftsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/swift/ListSwiftsCmd.java @@ -14,28 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.swift; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SwiftResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SwiftResponse; import com.cloud.storage.Swift; import com.cloud.user.Account; -@Implementation(description = "List Swift.", responseObject = HostResponse.class, since="3.0.0") +@APICommand(name = "listSwifts", description = "List Swift.", responseObject = HostResponse.class, since="3.0.0") public class ListSwiftsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSwiftsCmd.class.getName()); private static final String s_name = "listswiftsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -54,14 +54,14 @@ public class ListSwiftsCmd extends BaseListCmd { @Override public String getCommandName() { - return s_name; + return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ List result = _resourceService.listSwifts(this); diff --git a/api/src/com/cloud/api/commands/DestroySystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DestroySystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java index 44626e1ad46..ad0f09cba46 100644 --- a/api/src/com/cloud/api/commands/DestroySystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/DestroySystemVmCmd.java @@ -14,34 +14,29 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Destroyes a system virtual machine.") +@APICommand(name = "destroySystemVm", responseObject=SystemVmResponse.class, description="Destroyes a system virtual machine.") public class DestroySystemVmCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroySystemVmCmd.class.getName()); - + private static final String s_name = "destroysystemvmresponse"; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; - + public Long getId() { return id; } @@ -50,9 +45,9 @@ public class DestroySystemVmCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "systemvm"; + return "systemvm"; } @Override @@ -75,22 +70,22 @@ public class DestroySystemVmCmd extends BaseAsyncCmd { return EventTypes.EVENT_SSVM_DESTROY; } } - + @Override public String getEventDescription() { return "destroying system vm: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.SystemVm; } - + @Override public Long getInstanceId() { return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ListSystemVMsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java similarity index 65% rename from api/src/com/cloud/api/commands/ListSystemVMsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java index 03e19855e0c..27e2ee40daf 100644 --- a/api/src/com/cloud/api/commands/ListSystemVMsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/ListSystemVMsCmd.java @@ -14,24 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; +import com.cloud.utils.Pair; import com.cloud.vm.VirtualMachine; -@Implementation(description="List system virtual machines.", responseObject=SystemVmResponse.class) +@APICommand(name = "listSystemVms", description="List system virtual machines.", responseObject=SystemVmResponse.class) public class ListSystemVMsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSystemVMsCmd.class.getName()); @@ -41,19 +45,19 @@ public class ListSystemVMsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID of the system VM") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID of the system VM") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the system VM") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + description="the ID of the system VM") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the system VM") private String systemVmName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the system VM") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the Pod ID of the system VM") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="the state of the system VM") @@ -62,12 +66,12 @@ public class ListSystemVMsCmd extends BaseListCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"consoleproxy\" and \"secondarystoragevm\".") private String systemVmType; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the system VM") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the Zone ID of the system VM") private Long zoneId; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to", since="3.0.1") + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="the storage ID where vm's volumes belong to", since="3.0.1") private Long storageId; ///////////////////////////////////////////////////// @@ -101,7 +105,7 @@ public class ListSystemVMsCmd extends BaseListCmd { public Long getZoneId() { return zoneId; } - + public Long getStorageId() { return storageId; } @@ -114,23 +118,23 @@ public class ListSystemVMsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + @Override public void execute(){ - List systemVMs = _mgr.searchForSystemVm(this); + Pair, Integer> systemVMs = _mgr.searchForSystemVm(this); ListResponse response = new ListResponse(); List vmResponses = new ArrayList(); - for (VirtualMachine systemVM : systemVMs) { + for (VirtualMachine systemVM : systemVMs.first()) { SystemVmResponse vmResponse = _responseGenerator.createSystemVmResponse(systemVM); vmResponse.setObjectName("systemvm"); vmResponses.add(vmResponse); } - response.setResponses(vmResponses); + response.setResponses(vmResponses, systemVMs.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/MigrateSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java index 13bb208ad6d..dd844acd17f 100644 --- a/api/src/com/cloud/api/commands/MigrateSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/MigrateSystemVMCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +38,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Attempts Migration of a system virtual machine to the host specified.", responseObject=SystemVmInstanceResponse.class) +@APICommand(name = "migrateSystemVm", description="Attempts Migration of a system virtual machine to the host specified.", responseObject=SystemVmInstanceResponse.class) public class MigrateSystemVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MigrateSystemVMCmd.class.getName()); @@ -47,12 +48,12 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, required=true, description="destination Host ID to migrate VM to") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + required=true, description="destination Host ID to migrate VM to") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; @@ -77,7 +78,7 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -97,38 +98,38 @@ public class MigrateSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - + Host destinationHost = _resourceService.getHost(getHostId()); if (destinationHost == null) { throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); } try{ - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); - //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer - VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - if (migratedVm != null) { - // return the generic system VM instance response - SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + //FIXME : Should not be calling UserVmService to migrate all types of VMs - need a generic VM layer + VirtualMachine migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + if (migratedVm != null) { + // return the generic system VM instance response + SystemVmInstanceResponse response = _responseGenerator.createSystemVmInstanceResponse(migratedVm); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate the system vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/RebootSystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java index 03a95756a82..49e895b22fe 100644 --- a/api/src/com/cloud/api/commands/RebootSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/RebootSystemVmCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Reboots a system VM.", responseObject=SystemVmResponse.class) +@APICommand(name = "rebootSystemVm", description="Reboots a system VM.", responseObject=SystemVmResponse.class) public class RebootSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(RebootSystemVmCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(RebootSystemVmCmd.class.getName()); private static final String s_name = "rebootsystemvmresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -57,7 +56,7 @@ public class RebootSystemVmCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; @@ -88,15 +87,15 @@ public class RebootSystemVmCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting system vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StartSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/StartSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java index 9cd78f3c1fd..70ab5f38720 100644 --- a/api/src/com/cloud/api/commands/StartSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StartSystemVMCmd.java @@ -14,36 +14,35 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Starts a system virtual machine.") +@APICommand(name = "startSystemVm", responseObject=SystemVmResponse.class, description="Starts a system virtual machine.") public class StartSystemVMCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StartSystemVMCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StartSystemVMCmd.class.getName()); private static final String s_name = "startsystemvmresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -62,9 +61,9 @@ public class StartSystemVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "systemvm"; + return "systemvm"; } @Override @@ -92,15 +91,15 @@ public class StartSystemVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "starting system vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/StopSystemVmCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/StopSystemVmCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java index 91e48c8a35d..af2bd3ad64f 100644 --- a/api/src/com/cloud/api/commands/StopSystemVmCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/StopSystemVmCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,9 +29,9 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(description="Stops a system VM.", responseObject=SystemVmResponse.class) +@APICommand(name = "stopSystemVm", description="Stops a system VM.", responseObject=SystemVmResponse.class) public class StopSystemVmCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(StopSystemVmCmd.class.getName()); private static final String s_name = "stopsystemvmresponse"; @@ -44,13 +39,13 @@ public class StopSystemVmCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system virtual machine") private Long id; @Parameter(name=ApiConstants.FORCED, type=CommandType.BOOLEAN, required=false, description="Force stop the VM. The caller knows the VM is stopped.") private Boolean forced; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -93,17 +88,17 @@ public class StopSystemVmCmd extends BaseAsyncCmd { public String getEventDescription() { return "stopping system vm: " + getId(); } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.SystemVm; + return AsyncJob.Type.SystemVm; } - + @Override public Long getInstanceId() { - return getId(); + return getId(); } - + public boolean isForced() { return (forced != null) ? forced : false; } diff --git a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java index a36844aeb3b..290c3603f1f 100644 --- a/api/src/com/cloud/api/commands/UpgradeSystemVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/systemvm/UpgradeSystemVMCmd.java @@ -14,24 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.systemvm; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; +import org.apache.cloudstack.api.response.DiskOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SystemVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SystemVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.vm.VirtualMachine; -@Implementation(responseObject=SystemVmResponse.class, description="Changes the service offering for a system vm (console proxy or secondary storage). " + +@APICommand(name = "changeServiceForSystemVm", responseObject=SystemVmResponse.class, description="Changes the service offering for a system vm (console proxy or secondary storage). " + "The system vm must be in a \"Stopped\" state for " + "this command to take effect.") public class UpgradeSystemVMCmd extends BaseCmd { @@ -42,13 +40,12 @@ public class UpgradeSystemVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the system vm") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=SystemVmResponse.class, + required=true, description="The ID of the system vm") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, - description="the service offering ID to apply to the system vm") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the system vm") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -71,7 +68,7 @@ public class UpgradeSystemVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -81,16 +78,16 @@ public class UpgradeSystemVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } - + VirtualMachine result = _mgr.upgradeSystemVM(this); if (result != null) { SystemVmResponse response = _responseGenerator.createSystemVmResponse(result); diff --git a/api/src/com/cloud/api/commands/PrepareTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java similarity index 64% rename from api/src/com/cloud/api/commands/PrepareTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java index cb2cd2fa3f4..74f33915551 100644 --- a/api/src/com/cloud/api/commands/PrepareTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/template/PrepareTemplateCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.template; import java.util.List; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(responseObject=TemplateResponse.class, description="load template into primary storage") +@APICommand(name = "prepareTemplate", responseObject=TemplateResponse.class, description="load template into primary storage") public class PrepareTemplateCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(PrepareTemplateCmd.class.getName()); @@ -40,23 +40,23 @@ public class PrepareTemplateCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, required=true, type=CommandType.LONG, description="zone ID of the template to be prepared in primary storage(s).") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="zone ID of the template to be prepared in primary storage(s).") private Long zoneId; - - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, required=true, type=CommandType.LONG, description="template ID of the template to be prepared in primary storage(s).") + + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="template ID of the template to be prepared in primary storage(s).") private Long templateId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getZoneId() { - return zoneId; + return zoneId; } - + public Long getTemplateId() { return templateId; } @@ -69,20 +69,20 @@ public class PrepareTemplateCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() { ListResponse response = new ListResponse(); - - VirtualMachineTemplate vmTemplate = _templateService.prepareTemplate(templateId, zoneId); - List templateResponses = _responseGenerator.createTemplateResponses(vmTemplate.getId(), zoneId, true); + + VirtualMachineTemplate vmTemplate = _templateService.prepareTemplate(templateId, zoneId); + List templateResponses = _responseGenerator.createTemplateResponses(vmTemplate.getId(), zoneId, true); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/AddTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java index 7f3f07eb02f..1759ff7e8e6 100644 --- a/api/src/com/cloud/api/commands/AddTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/AddTrafficTypeCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +33,7 @@ import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds traffic type to a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") +@APICommand(name = "addTrafficType", description="Adds traffic type to a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddTrafficTypeCmd.class.getName()); @@ -42,30 +42,30 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, required=true, description="the trafficType to be added to the physical network") private String trafficType; - + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenLabel; - + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") private String kvmLabel; - + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareLabel; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="The VLAN id to be used for Management traffic by VMware host") private String vlan; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + @Override public String getEntityTable() { return "physical_network_traffic_types"; @@ -90,10 +90,10 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public String getVmwareLabel() { return vmwareLabel; } - + public String getSimulatorLabel() { - //simulators will have no labels - return null; + //simulators will have no labels + return null; } public void setVlan(String vlan) { @@ -112,12 +112,12 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ UserContext.current().setEventDetails("TrafficType Id: "+getEntityId()); @@ -138,19 +138,19 @@ public class AddTrafficTypeCmd extends BaseAsyncCreateCmd { setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add traffic type to physical network"); - } + } } @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_CREATE; } - + @Override public String getEventDescription() { return "Adding physical network traffic type: " + getEntityId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.TrafficType; diff --git a/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java index 35089d37f3d..bb665fbfd58 100644 --- a/api/src/com/cloud/api/commands/DeleteTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/DeleteTrafficTypeCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(description="Deletes traffic type of a physical network", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteTrafficType", description="Deletes traffic type of a physical network", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteTrafficTypeCmd.class.getName()); @@ -39,19 +39,19 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network_traffic_types") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TrafficTypeResponse.class, + required=true, description="traffic type id") private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +60,12 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _networkService.deletePhysicalNetworkTrafficType(getId()); @@ -81,7 +81,7 @@ public class DeleteTrafficTypeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting Traffic Type: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_DELETE; diff --git a/api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java old mode 100755 new mode 100644 similarity index 53% rename from api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java index 8b6bde43055..3cd00c02af7 --- a/api/src/com/cloud/api/commands/ListTrafficTypeImplementorsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypeImplementorsCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TrafficTypeImplementorResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TrafficTypeImplementorResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -36,51 +33,51 @@ import com.cloud.network.Networks.TrafficType; import com.cloud.user.Account; import com.cloud.utils.Pair; -@Implementation(description="Lists implementors of implementor of a network traffic type or implementors of all network traffic types", responseObject=TrafficTypeImplementorResponse.class, since="3.0.0") +@APICommand(name = "listTrafficTypeImplementors", description="Lists implementors of implementor of a network traffic type or implementors of all network traffic types", responseObject=TrafficTypeImplementorResponse.class, since="3.0.0") public class ListTrafficTypeImplementorsCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); - private static final String _name = "listtraffictypeimplementorsresponse"; - + public static final Logger s_logger = Logger.getLogger(ListTrafficTypeImplementorsCmd.class); + private static final String _name = "listtraffictypeimplementorsresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="Optional. The network traffic type, if specified, return its implementor. Otherwise, return all traffic types with their implementor") private String trafficType; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getTrafficType() { - return trafficType; + return trafficType; } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - List> results = _networkService.listTrafficTypeImplementor(this); - ListResponse response = new ListResponse(); - List responses= new ArrayList(); - for (Pair r : results) { - TrafficTypeImplementorResponse p = new TrafficTypeImplementorResponse(); - p.setTrafficType(r.first().toString()); - p.setImplementor(r.second()); - p.setObjectName("traffictypeimplementorresponse"); - responses.add(p); - } - - response.setResponses(responses); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + List> results = _networkService.listTrafficTypeImplementor(this); + ListResponse response = new ListResponse(); + List responses= new ArrayList(); + for (Pair r : results) { + TrafficTypeImplementorResponse p = new TrafficTypeImplementorResponse(); + p.setTrafficType(r.first().toString()); + p.setImplementor(r.second()); + p.setObjectName("traffictypeimplementorresponse"); + responses.add(p); + } + + response.setResponses(responses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - - @Override - public String getCommandName() { - return _name; - } + + @Override + public String getCommandName() { + return _name; + } } diff --git a/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java old mode 100755 new mode 100644 similarity index 73% rename from api/src/com/cloud/api/commands/ListTrafficTypesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java index 59ad2a745a4..2cbb13df0d3 --- a/api/src/com/cloud/api/commands/ListTrafficTypesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/ListTrafficTypesCmd.java @@ -14,26 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; +import com.cloud.utils.Pair; - -@Implementation(description="Lists traffic types of a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") +@APICommand(name = "listTrafficTypes", description="Lists traffic types of a given physical network.", responseObject=ProviderResponse.class, since="3.0.0") public class ListTrafficTypesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListTrafficTypesCmd.class.getName()); private static final String _name = "listtraffictypesresponse"; @@ -41,14 +41,14 @@ public class ListTrafficTypesCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } @@ -69,18 +69,18 @@ public class ListTrafficTypesCmd extends BaseListCmd { public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - List trafficTypes = _networkService.listTrafficTypes(getPhysicalNetworkId()); + Pair, Integer> trafficTypes = _networkService.listTrafficTypes(getPhysicalNetworkId()); ListResponse response = new ListResponse(); List trafficTypesResponses = new ArrayList(); - for (PhysicalNetworkTrafficType trafficType : trafficTypes) { + for (PhysicalNetworkTrafficType trafficType : trafficTypes.first()) { TrafficTypeResponse trafficTypeResponse = _responseGenerator.createTrafficTypeResponse(trafficType); trafficTypesResponses.add(trafficTypeResponse); } - response.setResponses(trafficTypesResponses); + response.setResponses(trafficTypesResponses, trafficTypes.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java index e23967a173c..279c2b858d3 100644 --- a/api/src/com/cloud/api/commands/UpdateTrafficTypeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/usage/UpdateTrafficTypeCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.usage; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TrafficTypeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.PhysicalNetworkTrafficType; import com.cloud.user.Account; -@Implementation(description="Updates traffic type of a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") +@APICommand(name = "updateTrafficType", description="Updates traffic type of a physical network", responseObject=TrafficTypeResponse.class, since="3.0.0") public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateTrafficTypeCmd.class.getName()); @@ -40,25 +39,25 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network_traffic_types") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="traffic type id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TrafficTypeResponse.class, + required=true, description="traffic type id") private Long id; - + @Parameter(name=ApiConstants.XEN_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenLabel; - + @Parameter(name=ApiConstants.KVM_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a KVM host") private String kvmLabel; - + @Parameter(name=ApiConstants.VMWARE_NETWORK_LABEL, type=CommandType.STRING, description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareLabel; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -69,11 +68,11 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getKvmLabel() { return kvmLabel; } - + public String getVmwareLabel() { return vmwareLabel; - } - + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -82,12 +81,12 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ PhysicalNetworkTrafficType result = _networkService.updatePhysicalNetworkTrafficType(getId(), getXenLabel(), getKvmLabel(), getVmwareLabel()); @@ -104,7 +103,7 @@ public class UpdateTrafficTypeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Updating Traffic Type: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_TRAFFIC_TYPE_UPDATE; diff --git a/api/src/com/cloud/api/commands/CreateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java index fc10437e257..2045abf4e93 100644 --- a/api/src/com/cloud/api/commands/CreateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/CreateUserCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Creates a user for an account that already exists", responseObject=UserResponse.class) +@APICommand(name = "createUser", description="Creates a user for an account that already exists", responseObject=UserResponse.class) public class CreateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateUserCmd.class.getName()); @@ -42,8 +42,8 @@ public class CreateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Creates the user under the specified account. If no account is specified, the username will be used as the account name.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Creates the user under the specified domain. Has to be accompanied with the account parameter") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="Creates the user under the specified domain. Has to be accompanied with the account parameter") private Long domainId; @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, required=true, description="email") @@ -108,7 +108,7 @@ public class CreateUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -127,7 +127,7 @@ public class CreateUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserName: "+getUserName()+", FirstName :"+getFirstName()+", LastName: "+getLastName()); @@ -140,4 +140,4 @@ public class CreateUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java index e43649591fc..a43501e7641 100644 --- a/api/src/com/cloud/api/commands/DeleteUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DeleteUserCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Creates a user for an account", responseObject=UserResponse.class) +@APICommand(name = "deleteUser", description="Creates a user for an account", responseObject=UserResponse.class) public class DeleteUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteUserCmd.class.getName()); @@ -39,8 +38,7 @@ public class DeleteUserCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Deletes a user") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, required=true, description="Deletes a user") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +57,7 @@ public class DeleteUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -69,7 +67,7 @@ public class DeleteUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); @@ -81,4 +79,4 @@ public class DeleteUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DisableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DisableUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java index 407042dfc40..f483e628928 100644 --- a/api/src/com/cloud/api/commands/DisableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/DisableUserCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.user.Account; @@ -33,17 +32,17 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Disables a user account", responseObject=UserResponse.class) +@APICommand(name = "disableUser", description="Disables a user account", responseObject=UserResponse.class) public class DisableUserCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DisableUserCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DisableUserCmd.class.getName()); private static final String s_name = "disableuserresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Disables user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Disables user by user ID.") private Long id; ///////////////////////////////////////////////////// @@ -83,20 +82,20 @@ public class DisableUserCmd extends BaseAsyncCmd { return "disabling user: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); UserAccount user = _accountService.disableUser(getId()); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable user"); } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.User; diff --git a/api/src/com/cloud/api/commands/EnableUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/EnableUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java index 914d59bb4ea..e444aa395d2 100644 --- a/api/src/com/cloud/api/commands/EnableUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/EnableUserCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Enables a user account", responseObject=UserResponse.class) +@APICommand(name = "enableUser", description="Enables a user account", responseObject=UserResponse.class) public class EnableUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(EnableUserCmd.class.getName()); private static final String s_name = "enableuserresponse"; @@ -39,8 +35,8 @@ public class EnableUserCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Enables user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Enables user by user ID.") private Long id; @@ -60,7 +56,7 @@ public class EnableUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -70,14 +66,14 @@ public class EnableUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); UserAccount user = _accountService.enableUser(getId()); if (user != null){ UserResponse response = _responseGenerator.createUserResponse(user); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable user"); diff --git a/api/src/com/cloud/api/commands/GetUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/GetUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java index 465e440a0f3..2ffe4ab245d 100644 --- a/api/src/com/cloud/api/commands/GetUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/GetUserCmd.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.UserAccount; -@Implementation(description="Find user account by API key", responseObject=UserResponse.class) +@APICommand(name = "getUser", description="Find user account by API key", responseObject=UserResponse.class) public class GetUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetUserCmd.class.getName()); @@ -43,32 +43,32 @@ public class GetUserCmd extends BaseCmd { /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getApiKey() { - return apiKey; - } + public String getApiKey() { + return apiKey; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - return 0; - } - + @Override + public long getEntityOwnerId() { + return 0; + } + @Override public void execute(){ UserAccount result = _accountService.getUserByApiKey(getApiKey()); if(result != null){ - UserResponse response = _responseGenerator.createUserResponse(result); - response.setResponseName(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); + UserResponse response = _responseGenerator.createUserResponse(result); + response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); + this.setResponseObject(response); } else { throw new InvalidParameterValueException("User with specified API key does not exist"); } diff --git a/api/src/com/cloud/api/commands/ListUsersCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/ListUsersCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java index ec3a1bb54f1..3d68e2f48c9 100644 --- a/api/src/com/cloud/api/commands/ListUsersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/ListUsersCmd.java @@ -14,23 +14,18 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.user.UserAccount; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserResponse; -@Implementation(description="Lists user accounts", responseObject=UserResponse.class) +@APICommand(name = "listUsers", description="Lists user accounts", responseObject=UserResponse.class) public class ListUsersCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListUsersCmd.class.getName()); @@ -43,8 +38,7 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.LONG, description="List users by account type. Valid types include admin, domain-admin, read-only-admin, or user.") private Long accountType; - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="List user by ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, description="List user by ID.") private Long id; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="List users by state of the user account.") @@ -78,21 +72,14 @@ public class ListUsersCmd extends BaseListAccountResourcesCmd { /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _accountService.searchForUsers(this); - ListResponse response = new ListResponse(); - List userResponses = new ArrayList(); - for (UserAccount user : result) { - UserResponse userResponse = _responseGenerator.createUserResponse(user); - userResponses.add(userResponse); - } - response.setResponses(userResponses); + ListResponse response = _queryService.searchForUsers(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/LockUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/LockUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java index 5d2f58cd3dd..622b4e9a023 100644 --- a/api/src/com/cloud/api/commands/LockUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/LockUserCmd.java @@ -14,22 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; -@Implementation(description="Locks a user account", responseObject=UserResponse.class) +@APICommand(name = "lockUser", description="Locks a user account", responseObject=UserResponse.class) public class LockUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(LockUserCmd.class.getName()); @@ -39,8 +38,8 @@ public class LockUserCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Locks user by user ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="Locks user by user ID.") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +58,7 @@ public class LockUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -69,7 +68,7 @@ public class LockUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserAccount user = _accountService.lockUser(getId()); diff --git a/api/src/com/cloud/api/commands/RegisterCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/RegisterCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java index dff8ec9ae32..06ffc537995 100644 --- a/api/src/com/cloud/api/commands/RegisterCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/RegisterCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.RegisterResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.RegisterResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; -@Implementation(responseObject=RegisterResponse.class, description="This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user") +@APICommand(name = "registerUserKeys", responseObject=RegisterResponse.class, description="This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user") public class RegisterCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterCmd.class.getName()); @@ -36,9 +36,9 @@ public class RegisterCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="User id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="User id") private Long id; ///////////////////////////////////////////////////// @@ -56,7 +56,7 @@ public class RegisterCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); diff --git a/api/src/com/cloud/api/commands/UpdateUserCmd.java b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/UpdateUserCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java index 634b5d6cc14..170d852ff58 100644 --- a/api/src/com/cloud/api/commands/UpdateUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/user/UpdateUserCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.user; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -@Implementation(description="Updates a user account", responseObject=UserResponse.class) +@APICommand(name = "updateUser", description="Updates a user account", responseObject=UserResponse.class) public class UpdateUserCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateUserCmd.class.getName()); @@ -49,8 +45,8 @@ public class UpdateUserCmd extends BaseCmd { @Parameter(name=ApiConstants.FIRSTNAME, type=CommandType.STRING, description="first name") private String firstname; - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="User id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserResponse.class, + required=true, description="User uuid") private Long id; @Parameter(name=ApiConstants.LASTNAME, type=CommandType.STRING, description="last name") @@ -116,7 +112,7 @@ public class UpdateUserCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { User user = _entityMgr.findById(User.class, getId()); @@ -126,7 +122,7 @@ public class UpdateUserCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("UserId: "+getId()); @@ -139,4 +135,4 @@ public class UpdateUserCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update user"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java index 63eda633858..c9717480e44 100644 --- a/api/src/com/cloud/api/commands/CreateVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/CreateVlanIpRangeCmd.java @@ -14,17 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.Vlan; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -32,9 +34,9 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; -@Implementation(description="Creates a VLAN IP range.", responseObject=VlanIpRangeResponse.class) +@APICommand(name = "createVlanIpRange", description="Creates a VLAN IP range.", responseObject=VlanIpRangeResponse.class) public class CreateVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(CreateVlanIpRangeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVlanIpRangeCmd.class.getName()); private static final String s_name = "createvlaniprangeresponse"; @@ -44,13 +46,13 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="project who will own the VLAN. If VLAN is Zone wide, this parameter should be ommited") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a VLAN") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a VLAN") private Long domainId; @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the VLAN IP range") @@ -65,29 +67,29 @@ public class CreateVlanIpRangeCmd extends BaseCmd { @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the VLAN IP range") private String netmask; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="optional parameter. Have to be specified for Direct Untagged vlan only.") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="optional parameter. Have to be specified for Direct Untagged vlan only.") private Long podId; @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, required=true, description="the beginning IP address in the VLAN IP range") private String startIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the VLAN. If not specified," + - " will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged") + " will be defaulted to the vlan of the network or if vlan of the network is null - to Untagged") private String vlan; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the VLAN IP range") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the VLAN IP range") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="the network id") private Long networkID; - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the physical network id") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the physical network id") private Long physicalNetworkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -147,17 +149,17 @@ public class CreateVlanIpRangeCmd extends BaseCmd { return physicalNetworkId; } - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException{ try { @@ -175,6 +177,6 @@ public class CreateVlanIpRangeCmd extends BaseCmd { } catch (InsufficientCapacityException ex) { s_logger.info(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java index f44c92ee3f9..f12b2175aef 100644 --- a/api/src/com/cloud/api/commands/DeleteVlanIpRangeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/DeleteVlanIpRangeCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Creates a VLAN IP range.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVlanIpRange", description="Creates a VLAN IP range.", responseObject=SuccessResponse.class) public class DeleteVlanIpRangeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVlanIpRangeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteVlanIpRangeCmd.class.getName()); private static final String s_name = "deletevlaniprangeresponse"; @@ -37,8 +37,8 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the VLAN IP range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + required=true, description="the id of the VLAN IP range") private Long id; ///////////////////////////////////////////////////// @@ -57,12 +57,12 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _configService.deleteVlanIpRange(this); @@ -73,4 +73,4 @@ public class DeleteVlanIpRangeCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete vlan ip range"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java similarity index 59% rename from api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java index 039628ab361..9b6b997c4b8 100644 --- a/api/src/com/cloud/api/commands/ListVlanIpRangesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vlan/ListVlanIpRangesCmd.java @@ -14,25 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vlan; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; import com.cloud.dc.Vlan; +import com.cloud.utils.Pair; -@Implementation(description="Lists all VLAN IP ranges.", responseObject=VlanIpRangeResponse.class) +@APICommand(name = "listVlanIpRanges", description="Lists all VLAN IP ranges.", responseObject=VlanIpRangeResponse.class) public class ListVlanIpRangesCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListVlanIpRangesCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListVlanIpRangesCmd.class.getName()); private static final String s_name = "listvlaniprangesresponse"; @@ -42,39 +48,39 @@ public class ListVlanIpRangesCmd extends BaseListCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account with which the VLAN IP range is associated. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="project who will own the VLAN") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="project who will own the VLAN") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID with which the VLAN IP range is associated. If used with the account parameter, returns all VLAN IP ranges for that account in the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID with which the VLAN IP range is associated. If used with the account parameter, returns all VLAN IP ranges for that account in the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=false, description="the ID of the VLAN IP range") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + required=false, description="the ID of the VLAN IP range") private Long id; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the Pod ID of the VLAN IP range") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType = PodResponse.class, + description="the Pod ID of the VLAN IP range") private Long podId; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the VLAN. Default is an \"untagged\" VLAN.") private String vlan; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the VLAN IP range") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the VLAN IP range") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="network id of the VLAN IP range") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="network id of the VLAN IP range") private Long networkId; - + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="true if VLAN is of Virtual type, false if Direct") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="physical network id of the VLAN IP range") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="physical network id of the VLAN IP range") private Long physicalNetworkId; ///////////////////////////////////////////////////// @@ -108,40 +114,40 @@ public class ListVlanIpRangesCmd extends BaseListCmd { public Long getNetworkId() { return networkId; } - + public Boolean getForVirtualNetwork() { - return forVirtualNetwork; - } - + return forVirtualNetwork; + } + public Long getProjectId() { return projectId; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override + + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ - List vlans = _mgr.searchForVlans(this); + Pair, Integer> vlans = _mgr.searchForVlans(this); ListResponse response = new ListResponse(); List vlanResponses = new ArrayList(); - for (Vlan vlan : vlans) { + for (Vlan vlan : vlans.first()) { VlanIpRangeResponse vlanResponse = _responseGenerator.createVlanIpRangeResponse(vlan); vlanResponse.setObjectName("vlaniprange"); vlanResponses.add(vlanResponse); } - response.setResponses(vlanResponses); + response.setResponses(vlanResponses, vlans.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/AssignVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java similarity index 65% rename from api/src/com/cloud/api/commands/AssignVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java index be28cc037d4..3482ec756fb 100644 --- a/api/src/com/cloud/api/commands/AssignVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/AssignVMCmd.java @@ -14,31 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; -import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.ZoneResponse; -import com.cloud.async.AsyncJob; -import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Move a user VM to another user under same domain.", responseObject=UserVmResponse.class, since="3.0.0") +@APICommand(name = "assignVirtualMachine", description="Move a user VM to another user under same domain.", responseObject=UserVmResponse.class, since="3.0.0") public class AssignVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AssignVMCmd.class.getName()); @@ -47,27 +41,27 @@ public class AssignVMCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the vm ID of the user VM to be moved") + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="the vm ID of the user VM to be moved") private Long virtualMachineId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="account name of the new VM owner.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="domain id of the new VM owner.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="domain id of the new VM owner.") private Long domainId; //Network information - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of network ids that will be part of VM network after move in advanced network setting.") + @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=NetworkResponse.class, + description="list of network ids that will be part of VM network after move in advanced network setting.") private List networkIds; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is moved in a zone with Basic Network support.") + @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is moved in a zone with Basic Network support.") private List securityGroupIdList; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -80,17 +74,17 @@ public class AssignVMCmd extends BaseCmd { return accountName; } - public Long getDomainId() { - return domainId; - } - - public List getNetworkIds() { - return networkIds; - } + public Long getDomainId() { + return domainId; + } - public List getSecurityGroupIdList() { - return securityGroupIdList; - } + public List getNetworkIds() { + return networkIds; + } + + public List getSecurityGroupIdList() { + return securityGroupIdList; + } ///////////////////////////////////////////////////// @@ -101,22 +95,22 @@ public class AssignVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ try { UserVm userVm = _userVmService.moveVMToUser(this); if (userVm == null){ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm"); - } - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + } + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); }catch (Exception e){ e.printStackTrace(); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to move vm " + e.getMessage()); } - + } @Override diff --git a/api/src/com/cloud/api/commands/MigrateVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java similarity index 61% rename from api/src/com/cloud/api/commands/MigrateVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java index c292a2e4e1b..5bb694da655 100644 --- a/api/src/com/cloud/api/commands/MigrateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/MigrateVMCmd.java @@ -14,18 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -39,7 +37,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.vm.VirtualMachine; -@Implementation(description="Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool", responseObject=UserVmResponse.class) +@APICommand(name = "migrateVirtualMachine", description="Attempts Migration of a VM to a different host or Root volume of the vm to a different storage pool", responseObject=UserVmResponse.class) public class MigrateVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MigrateVMCmd.class.getName()); @@ -49,16 +47,16 @@ public class MigrateVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, required=false, description="Destination Host ID to migrate VM to. Required for live migrating a VM from host to host") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + required=false, description="Destination Host ID to migrate VM to. Required for live migrating a VM from host to host") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, required=false, description="Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume") + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, entityType=StoragePoolResponse.class, + required=false, description="Destination storage pool ID to migrate VM volumes to. Required for migrating the root disk volume") private Long storageId; ///////////////////////////////////////////////////// @@ -72,9 +70,9 @@ public class MigrateVMCmd extends BaseAsyncCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getStoragePoolId() { - return storageId; + return storageId; } @@ -86,7 +84,7 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -106,66 +104,66 @@ public class MigrateVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId(); } - + @Override public void execute(){ - if (getHostId() == null && getStoragePoolId() == null) { - throw new InvalidParameterValueException("either hostId or storageId must be specified"); - } - - if (getHostId() != null && getStoragePoolId() != null) { - throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); - } - + if (getHostId() == null && getStoragePoolId() == null) { + throw new InvalidParameterValueException("either hostId or storageId must be specified"); + } + + if (getHostId() != null && getStoragePoolId() != null) { + throw new InvalidParameterValueException("only one of hostId and storageId can be specified"); + } + UserVm userVm = _userVmService.getUserVm(getVirtualMachineId()); if (userVm == null) { throw new InvalidParameterValueException("Unable to find the VM by id=" + getVirtualMachineId()); } - + Host destinationHost = null; if (getHostId() != null) { - destinationHost = _resourceService.getHost(getHostId()); - if (destinationHost == null) { - throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); + destinationHost = _resourceService.getHost(getHostId()); + if (destinationHost == null) { + throw new InvalidParameterValueException("Unable to find the host to migrate the VM, host id=" + getHostId()); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to host Id: "+ getHostId()); } - + StoragePool destStoragePool = null; if (getStoragePoolId() != null) { - destStoragePool = _storageService.getStoragePool(getStoragePoolId()); - if (destStoragePool == null) { - throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); - } - UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); + destStoragePool = _storageService.getStoragePool(getStoragePoolId()); + if (destStoragePool == null) { + throw new InvalidParameterValueException("Unable to find the storage pool to migrate the VM"); + } + UserContext.current().setEventDetails("VM Id: " + getVirtualMachineId() + " to storage pool Id: "+ getStoragePoolId()); } - + try{ - VirtualMachine migratedVm = null; - if (getHostId() != null) { - migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); - } else if (getStoragePoolId() != null) { - migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); - } - if (migratedVm != null) { + VirtualMachine migratedVm = null; + if (getHostId() != null) { + migratedVm = _userVmService.migrateVirtualMachine(getVirtualMachineId(), destinationHost); + } else if (getStoragePoolId() != null) { + migratedVm = _userVmService.vmStorageMigration(getVirtualMachineId(), destStoragePool); + } + if (migratedVm != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", (UserVm)migratedVm).get(0); response.setResponseName(getCommandName()); this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); - } + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate vm"); + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (ManagementServerException e) { + } catch (ManagementServerException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } catch (VirtualMachineMigrationException e) { + } catch (VirtualMachineMigrationException e) { s_logger.warn("Exception: ", e); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, e.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/RecoverVMCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/RecoverVMCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java index 50dd5e7c820..f8308614b89 100644 --- a/api/src/com/cloud/api/commands/RecoverVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vm/RecoverVMCmd.java @@ -14,22 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.ResourceAllocationException; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Recovers a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "recoverVirtualMachine", description="Recovers a virtual machine.", responseObject=UserVmResponse.class) public class RecoverVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RecoverVMCmd.class.getName()); @@ -39,8 +38,8 @@ public class RecoverVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -59,7 +58,7 @@ public class RecoverVMCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -69,7 +68,7 @@ public class RecoverVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute() throws ResourceAllocationException{ UserVm result = _userVmService.recoverVirtualMachine(this); @@ -80,6 +79,6 @@ public class RecoverVMCmd extends BaseCmd { } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recover vm"); } - + } } diff --git a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java index c56f9affc4b..7950b877cec 100644 --- a/api/src/com/cloud/api/commands/CreatePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreatePrivateGatewayCmd.java @@ -14,19 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +39,7 @@ import com.cloud.network.vpc.PrivateGateway; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Creates a private gateway", responseObject=PrivateGatewayResponse.class) +@APICommand(name = "createPrivateGateway", description="Creates a private gateway", responseObject=PrivateGatewayResponse.class) public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreatePrivateGatewayCmd.class.getName()); @@ -47,27 +48,27 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="the gateway of the Private gateway") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, required=true, description="the netmask of the Private gateway") private String netmask; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, required=true, description="the IP address of the Private gateaway") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, required=true, description="the Vlan for the private gateway") private String vlan; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="the VPC network belongs to") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + required=true, description="the VPC network belongs to") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,7 +80,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getVlan() { return vlan; } - + public String getNetmask() { return netmask; } @@ -87,11 +88,11 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getStartIp() { return ipAddress; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getVpcId() { return vpcId; } @@ -103,8 +104,8 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - - + + @Override public void create() throws ResourceAllocationException { PrivateGateway result = null; @@ -119,16 +120,16 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } - + if (result != null) { this.setEntityId(result.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override - public void execute() throws InsufficientCapacityException, ConcurrentOperationException, + public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException, ResourceUnavailableException { PrivateGateway result = _vpcService.applyVpcPrivateGateway(getEntityId(), true); if (result != null) { @@ -139,7 +140,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private gateway"); } } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -154,13 +155,13 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating private gateway"; } - + @Override public String getEntityTable() { return "vpc_gateways"; } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -174,7 +175,7 @@ public class CreatePrivateGatewayCmd extends BaseAsyncCreateCmd { } return vpc.getId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; diff --git a/api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java index 78ce2856679..a0abe99f826 100644 --- a/api/src/com/cloud/api/commands/CreateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/CreateVPCOfferingCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; import com.cloud.network.vpc.VpcOffering; import com.cloud.user.Account; -@Implementation(description="Creates VPC offering", responseObject=VpcOfferingResponse.class) +@APICommand(name = "createVPCOffering", description="Creates VPC offering", responseObject=VpcOfferingResponse.class) public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ public static final Logger s_logger = Logger.getLogger(CreateVPCOfferingCmd.class.getName()); private static final String _name = "createvpcofferingresponse"; @@ -41,22 +36,22 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the vpc offering") private String vpcOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of " + - "the vpc offering") + "the vpc offering") private String displayText; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="services supported by the vpc offering") private List supportedServices; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcOfferingName() { return vpcOfferingName; } @@ -68,7 +63,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ public List getSupportedServices() { return supportedServices; } - + @Override public void create() throws ResourceAllocationException { @@ -79,7 +74,7 @@ public class CreateVPCOfferingCmd extends BaseAsyncCreateCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC offering"); } } - + @Override public void execute() { VpcOffering vpc = _vpcService.getVpcOffering(this.getEntityId()); diff --git a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java index 2767efdae65..4a1e8d05912 100644 --- a/api/src/com/cloud/api/commands/DeletePrivateGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeletePrivateGatewayCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,7 +35,7 @@ import com.cloud.network.vpc.VpcGateway; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Private gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deletePrivateGateway", description="Deletes a Private gateway", responseObject=SuccessResponse.class) public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePrivateGatewayCmd.class.getName()); private static final String s_name = "deleteprivategatewayresponse"; @@ -44,8 +44,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the private gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = PrivateGatewayResponse.class, + required=true, description="the ID of the private gateway") private Long id; ///////////////////////////////////////////////////// @@ -55,7 +55,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -63,7 +63,7 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_PRIVATE_GATEWAY_DELETE; @@ -73,16 +73,16 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting private gateway id=" + id); } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute() throws ResourceUnavailableException, ConcurrentOperationException { UserContext.current().setEventDetails("Network ACL Id: " + id); - boolean result = _vpcService.deleteVpcPrivateGateway(id); + boolean result = _vpcService.deleteVpcPrivateGateway(id); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -90,8 +90,8 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete private gateway"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -105,10 +105,10 @@ public class DeletePrivateGatewayCmd extends BaseAsyncCmd { } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.PrivateGateway; } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java index 88d40e58b4c..231f2ee2955 100644 --- a/api/src/com/cloud/api/commands/DeleteVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/DeleteVPCOfferingCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; -@Implementation(description="Deletes VPC offering", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVPCOffering", description="Deletes VPC offering", responseObject=SuccessResponse.class) public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVPCOfferingCmd.class.getName()); private static final String s_name = "deletevpcofferingresponse"; @@ -38,11 +38,10 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the VPC offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcOfferingResponse.class, + required=true, description="the ID of the VPC offering") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +50,6 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -60,12 +58,12 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ boolean result = _vpcService.deleteVpcOffering(getId()); @@ -76,7 +74,7 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC offering"); } } - + @Override public String getEventType(){ return EventTypes.EVENT_VPC_OFFERING_DELETE; @@ -87,6 +85,6 @@ public class DeleteVPCOfferingCmd extends BaseAsyncCmd{ public String getEventDescription() { return "Deleting VPC offering id=" + getId(); } - - + + } diff --git a/api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java index 77f2c030cdb..65df48e3e1f 100644 --- a/api/src/com/cloud/api/commands/UpdateVPCOfferingCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/vpc/UpdateVPCOfferingCmd.java @@ -14,23 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.vpc; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.network.vpc.VpcOffering; import com.cloud.user.Account; -@Implementation(description="Updates VPC offering", responseObject=VpcOfferingResponse.class) +@APICommand(name = "updateVPCOffering", description="Updates VPC offering", responseObject=VpcOfferingResponse.class) public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(UpdateVPCOfferingCmd.class.getName()); private static final String _name = "updatevpcofferingresponse"; @@ -38,33 +33,33 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC offering") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcOfferingResponse.class, + description="the id of the VPC offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the VPC offering") private String vpcOffName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the VPC offering") private String displayText; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="update state for the VPC offering; " + - "supported states - Enabled/Disabled") + "supported states - Enabled/Disabled") private String state; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcOfferingName() { return vpcOffName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } @@ -72,7 +67,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -81,7 +76,7 @@ public class UpdateVPCOfferingCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/CreateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java old mode 100755 new mode 100644 similarity index 84% rename from api/src/com/cloud/api/commands/CreateZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java index 1e9170d45e2..e49f2439288 --- a/api/src/com/cloud/api/commands/CreateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/CreateZoneCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates a Zone.", responseObject=ZoneResponse.class) +@APICommand(name = "createZone", description="Creates a Zone.", responseObject=ZoneResponse.class) public class CreateZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateZoneCmd.class.getName()); @@ -60,16 +61,16 @@ public class CreateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="Network domain name for the networks in the zone") private String domain; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the containing domain, null for public zones") - private Long domainId; - + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the containing domain, null for public zones") + private Long domainId; + @Parameter(name=ApiConstants.NETWORK_TYPE, type=CommandType.STRING, required=true, description="network type of the zone, can be Basic or Advanced") - private String networkType; - + private String networkType; + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this Zone for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.SECURITY_GROUP_EANBLED, type=CommandType.BOOLEAN, description="true if network is security group enabled, false otherwise") private Boolean securitygroupenabled; @@ -109,17 +110,17 @@ public class CreateZoneCmd extends BaseCmd { } public Long getDomainId(){ - return domainId; + return domainId; } - + public String getNetworkType(){ return networkType; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public Boolean getSecuritygroupenabled() { if (securitygroupenabled == null) { return false; @@ -140,16 +141,16 @@ public class CreateZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - UserContext.current().setEventDetails("Zone Name: "+getZoneName()); - DataCenter result = _configService.createZone(this); + UserContext.current().setEventDetails("Zone Name: "+getZoneName()); + DataCenter result = _configService.createZone(this); if (result != null){ ZoneResponse response = _responseGenerator.createZoneResponse(result,false); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DeleteZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/DeleteZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java index c695d8fdf83..d09c7fff891 100644 --- a/api/src/com/cloud/api/commands/DeleteZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/DeleteZoneCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Zone.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteZone", description="Deletes a Zone.", responseObject=SuccessResponse.class) public class DeleteZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteZoneCmd.class.getName()); @@ -38,8 +35,8 @@ public class DeleteZoneCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the Zone") private Long id; @@ -60,7 +57,7 @@ public class DeleteZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; @@ -68,8 +65,8 @@ public class DeleteZoneCmd extends BaseCmd { @Override public void execute(){ - UserContext.current().setEventDetails("Zone Id: "+getId()); - boolean result = _configService.deleteZone(this); + UserContext.current().setEventDetails("Zone Id: "+getId()); + boolean result = _configService.deleteZone(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java similarity index 56% rename from api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java index 7f06926070c..816befbd029 100644 --- a/api/src/com/cloud/api/commands/MarkDefaultZoneForAccountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/MarkDefaultZoneForAccountCmd.java @@ -15,23 +15,25 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import org.apache.log4j.Logger; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ApiConstants; -import com.cloud.api.IdentityMapper; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.user.Account; import com.cloud.event.EventTypes; import com.cloud.async.AsyncJob; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; -@Implementation(description="Marks a default zone for this account", responseObject=AccountResponse.class, since="4.0") +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.BaseCmd; + +@APICommand(name = "markDefaultZoneForAccount", description="Marks a default zone for this account", responseObject=AccountResponse.class, since="4.0") public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(MarkDefaultZoneForAccountCmd.class.getName()); @@ -41,16 +43,16 @@ public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { ////////////////API parameters ////////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="Name of the account that is to be marked.") + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, entityType=AccountResponse.class, + required=true, description="Name of the account that is to be marked.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="Marks the account that belongs to the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + required=true, description="Marks the account that belongs to the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="The Zone ID with which the account is to be marked.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="The Zone ID with which the account is to be marked.") private Long defaultZoneId; ///////////////////////////////////////////////////// @@ -68,47 +70,47 @@ public class MarkDefaultZoneForAccountCmd extends BaseAsyncCmd { public Long getDefaultZoneId() { return defaultZoneId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { - return s_name; + return s_name; } @Override public long getEntityOwnerId() { - return Account.ACCOUNT_ID_SYSTEM; + return Account.ACCOUNT_ID_SYSTEM; } - + @Override public String getEventType() { - return EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE; + return EventTypes.EVENT_ACCOUNT_MARK_DEFAULT_ZONE; } - + @Override public String getEventDescription() { - return "Marking account with the default zone: " + getDefaultZoneId(); + return "Marking account with the default zone: " + getDefaultZoneId(); } @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.Account; } - + @Override public void execute(){ - Account result = _configService.markDefaultZone(getAccountName(),getDomainId(), getDefaultZoneId()); - if (result != null) { - AccountResponse response = _responseGenerator.createAccountResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to mark the account with the default zone"); - } + Account result = _configService.markDefaultZone(getAccountName(),getDomainId(), getDefaultZoneId()); + if (result != null) { + AccountResponse response = _responseGenerator.createAccountResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to mark the account with the default zone"); + } } } diff --git a/api/src/com/cloud/api/commands/UpdateZoneCmd.java b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java old mode 100755 new mode 100644 similarity index 87% rename from api/src/com/cloud/api/commands/UpdateZoneCmd.java rename to api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java index 1fa0f79da6b..0bfd1a31a0f --- a/api/src/com/cloud/api/commands/UpdateZoneCmd.java +++ b/api/src/org/apache/cloudstack/api/command/admin/zone/UpdateZoneCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.admin.zone; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates a Zone.", responseObject=ZoneResponse.class) +@APICommand(name = "updateZone", description="Updates a Zone.", responseObject=ZoneResponse.class) public class UpdateZoneCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateZoneCmd.class.getName()); @@ -51,8 +47,8 @@ public class UpdateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.GUEST_CIDR_ADDRESS, type=CommandType.STRING, description="the guest CIDR address for the Zone") private String guestCidrAddress; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the Zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the Zone") private Long id; @Parameter(name=ApiConstants.INTERNAL_DNS1, type=CommandType.STRING, description="the first internal DNS for the Zone") @@ -66,21 +62,21 @@ public class UpdateZoneCmd extends BaseCmd { @Parameter(name=ApiConstants.IS_PUBLIC, type=CommandType.BOOLEAN, description="updates a private zone to public if set, but not vice-versa") private Boolean isPublic; - + @Parameter(name=ApiConstants.ALLOCATION_STATE, type=CommandType.STRING, description="Allocation state of this cluster for allocation of new resources") private String allocationState; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="the details for the Zone") private Map details; - + @Parameter(name=ApiConstants.DHCP_PROVIDER, type=CommandType.STRING, description="the dhcp Provider for the Zone") private String dhcpProvider; - + @Parameter(name=ApiConstants.DOMAIN, type=CommandType.STRING, description="Network domain name for the networks in the zone; empty string will update domain with NULL value") private String domain; - + @Parameter(name=ApiConstants.DNS_SEARCH_ORDER, type=CommandType.LIST, collectionType = CommandType.STRING, description="the dns search order list") - private List dnsSearchOrder; + private List dnsSearchOrder; @Parameter(name=ApiConstants.LOCAL_STORAGE_ENABLED, type=CommandType.BOOLEAN, description="true if local storage offering enabled, false otherwise") private Boolean localStorageEnabled; @@ -120,26 +116,26 @@ public class UpdateZoneCmd extends BaseCmd { public Boolean isPublic() { return isPublic; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public Map getDetails() { return details; } - + public String getDhcpProvider() { return dhcpProvider; } - + public String getDomain() { return domain; } public List getDnsSearchOrder() { return dnsSearchOrder; - } + } public Boolean getLocalStorageEnabled() { return localStorageEnabled; @@ -153,16 +149,16 @@ public class UpdateZoneCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ - UserContext.current().setEventDetails("Zone Id: "+getId()); - DataCenter result = _configService.editZone(this); + UserContext.current().setEventDetails("Zone Id: "+getId()); + DataCenter result = _configService.editZone(this); if (result != null) { ZoneResponse response = _responseGenerator.createZoneResponse(result, false); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/AddAccountToProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java index 5178aa31ca3..889c3697515 100644 --- a/api/src/com/cloud/api/commands/AddAccountToProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/AddAccountToProjectCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -import com.cloud.utils.AnnotationHelper; -@Implementation(description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "addAccountToProject", description="Adds acoount to a project", responseObject=SuccessResponse.class, since="3.0.0") public class AddAccountToProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddAccountToProjectCmd.class.getName()); @@ -43,13 +38,13 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to add the account to") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project to add the account to") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="name of the account to be added to the project") private String accountName; - + @Parameter(name=ApiConstants.EMAIL, type=CommandType.STRING, description="email to which invitation to the project is going to be sent") private String email; @@ -66,7 +61,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { return projectId; } - + public String getEmail() { return email; } @@ -85,7 +80,7 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { if (accountName == null && email == null) { throw new InvalidParameterValueException("Either accountName or email is required"); } - + UserContext.current().setEventDetails("Project id: "+ projectId + "; accountName " + accountName); boolean result = _projectService.addAccountToProject(getProjectId(), getAccountName(), getEmail()); if (result) { @@ -95,31 +90,31 @@ public class AddAccountToProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add account to the project"); } } - + @Override public long getEntityOwnerId() { - Project project= _projectService.getProject(projectId); + Project project= _projectService.getProject(getProjectId()); //verify input parameters if (project == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); - ex.addProxyObject(project, projectId, "projectId"); + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find project with specified id"); + ex.addProxyObject(project, getProjectId(), "projectId"); throw ex; - } - - return _projectService.getProjectOwner(projectId).getId(); + } + + return _projectService.getProjectOwner(getProjectId()).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_ADD; } - + @Override public String getEventDescription() { if (accountName != null) { - return "Adding account " + accountName + " to project: " + projectId; + return "Adding account " + getAccountName() + " to project: " + getProjectId(); } else { - return "Sending invitation to email " + email + " to join project: " + projectId; - } + return "Sending invitation to email " + email + " to join project: " + getProjectId(); + } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java index d9b3bf19bee..f9e967ad4c2 100644 --- a/api/src/com/cloud/api/commands/DeleteAccountFromProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/DeleteAccountFromProjectCmd.java @@ -14,24 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.project.DeleteProjectCmd; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Deletes account from the project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteAccountFromProject", description="Deletes account from the project", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectCmd.class.getName()); @@ -40,10 +37,10 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project to remove the account from") + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project to remove the account from") private Long projectId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, required=true, description="name of the account to be removed from the project") private String accountName; @@ -52,7 +49,7 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// - + @Override public String getCommandName() { @@ -82,26 +79,26 @@ public class DeleteAccountFromProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete account from the project"); } } - - + + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(projectId); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + projectId); - } - - return _projectService.getProjectOwner(projectId).getId(); + } + + return _projectService.getProjectOwner(projectId).getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACCOUNT_REMOVE; } - + @Override public String getEventDescription() { return "Removing account " + accountName + " from project: " + projectId; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListAccountsCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java old mode 100755 new mode 100644 similarity index 69% rename from api/src/com/cloud/api/commands/ListAccountsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java index eac7d1b9e09..f679a5ae7d1 --- a/api/src/com/cloud/api/commands/ListAccountsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/ListAccountsCmd.java @@ -14,25 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.account; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListDomainResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AccountResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.user.Account; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListDomainResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserResponse; -@Implementation(description="Lists accounts and provides detailed account information for listed accounts", responseObject=AccountResponse.class) +import com.cloud.user.Account; +import com.cloud.utils.Pair; + +@APICommand(name = "listAccounts", description="Lists accounts and provides detailed account information for listed accounts", responseObject=AccountResponse.class) public class ListAccountsCmd extends BaseListDomainResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); private static final String s_name = "listaccountsresponse"; ///////////////////////////////////////////////////// @@ -42,8 +44,8 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Parameter(name=ApiConstants.ACCOUNT_TYPE, type=CommandType.LONG, description="list accounts by account type. Valid account types are 1 (admin), 2 (domain-admin), and 0 (user).") private Long accountType; - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list account by account ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AccountResponse.class, + description="list account by account ID") private Long id; @Parameter(name=ApiConstants.IS_CLEANUP_REQUIRED, type=CommandType.BOOLEAN, description="list accounts by cleanuprequred attribute (values are true or false)") @@ -54,7 +56,7 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list accounts by state. Valid states are enabled, disabled, and locked.") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -78,7 +80,7 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -91,17 +93,8 @@ public class ListAccountsCmd extends BaseListDomainResourcesCmd { @Override public void execute(){ - List accounts = _accountService.searchForAccounts(this); - ListResponse response = new ListResponse(); - List accountResponses = new ArrayList(); - for (Account account : accounts) { - AccountResponse acctResponse = _responseGenerator.createAccountResponse(account); - acctResponse.setObjectName("account"); - accountResponses.add(acctResponse); - } - response.setResponses(accountResponses); + ListResponse response = _queryService.searchForAccounts(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListProjectAccountsCmd.java b/api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/ListProjectAccountsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java index 893e7534ce9..2c279db64a8 100644 --- a/api/src/com/cloud/api/commands/ListProjectAccountsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/account/ListProjectAccountsCmd.java @@ -14,25 +14,21 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.account; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.projects.ProjectAccount; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectResponse; + import com.cloud.user.Account; -@Implementation(description="Lists project's accounts", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "listProjectAccounts", description="Lists project's accounts", responseObject=ProjectResponse.class, since="3.0.0") public class ListProjectAccountsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListProjectAccountsCmd.class.getName()); @@ -41,14 +37,14 @@ public class ListProjectAccountsCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, required=true, description="id of the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + required=true, description="id of the project") private Long projectId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="list accounts of the project by account name") private String accountName; - + @Parameter(name=ApiConstants.ROLE, type=CommandType.STRING, description="list accounts of the project by role") private String role; ///////////////////////////////////////////////////// @@ -59,18 +55,29 @@ public class ListProjectAccountsCmd extends BaseListCmd { return accountName; } + + public Long getProjectId() { + return projectId; + } + + + public String getRole() { + return role; + } + + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { //TODO - return project entity ownerId return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -78,16 +85,9 @@ public class ListProjectAccountsCmd extends BaseListCmd { @Override public void execute(){ - List projectAccounts = _projectService.listProjectAccounts(projectId, accountName, role, this.getStartIndex(), this.getPageSizeVal()); - ListResponse response = new ListResponse(); - List projectResponses = new ArrayList(); - for (ProjectAccount projectAccount : projectAccounts) { - ProjectAccountResponse projectAccountResponse = _responseGenerator.createProjectAccountResponse(projectAccount); - projectResponses.add(projectAccountResponse); - } - response.setResponses(projectResponses); + ListResponse response = _queryService.listProjectAccounts(this); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/AssociateIPAddrCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java index 7aaa5b5790b..7d4e44bb507 100644 --- a/api/src/com/cloud/api/commands/AssociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/AssociateIPAddrCmd.java @@ -14,21 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.IPAddressResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -45,7 +49,7 @@ import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Acquires and associates a public IP to an account.", responseObject=IPAddressResponse.class) +@APICommand(name = "associateIpAddress", description="Acquires and associates a public IP to an account.", responseObject=IPAddressResponse.class) public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AssociateIPAddrCmd.class.getName()); private static final String s_name = "associateipaddressresponse"; @@ -54,33 +58,29 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account to associate with this IP address") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, description="the ID of the domain to associate with this IP address") private Long domainId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, description="the ID of the availability zone you want to acquire an public IP address from") private Long zoneId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, description="The network this ip address should be associated to.") private Long networkId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, description="Deploy vm for the project") private Long projectId; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC you want the ip address to " + - "be associated with") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="the VPC you want the ip address to " + + "be associated with") private Long vpcId; ///////////////////////////////////////////////////// @@ -88,11 +88,11 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public String getAccountName() { - if (accountName != null) { + if (accountName != null) { return accountName; } return UserContext.current().getCaller().getAccountName(); @@ -119,56 +119,56 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { return ntwk.getDataCenterId(); } } - + throw new InvalidParameterValueException("Unable to figure out zone to assign ip to"); } - + public Long getVpcId() { return vpcId; } - + public Long getNetworkId() { if (vpcId != null) { return null; } - + if (networkId != null) { return networkId; - } + } Long zoneId = getZoneId(); - + if (zoneId == null) { return null; } - + DataCenter zone = _configService.getZone(zoneId); if (zone.getNetworkType() == NetworkType.Advanced) { - List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), + List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); - throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + + throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); if (defaultGuestNetwork == null) { - throw new InvalidParameterValueException("Unable to find a default Guest network for account " + + throw new InvalidParameterValueException("Unable to find a default Guest network for account " + getAccountName() + " in domain id=" + getDomainId()); } else { return defaultGuestNetwork.getId(); } } } - + @Override public long getEntityOwnerId() { Account caller = UserContext.current().getCaller(); @@ -193,7 +193,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public String getEventType() { return EventTypes.EVENT_NET_IP_ASSIGN; } - + @Override public String getEventDescription() { return "associating ip to network id: " + getNetworkId() + " in zone " + getZoneId(); @@ -210,13 +210,14 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { } public static String getResultObjectName() { - return "addressinfo"; + return "addressinfo"; } - + @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 { @@ -231,9 +232,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } } - + @Override - public void execute() throws ResourceUnavailableException, ResourceAllocationException, + public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { UserContext.current().setEventDetails("Ip Id: " + getEntityId()); @@ -242,9 +243,9 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { if (getVpcId() != null) { result = _vpcService.associateIPToVpc(getEntityId(), getVpcId()); } else if (getNetworkId() != null) { - result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId()); + result = _networkService.associateIPToNetwork(getEntityId(), getNetworkId()); } - + if (result != null) { IPAddressResponse ipResponse = _responseGenerator.createIPAddressResponse(result); ipResponse.setResponseName(getCommandName()); @@ -253,8 +254,8 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign ip address"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -264,7 +265,7 @@ public class AssociateIPAddrCmd extends BaseAsyncCreateCmd { public Long getSyncObjId() { return getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; diff --git a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java index 2f2addb3f9b..20ccd89ba84 100644 --- a/api/src/com/cloud/api/commands/DisassociateIPAddrCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/DisassociateIPAddrCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; @@ -34,7 +31,7 @@ import com.cloud.network.IpAddress; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Disassociates an ip address from the account.", responseObject=SuccessResponse.class) +@APICommand(name = "disassociateIpAddress", description="Disassociates an ip address from the account.", responseObject=SuccessResponse.class) public class DisassociateIPAddrCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisassociateIPAddrCmd.class.getName()); @@ -44,14 +41,14 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the public ip address" + - " to disassociate") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID,entityType = IPAddressResponse.class, + required=true, description="the id of the public ip address" + + " to disassociate") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -81,7 +78,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disassociate ip address"); } } - + @Override public String getEventType() { return EventTypes.EVENT_NET_IP_RELEASE; @@ -91,7 +88,7 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disassociating ip address with id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -101,13 +98,13 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { } ownerId = ip.getAccountId(); } - + if (ownerId == null) { return Account.ACCOUNT_ID_SYSTEM; } return ownerId; } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -118,22 +115,22 @@ public class DisassociateIPAddrCmd extends BaseAsyncCmd { IpAddress ip = getIpAddress(id); return ip.getAssociatedWithNetworkId(); } - + private IpAddress getIpAddress(long id) { IpAddress ip = _entityMgr.findById(IpAddress.class, id); - + if (ip == null) { throw new InvalidParameterValueException("Unable to find ip address by id=" + id); } else { return ip; } } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } - + @Override public Long getInstanceId() { return getIpAddressId(); diff --git a/api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java b/api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java index c6acf97c214..06b08da6907 100644 --- a/api/src/com/cloud/api/commands/ListPublicIpAddressesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/address/ListPublicIpAddressesCmd.java @@ -14,26 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.address; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.network.IpAddress; +import com.cloud.utils.Pair; - -@Implementation(description="Lists all public ip addresses", responseObject=IPAddressResponse.class) -public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { +@APICommand(name = "listPublicIpAddresses", description="Lists all public ip addresses", responseObject=IPAddressResponse.class) +public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListPublicIpAddressesCmd.class.getName()); private static final String s_name = "listpublicipaddressesresponse"; @@ -47,41 +51,41 @@ public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="the virtual network for the IP address") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists ip address by id") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="lists ip address by id") private Long id; @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="lists the specified IP address") private String ipAddress; - @IdentityMapper(entityTableName="vlan") - @Parameter(name=ApiConstants.VLAN_ID, type=CommandType.LONG, description="lists all public IP addresses by VLAN ID") + @Parameter(name=ApiConstants.VLAN_ID, type=CommandType.UUID, entityType = VlanIpRangeResponse.class, + description="lists all public IP addresses by VLAN ID") private Long vlanId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="lists all public IP addresses by Zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="lists all public IP addresses by Zone ID") private Long zoneId; - + @Parameter(name=ApiConstants.FOR_LOAD_BALANCING, type=CommandType.BOOLEAN, description="list only ips used for load balancing") private Boolean forLoadBalancing; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="lists all public IP addresses by physical network id") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="lists all public IP addresses by physical network id") private Long physicalNetworkId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ASSOCIATED_NETWORK_ID, type=CommandType.LONG, description="lists all public IP addresses associated to the network specified") + + @Parameter(name=ApiConstants.ASSOCIATED_NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="lists all public IP addresses associated to the network specified") private Long associatedNetworkId; - + @Parameter(name=ApiConstants.IS_SOURCE_NAT, type=CommandType.BOOLEAN, description="list only source nat ip addresses") private Boolean isSourceNat; - + @Parameter(name=ApiConstants.IS_STATIC_NAT, type=CommandType.BOOLEAN, description="list only static nat ip addresses") private Boolean isStaticNat; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List ips belonging to the VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="List ips belonging to the VPC") private Long vpcId; ///////////////////////////////////////////////////// @@ -110,51 +114,51 @@ public class ListPublicIpAddressesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Long getPhysicalNetworkId() { return physicalNetworkId; } - + public Long getAssociatedNetworkId() { - return associatedNetworkId; - } + return associatedNetworkId; + } public Boolean getIsSourceNat() { - return isSourceNat; - } + return isSourceNat; + } - public Boolean getIsStaticNat() { - return isStaticNat; - } + public Boolean getIsStaticNat() { + return isStaticNat; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; - } + } - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _mgr.searchForIPAddresses(this); + Pair, Integer> result = _mgr.searchForIPAddresses(this); ListResponse response = new ListResponse(); List ipAddrResponses = new ArrayList(); - for (IpAddress ipAddress : result) { + for (IpAddress ipAddress : result.first()) { IPAddressResponse ipResponse = _responseGenerator.createIPAddressResponse(ipAddress); ipResponse.setObjectName("publicipaddress"); ipAddrResponses.add(ipResponse); } - response.setResponses(ipAddrResponses); + response.setResponses(ipAddrResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + public AsyncJob.Type getInstanceType() { return AsyncJob.Type.IpAddress; } diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java new file mode 100644 index 00000000000..db3aaa6dc5d --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScalePolicyCmd.java @@ -0,0 +1,166 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.List; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import com.cloud.async.AsyncJob; +import com.cloud.domain.Domain; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.Condition; +import com.cloud.user.Account; + +@APICommand(name = "createAutoScalePolicy", description = "Creates an autoscale policy for a provision or deprovision action, the action is taken when the all the conditions evaluates to true for the specified duration. The policy is in effect once it is attached to a autscale vm group.", responseObject = AutoScalePolicyResponse.class) +public class CreateAutoScalePolicyCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(CreateAutoScalePolicyCmd.class.getName()); + + private static final String s_name = "autoscalepolicyresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ACTION, type = CommandType.STRING, required = true, description = "the action to be executed if all the conditions evaluate to true for the specified duration.") + private String action; + + @Parameter(name = ApiConstants.DURATION, type = CommandType.INTEGER, required = true, description = "the duration for which the conditions have to be true before action is taken") + private int duration; + + @Parameter(name = ApiConstants.QUIETTIME, type = CommandType.INTEGER, description = "the cool down period for which the policy should not be evaluated after the action has been taken") + private Integer quietTime; + + @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ConditionResponse.class, + required = true, description = "the list of IDs of the conditions that are being evaluated on every interval") + private List conditionIds; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + private Long conditionDomainId; + private Long conditionAccountId; + + @Override + public String getEntityTable() { + return "autoscale_policies"; + } + + public int getDuration() { + return duration; + } + + public Integer getQuietTime() { + return quietTime; + } + + public String getAction() { + return action; + } + + public List getConditionIds() { + return conditionIds; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public static String getResultObjectName() { + return "autoscalepolicy"; + } + + public long getAccountId() + { + if (conditionAccountId == null) + getEntityOwnerId(); + return conditionAccountId; + } + + public long getDomainId() + { + if (conditionDomainId == null) { + getEntityOwnerId(); + } + + return conditionDomainId; + } + + @Override + public long getEntityOwnerId() { + if (conditionAccountId != null) { + return conditionAccountId; + } + long conditionId = getConditionIds().get(0); + Condition condition = _entityMgr.findById(Condition.class, conditionId); + if(condition == null) { + // it is an invalid condition, return system acccount, error will be thrown later. + conditionDomainId = Domain.ROOT_DOMAIN; + conditionAccountId = Account.ACCOUNT_ID_SYSTEM; + } else { + conditionDomainId = condition.getDomainId(); + conditionAccountId = condition.getAccountId(); + } + + return conditionAccountId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEPOLICY_CREATE; + } + + @Override + public String getEventDescription() { + return "creating AutoScale Policy"; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScalePolicy; + } + + @Override + public void execute() { + AutoScalePolicy result = _entityMgr.findById(AutoScalePolicy.class, getEntityId()); + AutoScalePolicyResponse response = _responseGenerator.createAutoScalePolicyResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + @Override + public void create() throws ResourceAllocationException { + AutoScalePolicy result = _autoScaleService.createAutoScalePolicy(this); + if (result != null) { + this.setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create AutoScale Policy"); + } + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java new file mode 100644 index 00000000000..6297888f5d3 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmGroupCmd.java @@ -0,0 +1,192 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.List; + +import org.apache.cloudstack.api.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.rules.LoadBalancer; + +@APICommand(name = "createAutoScaleVmGroup", description = "Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject = AutoScaleVmGroupResponse.class) +public class CreateAutoScaleVmGroupCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmGroupCmd.class.getName()); + + private static final String s_name = "autoscalevmgroupresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") + private long lbRuleId; + + @Parameter(name = ApiConstants.MIN_MEMBERS, type = CommandType.INTEGER, required = true, description = "the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.") + private int minMembers; + + @Parameter(name = ApiConstants.MAX_MEMBERS, type = CommandType.INTEGER, required = true, description = "the maximum number of members in the vmgroup, The number of instances in the vm group will be equal to or less than this number.") + private int maxMembers; + + @Parameter(name = ApiConstants.INTERVAL, type = CommandType.INTEGER, description = "the frequency at which the conditions have to be evaluated") + private Integer interval; + + @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "list of scaleup autoscale policies") + private List scaleUpPolicyIds; + + @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "list of scaledown autoscale policies") + private List scaleDownPolicyIds; + + @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the autoscale profile that contains information about the vms in the vm group.") + private long profileId; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getEntityTable() { + return "autoscale_vmgroups"; + } + + public int getMinMembers() { + return minMembers; + } + + public int getMaxMembers() { + return maxMembers; + } + + public Integer getInterval() { + return interval; + } + + public long getProfileId() { + return profileId; + } + + public List getScaleUpPolicyIds() { + return scaleUpPolicyIds; + } + + public List getScaleDownPolicyIds() { + return scaleDownPolicyIds; + } + + public long getLbRuleId() { + return lbRuleId; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public static String getResultObjectName() { + return "autoscalevmgroup"; + } + + @Override + public long getEntityOwnerId() { + LoadBalancer lb = _entityMgr.findById(LoadBalancer.class, getLbRuleId()); + if (lb == null) { + throw new InvalidParameterValueException("Unable to find loadbalancer by lbRuleId"); + } + return lb.getAccountId(); + } + + public void setLbRuleId(Long lbRuleId) { + this.lbRuleId = lbRuleId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE; + } + + @Override + public String getCreateEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE; + } + + @Override + public String getCreateEventDescription() { + return "creating AutoScale Vm Group"; + } + + @Override + public String getEventDescription() { + return "configuring AutoScale Vm Group. Vm Group Id: " + getEntityId(); + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmGroup; + } + + @Override + public void create() throws ResourceAllocationException { + AutoScaleVmGroup result = _autoScaleService.createAutoScaleVmGroup(this); + if (result != null) { + this.setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); + } + } + + @Override + public void execute() { + boolean success = false; + AutoScaleVmGroup vmGroup = null; + try + { + success = _autoScaleService.configureAutoScaleVmGroup(this); + if (success) { + vmGroup = _entityMgr.findById(AutoScaleVmGroup.class, getEntityId()); + AutoScaleVmGroupResponse responseObject = _responseGenerator.createAutoScaleVmGroupResponse(vmGroup); + setResponseObject(responseObject); + responseObject.setResponseName(getCommandName()); + } + } catch (Exception ex) { + // TODO what will happen if Resource Layer fails in a step inbetween + s_logger.warn("Failed to create autoscale vm group", ex); + } finally { + if (!success || vmGroup == null) { + _autoScaleService.deleteAutoScaleVmGroup(getEntityId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Group"); + } + } + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java new file mode 100644 index 00000000000..daa48501c53 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateAutoScaleVmProfileCmd.java @@ -0,0 +1,239 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.user.UserContext; + +@APICommand(name = "createAutoScaleVmProfile", description = "Creates a profile that contains information about the virtual machine which will be provisioned automatically by autoscale feature.", responseObject = AutoScaleVmProfileResponse.class) +@SuppressWarnings("rawtypes") +public class CreateAutoScaleVmProfileCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(CreateAutoScaleVmProfileCmd.class.getName()); + + private static final String s_name = "autoscalevmprofileresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + required = true, description = "availability zone for the auto deployed virtual machine") + private Long zoneId; + + @Parameter(name = ApiConstants.SERVICE_OFFERING_ID, type = CommandType.UUID, entityType = DiskOfferingResponse.class, + required = true, description = "the service offering of the auto deployed virtual machine") + private Long serviceOfferingId; + + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, + required = true, description = "the template of the auto deployed virtual machine") + private Long templateId; + + @Parameter(name = ApiConstants.OTHER_DEPLOY_PARAMS, type = CommandType.STRING, description = "parameters other than zoneId/serviceOfferringId/templateId of the auto deployed virtual machine") + private String otherDeployParams; + + @Parameter(name = ApiConstants.AUTOSCALE_VM_DESTROY_TIME, type = CommandType.INTEGER, description = "the time allowed for existing connections to get closed before a vm is destroyed") + private Integer destroyVmGraceperiod; + + @Parameter(name = ApiConstants.COUNTERPARAM_LIST, type = CommandType.MAP, description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161") + private Map counterParamList; + + @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.UUID, entityType = UserResponse.class, + description = "the ID of the user used to launch and destroy the VMs") + private Long autoscaleUserId; + + private Map otherDeployParamMap; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + private Long domainId; + private Long accountId; + + @Override + public String getEntityTable() { + return "autoscale_vmprofiles"; + } + + public Long getDomainId() { + if (domainId == null) { + getAccountId(); + } + return domainId; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + public Long getTemplateId() { + return templateId; + } + + public Map getCounterParamList() { + return counterParamList; + } + + public String getOtherDeployParams() { + return otherDeployParams; + } + + public Long getAutoscaleUserId() { + if (autoscaleUserId != null) { + return autoscaleUserId; + } else { + return UserContext.current().getCaller().getId(); + } + } + + public Integer getDestroyVmGraceperiod() { + return destroyVmGraceperiod; + } + + public long getAccountId() { + if (accountId != null) { + return accountId; + } + Account account = null; + if (autoscaleUserId != null) { + User user = _entityMgr.findById(User.class, autoscaleUserId); + account = _entityMgr.findById(Account.class, user.getAccountId()); + } else { + account = UserContext.current().getCaller(); + } + accountId = account.getAccountId(); + domainId = account.getDomainId(); + return accountId; + } + + private void createOtherDeployParamMap() + { + if (otherDeployParamMap == null) { + otherDeployParamMap = new HashMap(); + } + if (otherDeployParams == null) + return; + String[] keyValues = otherDeployParams.split("&"); // hostid=123, hypervisor=xenserver + for (String keyValue : keyValues) { // keyValue == "hostid=123" + String[] keyAndValue = keyValue.split("="); // keyValue = hostid, 123 + if (keyAndValue.length != 2) { + throw new InvalidParameterValueException("Invalid parameter in otherDeployParam : " + keyValue); + } + String paramName = keyAndValue[0]; // hostid + String paramValue = keyAndValue[1]; // 123 + otherDeployParamMap.put(paramName, paramValue); + } + } + + public HashMap getDeployParamMap() + { + createOtherDeployParamMap(); + HashMap deployParams = new HashMap(otherDeployParamMap); + deployParams.put("command", "deployVirtualMachine"); + deployParams.put("zoneId", zoneId.toString()); + deployParams.put("serviceOfferingId", serviceOfferingId.toString()); + deployParams.put("templateId", templateId.toString()); + return deployParams; + } + + public String getOtherDeployParam(String param) + { + if (param == null) { + return null; + } + createOtherDeployParamMap(); + return otherDeployParamMap.get(param); + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public static String getResultObjectName() { + return "autoscalevmprofile"; + } + + @Override + public long getEntityOwnerId() { + return getAccountId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMPROFILE_CREATE; + } + + @Override + public String getEventDescription() { + return "creating AutoScale Vm Profile"; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmProfile; + } + + @Override + public void execute() { + AutoScaleVmProfile result = _entityMgr.findById(AutoScaleVmProfile.class, getEntityId()); + AutoScaleVmProfileResponse response = _responseGenerator.createAutoScaleVmProfileResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + @Override + public void create() throws ResourceAllocationException { + + AutoScaleVmProfile result = _autoScaleService.createAutoScaleVmProfile(this); + if (result != null) { + this.setEntityId(result.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create Autoscale Vm Profile"); + } + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java new file mode 100644 index 00000000000..a9524714ffa --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/CreateConditionCmd.java @@ -0,0 +1,153 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ConditionResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.as.Condition; +import com.cloud.user.UserContext; + +@APICommand(name = "createCondition", description = "Creates a condition", responseObject = ConditionResponse.class) +public class CreateConditionCmd extends BaseAsyncCreateCmd { + public static final Logger s_logger = Logger.getLogger(CreateConditionCmd.class.getName()); + private static final String s_name = "conditionresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.UUID, entityType = CounterResponse.class, + required = true, description = "ID of the Counter.") + private long counterId; + + @Parameter(name = ApiConstants.RELATIONAL_OPERATOR, type = CommandType.STRING, required = true, description = "Relational Operator to be used with threshold.") + private String relationalOperator; + + @Parameter(name = ApiConstants.THRESHOLD, type = CommandType.LONG, required = true, description = "Threshold value.") + private Long threshold; + + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the condition. " + + "Must be used with the domainId parameter.") + private String accountName; + + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "the domain ID of the account.") + private Long domainId; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void create() throws ResourceAllocationException { + Condition condition = null; + condition = _autoScaleService.createCondition(this); + + if (condition != null) { + this.setEntityId(condition.getId()); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create condition."); + } + } + + @Override + public void execute() { + Condition condition = _entityMgr.findById(Condition.class, getEntityId()); + ConditionResponse response = _responseGenerator.createConditionResponse(condition); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + // ///////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public Long getCounterId() { + return counterId; + } + + public String getRelationalOperator() { + return relationalOperator; + } + + public String getAccountName() { + if (accountName == null) { + return UserContext.current().getCaller().getAccountName(); + } + + return accountName; + } + + public Long getDomainId() { + if (domainId == null) { + return UserContext.current().getCaller().getDomainId(); + } + return domainId; + } + + public Long getThreshold() { + return threshold; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.Condition; + } + + @Override + public String getEventDescription() { + return "creating a condition"; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_CONDITION_CREATE; + } + + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, null, true); + if (accountId == null) { + return UserContext.current().getCaller().getId(); + } + + return accountId; + } + + @Override + public String getEntityTable() { + return "conditions"; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java new file mode 100644 index 00000000000..483a87ac892 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScalePolicyCmd.java @@ -0,0 +1,103 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "deleteAutoScalePolicy", description = "Deletes a autoscale policy.", responseObject = SuccessResponse.class) +public class DeleteAutoScalePolicyCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteAutoScalePolicyCmd.class.getName()); + private static final String s_name = "deleteautoscalepolicyresponse"; + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "the ID of the autoscale policy") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScalePolicy autoScalePolicy = _entityMgr.findById(AutoScalePolicy.class, getId()); + if (autoScalePolicy != null) { + return autoScalePolicy.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEPOLICY_DELETE; + } + + @Override + public String getEventDescription() { + return "deleting AutoScale Policy: " + getId(); + } + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale Policy Id: " + getId()); + boolean result = _autoScaleService.deleteAutoScalePolicy(id); + + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + s_logger.warn("Failed to delete autoscale policy " + getId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete AutoScale Policy"); + } + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScalePolicy; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java new file mode 100644 index 00000000000..1d78fe80395 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmGroupCmd.java @@ -0,0 +1,103 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "deleteAutoScaleVmGroup", description = "Deletes a autoscale vm group.", responseObject = SuccessResponse.class) +public class DeleteAutoScaleVmGroupCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmGroupCmd.class.getName()); + private static final String s_name = "deleteautoscalevmgroupresponse"; + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required = true, description = "the ID of the autoscale group") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmGroup autoScaleVmGroup = _entityMgr.findById(AutoScaleVmGroup.class, getId()); + if (autoScaleVmGroup != null) { + return autoScaleVmGroup.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_DELETE; + } + + @Override + public String getEventDescription() { + return "deleting autoscale vm group: " + getId(); + } + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale Vm Group Id: " + getId()); + boolean result = _autoScaleService.deleteAutoScaleVmGroup(id); + + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + s_logger.warn("Failed to delete autoscale vm group " + getId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete autoscale vm group"); + } + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmGroup; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java new file mode 100644 index 00000000000..e49f0c862a3 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteAutoScaleVmProfileCmd.java @@ -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. +package org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "deleteAutoScaleVmProfile", description = "Deletes a autoscale vm profile.", responseObject = SuccessResponse.class) +public class DeleteAutoScaleVmProfileCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteAutoScaleVmProfileCmd.class.getName()); + private static final String s_name = "deleteautoscalevmprofileresponse"; + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the ID of the autoscale profile") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmProfile autoScaleVmProfile = _entityMgr.findById(AutoScaleVmProfile.class, getId()); + if (autoScaleVmProfile != null) { + return autoScaleVmProfile.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are +// tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMPROFILE_DELETE; + } + + @Override + public String getEventDescription() { + return "deleting autoscale vm profile: " + getId(); + } + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale VM Profile Id: " + getId()); + boolean result = _autoScaleService.deleteAutoScaleVmProfile(id); + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + s_logger.warn("Failed to delete autoscale vm profile " + getId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete autoscale vm profile"); + } + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmProfile; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java new file mode 100644 index 00000000000..a1fba2e3725 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DeleteConditionCmd.java @@ -0,0 +1,109 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.exception.ResourceInUseException; +import com.cloud.network.as.Condition; +import com.cloud.user.Account; + +@APICommand(name = "deleteCondition", description = "Removes a condition", responseObject = SuccessResponse.class) +public class DeleteConditionCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DeleteConditionCmd.class.getName()); + private static final String s_name = "deleteconditionresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ConditionResponse.class, + required= true, description = "the ID of the condition.") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + boolean result = false; + try { + result = _autoScaleService.deleteCondition(getId()); + } catch (ResourceInUseException ex) { + s_logger.warn("Exception: ", ex); + throw new ServerApiException(BaseCmd.RESOURCE_IN_USE_ERROR, ex.getMessage()); + } + if (result) { + SuccessResponse response = new SuccessResponse(getCommandName()); + this.setResponseObject(response); + } else { + s_logger.warn("Failed to delete condition " + getId()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete condition."); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.Condition; + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Condition condition = _entityMgr.findById(Condition.class, getId()); + if (condition != null) { + return condition.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_CONDITION_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting a condition."; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.java new file mode 100644 index 00000000000..2aba82c2a93 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/DisableAutoScaleVmGroupCmd.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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.user.Account; + +@APICommand(name = "disableAutoScaleVmGroup", description = "Disables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) +public class DisableAutoScaleVmGroupCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(DisableAutoScaleVmGroupCmd.class.getName()); + private static final String s_name = "disableautoscalevmGroupresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required=true, description="the ID of the autoscale group") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + AutoScaleVmGroup result = _autoScaleService.disableAutoScaleVmGroup(getId()); + if (result != null) { + AutoScaleVmGroupResponse response = _responseGenerator.createAutoScaleVmGroupResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable AutoScale Vm Group"); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmGroup autoScaleVmGroup = _entityMgr.findById(AutoScaleVmGroup.class, getId()); + if (autoScaleVmGroup != null) { + return autoScaleVmGroup.getAccountId(); + } + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE; + } + + @Override + public String getEventDescription() { + return "Disabling AutoScale Vm Group. Vm Group Id: " + getId(); + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmGroup; + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java new file mode 100644 index 00000000000..db7acdf5d98 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/EnableAutoScaleVmGroupCmd.java @@ -0,0 +1,97 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import org.apache.cloudstack.api.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.user.Account; + +@APICommand(name = "enableAutoScaleVmGroup", description = "Enables an AutoScale Vm Group", responseObject = AutoScaleVmGroupResponse.class) +public class EnableAutoScaleVmGroupCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(EnableAutoScaleVmGroupCmd.class.getName()); + private static final String s_name = "enableautoscalevmGroupresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required=true, description="the ID of the autoscale group") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + AutoScaleVmGroup result = _autoScaleService.enableAutoScaleVmGroup(getId()); + if (result != null) { + AutoScaleVmGroupResponse response = _responseGenerator.createAutoScaleVmGroupResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to enable AutoScale Vm Group"); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmGroup autoScaleVmGroup = _entityMgr.findById(AutoScaleVmGroup.class, getId()); + if (autoScaleVmGroup != null) { + return autoScaleVmGroup.getAccountId(); + } + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE; + } + + @Override + public String getEventDescription() { + return "Enabling AutoScale Vm Group. Vm Group Id: "+getId(); + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmGroup; + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java new file mode 100644 index 00000000000..31621442252 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScalePoliciesCmd.java @@ -0,0 +1,104 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.network.as.AutoScalePolicy; + +@APICommand(name = "listAutoScalePolicies", description = "Lists autoscale policies.", responseObject = AutoScalePolicyResponse.class) +public class ListAutoScalePoliciesCmd extends BaseListAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListAutoScalePoliciesCmd.class.getName()); + + private static final String s_name = "listautoscalepoliciesresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the autoscale policy") + private Long id; + + @Parameter(name = ApiConstants.CONDITION_ID, type = CommandType.UUID, entityType = ConditionResponse.class, + description = "the ID of the condition of the policy") + private Long conditionId; + + @Parameter(name = ApiConstants.ACTION, type = CommandType.STRING, description = "the action to be executed if all the conditions evaluate to true for the specified duration.") + private String action; + + @Parameter(name = ApiConstants.VMGROUP_ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + description = "the ID of the autoscale vm group") + private Long vmGroupId; + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getConditionId() { + return conditionId; + } + + public String getAction() { + return action; + } + + public Long getVmGroupId() { + return vmGroupId; + } + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public void execute() { + List autoScalePolicies = _autoScaleService.listAutoScalePolicies(this); + ListResponse response = new ListResponse(); + List responses = new ArrayList(); + if (autoScalePolicies != null) { + for (AutoScalePolicy autoScalePolicy : autoScalePolicies) { + AutoScalePolicyResponse autoScalePolicyResponse = _responseGenerator.createAutoScalePolicyResponse(autoScalePolicy); + autoScalePolicyResponse.setObjectName("autoscalepolicy"); + responses.add(autoScalePolicyResponse); + } + } + response.setResponses(responses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java new file mode 100644 index 00000000000..7561757fcab --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmGroupsCmd.java @@ -0,0 +1,118 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.APICommand; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.network.as.AutoScaleVmGroup; + +@APICommand(name = "listAutoScaleVmGroups", description = "Lists autoscale vm groups.", responseObject = AutoScaleVmGroupResponse.class) +public class ListAutoScaleVmGroupsCmd extends BaseListProjectAndAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmGroupsCmd.class.getName()); + + private static final String s_name = "listautoscalevmgroupsresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + description = "the ID of the autoscale vm group") + private Long id; + + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + description = "the ID of the loadbalancer") + private Long loadBalancerId; + + @Parameter(name = ApiConstants.VMPROFILE_ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + description = "the ID of the profile") + private Long profileId; + + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the policy") + private Long policyId; + + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the availability zone ID") + private Long zoneId; + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getLoadBalancerId() { + return loadBalancerId; + } + + + public Long getProfileId() { + return profileId; + } + + public Long getPolicyId() { + return policyId; + } + + public Long getZoneId() { + return zoneId; + } + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public void execute() { + if(id != null && (loadBalancerId != null || profileId != null || policyId != null)) + throw new InvalidParameterValueException("When id is specified other parameters need not be specified"); + + List autoScaleGroups = _autoScaleService.listAutoScaleVmGroups(this); + ListResponse response = new ListResponse(); + List responses = new ArrayList(); + if (autoScaleGroups != null) { + for (AutoScaleVmGroup autoScaleVmGroup : autoScaleGroups) { + AutoScaleVmGroupResponse autoScaleVmGroupResponse = _responseGenerator.createAutoScaleVmGroupResponse(autoScaleVmGroup); + autoScaleVmGroupResponse.setObjectName("autoscalevmgroup"); + responses.add(autoScaleVmGroupResponse); + } + } + response.setResponses(responses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java new file mode 100644 index 00000000000..7a88db3e7b9 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListAutoScaleVmProfilesCmd.java @@ -0,0 +1,95 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.network.as.AutoScaleVmProfile; + +@APICommand(name = "listAutoScaleVmProfiles", description = "Lists autoscale vm profiles.", responseObject = AutoScaleVmProfileResponse.class) +public class ListAutoScaleVmProfilesCmd extends BaseListProjectAndAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListAutoScaleVmProfilesCmd.class.getName()); + + private static final String s_name = "listautoscalevmprofilesresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + description = "the ID of the autoscale vm profile") + private Long id; + + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + description="the templateid of the autoscale vm profile") + private Long templateId; + + @Parameter(name=ApiConstants.OTHER_DEPLOY_PARAMS, type=CommandType.STRING, description="the otherdeployparameters of the autoscale vm profile") + private String otherDeployParams; + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getTemplateId() { + return templateId; + } + + public String getOtherDeployParams() { + return otherDeployParams; + } + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public void execute() { + List autoScaleProfiles = _autoScaleService.listAutoScaleVmProfiles(this); + ListResponse response = new ListResponse(); + List responses = new ArrayList(); + if (autoScaleProfiles != null) { + for (AutoScaleVmProfile autoScaleVmProfile : autoScaleProfiles) { + AutoScaleVmProfileResponse autoScaleVmProfileResponse = _responseGenerator.createAutoScaleVmProfileResponse(autoScaleVmProfile); + autoScaleVmProfileResponse.setObjectName("autoscalevmprofile"); + responses.add(autoScaleVmProfileResponse); + } + } + response.setResponses(responses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java new file mode 100644 index 00000000000..0b3ffec040c --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListConditionsCmd.java @@ -0,0 +1,96 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.network.as.Condition; + +@APICommand(name = "listConditions", description = "List Conditions for the specific user", responseObject = CounterResponse.class) +public class ListConditionsCmd extends BaseListAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListConditionsCmd.class.getName()); + private static final String s_name = "listconditionsresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = ConditionResponse.class, + required = false, description = "ID of the Condition.") + private Long id; + + @Parameter(name = ApiConstants.COUNTER_ID, type = CommandType.UUID, entityType = CounterResponse.class, + required = false, description = "Counter-id of the condition.") + private Long counterId; + + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "the ID of the policy") + private Long policyId; + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + List conditions = null; + conditions = _autoScaleService.listConditions(this); + ListResponse response = new ListResponse(); + List cndnResponses = new ArrayList(); + for (Condition cndn : conditions) { + ConditionResponse cndnResponse = _responseGenerator.createConditionResponse(cndn); + cndnResponses.add(cndnResponse); + } + + response.setResponses(cndnResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + // ///////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getCounterId() { + return counterId; + } + + public Long getPolicyId() { + return policyId; + } + + @Override + public String getCommandName() { + return s_name; + } + +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java new file mode 100644 index 00000000000..66a38f34396 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/ListCountersCmd.java @@ -0,0 +1,98 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.cloudstack.api.APICommand; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.network.as.Counter; +import com.cloud.user.Account; + +@APICommand(name = "listCounters", description = "List the counters", responseObject = CounterResponse.class) +public class ListCountersCmd extends BaseListCmd { + public static final Logger s_logger = Logger.getLogger(ListCountersCmd.class.getName()); + private static final String s_name = "counterresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = CounterResponse.class, + description = "ID of the Counter.") + private Long id; + + @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "Name of the counter.") + private String name; + + @Parameter(name = ApiConstants.SOURCE, type = CommandType.STRING, description = "Source of the counter.") + private String source; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + List counters = null; + counters = _autoScaleService.listCounters(this); + ListResponse response = new ListResponse(); + List ctrResponses = new ArrayList(); + for (Counter ctr : counters) { + CounterResponse ctrResponse = _responseGenerator.createCounterResponse(ctr); + ctrResponses.add(ctrResponse); + } + + response.setResponses(ctrResponses); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + + // ///////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + @Override + public String getCommandName() { + return s_name; + } + + public Long getId() { + return id; + } + + public String getName() { + return name; + } + + public String getSource() { + return source; + } + + @Override + public long getEntityOwnerId() { + return Account.ACCOUNT_ID_SYSTEM; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java new file mode 100644 index 00000000000..56d71078ece --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScalePolicyCmd.java @@ -0,0 +1,126 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.List; + +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "updateAutoScalePolicy", description = "Updates an existing autoscale policy.", responseObject = AutoScalePolicyResponse.class) +public class UpdateAutoScalePolicyCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UpdateAutoScalePolicyCmd.class.getName()); + + private static final String s_name = "updateautoscalepolicyresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.DURATION, type = CommandType.INTEGER, description = "the duration for which the conditions have to be true before action is taken") + private Integer duration; + + @Parameter(name = ApiConstants.QUIETTIME, type = CommandType.INTEGER, description = "the cool down period for which the policy should not be evaluated after the action has been taken") + private Integer quietTime; + + @Parameter(name = ApiConstants.CONDITION_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = ConditionResponse.class, + description = "the list of IDs of the conditions that are being evaluated on every interval") + private List conditionIds; + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + required = true, description = "the ID of the autoscale policy") + private Long id; + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale Policy Id: " + getId()); + AutoScalePolicy result = _autoScaleService.updateAutoScalePolicy(this); + if (result != null) { + AutoScalePolicyResponse response = _responseGenerator.createAutoScalePolicyResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale policy"); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Integer getDuration() { + return duration; + } + + public Integer getQuietTime() { + return quietTime; + } + + + public List getConditionIds() { + return conditionIds; + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScalePolicy autoScalePolicy = _entityMgr.findById(AutoScalePolicy.class, getId()); + if (autoScalePolicy != null) { + return autoScalePolicy.getAccountId(); + } + + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEPOLICY_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating Auto Scale Policy. Policy Id: " + getId(); + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScalePolicy; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java new file mode 100644 index 00000000000..ea5b6a9f489 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmGroupCmd.java @@ -0,0 +1,139 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.List; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "updateAutoScaleVmGroup", description = "Updates an existing autoscale vm group.", responseObject = AutoScaleVmGroupResponse.class) +public class UpdateAutoScaleVmGroupCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmGroupCmd.class.getName()); + + private static final String s_name = "updateautoscalevmgroupresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.MIN_MEMBERS, type = CommandType.INTEGER, description = "the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.") + private Integer minMembers; + + @Parameter(name = ApiConstants.MAX_MEMBERS, type = CommandType.INTEGER, description = "the maximum number of members in the vmgroup, The number of instances in the vm group will be equal to or less than this number.") + private Integer maxMembers; + + @Parameter(name=ApiConstants.INTERVAL, type=CommandType.INTEGER, description="the frequency at which the conditions have to be evaluated") + private Integer interval; + + @Parameter(name = ApiConstants.SCALEUP_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "list of scaleup autoscale policies") + private List scaleUpPolicyIds; + + @Parameter(name = ApiConstants.SCALEDOWN_POLICY_IDS, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = AutoScalePolicyResponse.class, + description = "list of scaledown autoscale policies") + private List scaleDownPolicyIds; + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmGroupResponse.class, + required = true, description = "the ID of the autoscale group") + private Long id; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale Vm Group Id: " + getId()); + AutoScaleVmGroup result = _autoScaleService.updateAutoScaleVmGroup(this); + if (result != null) { + AutoScaleVmGroupResponse response = _responseGenerator.createAutoScaleVmGroupResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale VmGroup"); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Integer getMinMembers() { + return minMembers; + } + + public Integer getMaxMembers() { + return maxMembers; + } + + public Integer getInterval() { + return interval; + } + + public List getScaleUpPolicyIds() { + return scaleUpPolicyIds; + } + + public List getScaleDownPolicyIds() { + return scaleDownPolicyIds; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating AutoScale Vm Group. Vm Group Id: "+getId(); + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmGroup autoScaleVmGroup = _entityMgr.findById(AutoScaleVmGroup.class, getId()); + if (autoScaleVmGroup != null) { + return autoScaleVmGroup.getAccountId(); + } + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmGroup; + } +} diff --git a/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java new file mode 100644 index 00000000000..c8ef8b11198 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/autoscale/UpdateAutoScaleVmProfileCmd.java @@ -0,0 +1,133 @@ +// 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 org.apache.cloudstack.api.command.user.autoscale; + +import java.util.Map; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import com.cloud.async.AsyncJob; +import com.cloud.event.EventTypes; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +@APICommand(name = "updateAutoScaleVmProfile", description = "Updates an existing autoscale vm profile.", responseObject = AutoScaleVmProfileResponse.class) +public class UpdateAutoScaleVmProfileCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UpdateAutoScaleVmProfileCmd.class.getName()); + + private static final String s_name = "updateautoscalevmprofileresponse"; + + // /////////////////////////////////////////////////// + // ////////////// API parameters ///////////////////// + // /////////////////////////////////////////////////// + + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = AutoScaleVmProfileResponse.class, + required = true, description = "the ID of the autoscale vm profile") + private Long id; + + @Parameter(name = ApiConstants.TEMPLATE_ID, type = CommandType.UUID, entityType = TemplateResponse.class, + description = "the template of the auto deployed virtual machine") + private Long templateId; + + @Parameter(name = ApiConstants.AUTOSCALE_VM_DESTROY_TIME, type = CommandType.INTEGER, description = "the time allowed for existing connections to get closed before a vm is destroyed") + private Integer destroyVmGraceperiod; + + @Parameter(name = ApiConstants.COUNTERPARAM_LIST, type = CommandType.MAP, description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161") + private Map counterParamList; + + @Parameter(name = ApiConstants.AUTOSCALE_USER_ID, type = CommandType.UUID, entityType = UserResponse.class, + description = "the ID of the user used to launch and destroy the VMs") + private Long autoscaleUserId; + + // /////////////////////////////////////////////////// + // ///////////// API Implementation/////////////////// + // /////////////////////////////////////////////////// + + @Override + public void execute() { + UserContext.current().setEventDetails("AutoScale Policy Id: " + getId()); + AutoScaleVmProfile result = _autoScaleService.updateAutoScaleVmProfile(this); + if (result != null) { + AutoScaleVmProfileResponse response = _responseGenerator.createAutoScaleVmProfileResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update autoscale vm profile"); + } + } + + // /////////////////////////////////////////////////// + // ///////////////// Accessors /////////////////////// + // /////////////////////////////////////////////////// + + public Long getId() { + return id; + } + + public Long getTemplateId() { + return templateId; + } + + public Map getCounterParamList() { + return counterParamList; + } + + public Long getAutoscaleUserId() { + return autoscaleUserId; + } + + public Integer getDestroyVmGraceperiod() { + return destroyVmGraceperiod; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_AUTOSCALEVMPROFILE_UPDATE; + } + + @Override + public String getEventDescription() { + return "Updating AutoScale Vm Profile. Vm Profile Id: " + getId(); + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + AutoScaleVmProfile vmProfile = _entityMgr.findById(AutoScaleVmProfile.class, getId()); + if (vmProfile != null) { + return vmProfile.getAccountId(); + } + return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are + // tracked + } + + @Override + public AsyncJob.Type getInstanceType() { + return AsyncJob.Type.AutoScaleVmProfile; + } +} diff --git a/api/src/com/cloud/api/commands/ListCapabilitiesCmd.java b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListCapabilitiesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java index 108b268ae5d..129aeb85d24 100644 --- a/api/src/com/cloud/api/commands/ListCapabilitiesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/config/ListCapabilitiesCmd.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.config; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.CapabilitiesResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.CapabilitiesResponse; import com.cloud.user.Account; -@Implementation(description="Lists capabilities", responseObject=CapabilitiesResponse.class) +@APICommand(name = "listCapabilities", description="Lists capabilities", responseObject=CapabilitiesResponse.class) public class ListCapabilitiesCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); private static final String s_name = "listcapabilitiesresponse"; @@ -35,12 +35,12 @@ public class ListCapabilitiesCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ Map capabilities = _mgr.listCapabilities(this); diff --git a/api/src/com/cloud/api/commands/ListEventTypesCmd.java b/api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/ListEventTypesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java index cd1d1291f21..4c432f35ebb 100644 --- a/api/src/com/cloud/api/commands/ListEventTypesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/event/ListEventTypesCmd.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.event; import java.util.ArrayList; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.EventTypeResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.EventTypeResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.user.Account; -@Implementation(description = "List Event Types", responseObject = EventTypeResponse.class) +@APICommand(name = "listEventTypes", description = "List Event Types", responseObject = EventTypeResponse.class) public class ListEventTypesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListEventTypesCmd.class.getName()); private static final String s_name = "listeventtypesresponse"; diff --git a/api/src/com/cloud/api/commands/ListEventsCmd.java b/api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/commands/ListEventsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java index 512d377fabd..94205d13226 --- a/api/src/com/cloud/api/commands/ListEventsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/event/ListEventsCmd.java @@ -14,24 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.event; -import java.util.ArrayList; import java.util.Date; -import java.util.List; - import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.event.Event; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ListResponse; -@Implementation(description="A command to list events.", responseObject=EventResponse.class) +@APICommand(name = "listEvents", description="A command to list events.", responseObject=EventResponse.class) public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListEventsCmd.class.getName()); @@ -41,10 +36,10 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="event") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the event") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = EventResponse.class, + description="the ID of the event") private Long id; - + @Parameter(name=ApiConstants.DURATION, type=CommandType.INTEGER, description="the duration of the event") private Integer duration; @@ -70,7 +65,7 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { public Long getId() { return id; } - + public Integer getDuration() { return duration; } @@ -106,14 +101,8 @@ public class ListEventsCmd extends BaseListProjectAndAccountResourcesCmd { @Override public void execute(){ - List result = _mgr.searchForEvents(this); - ListResponse response = new ListResponse(); - List eventResponses = new ArrayList(); - for (Event event : result) { - eventResponses.add(_responseGenerator.createEventResponse(event)); - } - response.setResponses(eventResponses); + ListResponse response = _queryService.searchForEvents(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java similarity index 88% rename from api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java index 937e9aa91e5..803301febe9 100644 --- a/api/src/com/cloud/api/commands/CreateFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreateFirewallRuleCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +41,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description = "Creates a firewall rule for a given ip address", responseObject = FirewallResponse.class) +@APICommand(name = "createFirewallRule", description = "Creates a firewall rule for a given ip address", responseObject = FirewallResponse.class) public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements FirewallRule { public static final Logger s_logger = Logger.getLogger(CreateFirewallRuleCmd.class.getName()); @@ -51,8 +51,8 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.LONG, required=true, description = "the IP address id of the port forwarding rule") + @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description = "the IP address id of the port forwarding rule") private Long ipAddressId; @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the firewall rule. Valid values are TCP/UDP/ICMP.") @@ -63,25 +63,25 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of firewall rule") private Integer publicEndPort; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - + @Parameter(name = ApiConstants.TYPE, type = CommandType.STRING, description = "type of firewallrule: system/user") private String type; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } public Long getIpAddressId() { @@ -101,7 +101,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal oneCidrList.add(NetUtils.ALL_CIDRS); return oneCidrList; } - + } // /////////////////////////////////////////////////// @@ -112,7 +112,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -128,7 +128,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal // State is different after the rule is applied, so get new object here rule = _entityMgr.findById(FirewallRule.class, getEntityId()); - FirewallResponse fwResponse = new FirewallResponse(); + FirewallResponse fwResponse = new FirewallResponse(); if (rule != null) { fwResponse = _responseGenerator.createFirewallResponse(rule); setResponseObject(fwResponse); @@ -153,6 +153,13 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return ipAddressId; @@ -175,7 +182,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } else { return publicEndPort.intValue(); } - + return null; } @@ -193,13 +200,13 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to create firewall rule for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -227,7 +234,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -276,7 +283,7 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return ip; } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -286,14 +293,14 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { return -1; - + } return null; } @@ -303,20 +310,20 @@ public class CreateFirewallRuleCmd extends BaseAsyncCreateCmd implements Firewal return null; } - @Override - public FirewallRuleType getType() { - if (type != null && type.equalsIgnoreCase("system")) { - return FirewallRuleType.System; - } else { - return FirewallRuleType.User; - } - } - + @Override + public FirewallRuleType getType() { + if (type != null && type.equalsIgnoreCase("system")) { + return FirewallRuleType.System; + } else { + return FirewallRuleType.User; + } + } + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java index 3f3915a705d..ecccf032ace 100644 --- a/api/src/com/cloud/api/commands/CreatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/CreatePortForwardingRuleCmd.java @@ -14,21 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +37,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.Ip; -@Implementation(description = "Creates a port forwarding rule", responseObject = FirewallRuleResponse.class) +@APICommand(name = "createPortForwardingRule", description = "Creates a port forwarding rule", responseObject = FirewallRuleResponse.class) public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements PortForwardingRule { public static final Logger s_logger = Logger.getLogger(CreatePortForwardingRuleCmd.class.getName()); @@ -50,31 +47,31 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "user_ip_address") - @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.LONG, required = true, + @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + required = true, description = "the IP address id of the port forwarding rule") private Long ipAddressId; - @Parameter(name = ApiConstants.PRIVATE_START_PORT, type = CommandType.INTEGER, required = true, + @Parameter(name = ApiConstants.PRIVATE_START_PORT, type = CommandType.INTEGER, required = true, description = "the starting port of port forwarding rule's private port range") private Integer privateStartPort; - @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, + @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the port fowarding rule. Valid values are TCP or UDP.") private String protocol; @Parameter(name = ApiConstants.PRIVATE_END_PORT, type = CommandType.INTEGER, required = false, description = "the ending port of port forwarding rule's private port range") private Integer privateEndPort; - @Parameter(name = ApiConstants.PUBLIC_START_PORT, type = CommandType.INTEGER, required = true, + @Parameter(name = ApiConstants.PUBLIC_START_PORT, type = CommandType.INTEGER, required = true, description = "the starting port of port forwarding rule's public port range") private Integer publicStartPort; - + @Parameter(name = ApiConstants.PUBLIC_END_PORT, type = CommandType.INTEGER, required = false, description = "the ending port of port forwarding rule's private port range") private Integer publicEndPort; - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, required = true, + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, + required = true, description = "the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; @@ -82,16 +79,15 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P description = "the cidr list to forward traffic from") private List cidrlist; - @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; " + - "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + - " rule is being created for VPC guest network 2) in all other cases defaulted to true") + "if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when PF" + + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, - description="The network of the vm the Port Forwarding rule will be created for. " + - "Required when public Ip address is not associated with any Guest network yet (VPC case)") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="The network of the vm the Port Forwarding rule will be created for. " + + "Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; // /////////////////////////////////////////////////// @@ -99,7 +95,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P // /////////////////////////////////////////////////// public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } public Long getIpAddressId() { @@ -119,11 +115,11 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall " + - "rule for the specific cidr, please refer to createFirewallRule command"); + "rule for the specific cidr, please refer to createFirewallRule command"); } return null; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { @@ -138,7 +134,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return true; } } - + private Long getVpcId() { if (ipAddressId != null) { IpAddress ipAddr = _networkService.getIp(ipAddressId); @@ -168,16 +164,16 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P PortForwardingRule rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(ipAddressId, callerContext.getCaller()); } - + success = success && _rulesService.applyPortForwardingRules(ipAddressId, callerContext.getCaller()); // State is different after the rule is applied, so get new object here rule = _entityMgr.findById(PortForwardingRule.class, getEntityId()); - FirewallRuleResponse fwResponse = new FirewallRuleResponse(); + FirewallRuleResponse fwResponse = new FirewallRuleResponse(); if (rule != null) { fwResponse = _responseGenerator.createPortForwardingRuleResponse(rule); setResponseObject(fwResponse); @@ -185,13 +181,13 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P fwResponse.setResponseName(getCommandName()); } finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokePortForwardingRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply port forwarding rule"); } } @@ -208,6 +204,13 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return ipAddressId; @@ -220,7 +223,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P @Override public Integer getSourcePortEnd() { - return (publicEndPort == null)? publicStartPort.intValue() : publicEndPort.intValue(); + return (publicEndPort == null)? publicStartPort.intValue() : publicEndPort.intValue(); } @Override @@ -237,14 +240,14 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { ntwkId = networkId; } if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to create port forwarding rule for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -272,10 +275,10 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P public Ip getDestinationIpAddress() { return null; } - + @Override public void setDestinationIpAddress(Ip destinationIpAddress) { - return; + return; } @Override @@ -294,7 +297,7 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } - + try { PortForwardingRule result = _rulesService.createPortForwardingRule(this, virtualMachineId, getOpenFirewall()); setEntityId(result.getId()); @@ -339,26 +342,26 @@ public class CreatePortForwardingRuleCmd extends BaseAsyncCreateCmd implements P } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } @Override public AsyncJob.Type getInstanceType() { diff --git a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java index 36ae4aa3a15..5655b5e430f 100644 --- a/api/src/com/cloud/api/commands/DeleteFirewallRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeleteFirewallRuleCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a firewall rule", responseObject=SuccessResponse.class) +@APICommand(name = "deleteFirewallRule", description="Deletes a firewall rule", responseObject=SuccessResponse.class) public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteFirewallRuleCmd.class.getName()); private static final String s_name = "deletefirewallruleresponse"; @@ -42,13 +39,13 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the firewall rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the firewall rule") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +54,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +62,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -75,7 +72,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting firewall rule id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +85,12 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Rule Id: " + id); boolean result = _firewallService.revokeFirewallRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +98,8 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete firewall rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,7 +109,7 @@ public class DeleteFirewallRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java index ed2c32a279f..8f4d5996df8 100644 --- a/api/src/com/cloud/api/commands/DeletePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/DeletePortForwardingRuleCmd.java @@ -14,25 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.PortForwardingRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a port forwarding rule", responseObject=SuccessResponse.class) +@APICommand(name = "deletePortForwardingRule", description="Deletes a port forwarding rule", responseObject=SuccessResponse.class) public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); private static final String s_name = "deleteportforwardingruleresponse"; @@ -41,13 +38,13 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the port forwarding rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the port forwarding rule") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -56,7 +53,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -64,7 +61,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_NET_RULE_DELETE; @@ -74,7 +71,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting port forwarding rule for id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -84,18 +81,18 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { } else { ownerId = _entityMgr.findById(PortForwardingRule.class, id).getAccountId(); } - + } return ownerId; } - + @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); //revoke corresponding firewall rule first boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _rulesService.revokePortForwardingRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -103,8 +100,8 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete port forwarding rule"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,7 +111,7 @@ public class DeletePortForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getPortForwardigRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/ListFirewallRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListFirewallRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java index 66dcc4d8e35..80581fb7d3b 100644 --- a/api/src/com/cloud/api/commands/ListFirewallRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/ListFirewallRulesCmd.java @@ -14,23 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.Pair; -@Implementation(description="Lists all firewall rules for an IP address.", responseObject=FirewallResponse.class) +@APICommand(name = "listFirewallRules", description="Lists all firewall rules for an IP address.", responseObject=FirewallResponse.class) public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListFirewallRulesCmd.class.getName()); private static final String s_name = "listfirewallrulesresponse"; @@ -38,22 +40,22 @@ public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="the id of IP address of the firwall services") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="the id of IP address of the firwall services") private Long ipAddressId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getIpAddressId() { return ipAddressId; } - + public Long getId() { return id; } @@ -66,20 +68,20 @@ public class ListFirewallRulesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _firewallService.listFirewallRules(this); + Pair, Integer> result = _firewallService.listFirewallRules(this); ListResponse response = new ListResponse(); List fwResponses = new ArrayList(); - - for (FirewallRule fwRule : result) { + + for (FirewallRule fwRule : result.first()) { FirewallResponse ruleData = _responseGenerator.createFirewallResponse(fwRule); ruleData.setObjectName("firewallrule"); fwResponses.add(ruleData); } - response.setResponses(fwResponses); + response.setResponses(fwResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java index 499a574bffb..665af44ad96 100644 --- a/api/src/com/cloud/api/commands/ListPortForwardingRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/ListPortForwardingRulesCmd.java @@ -14,48 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.PortForwardingRule; +import com.cloud.utils.Pair; + +@APICommand(name = "listPortForwardingRules", description="Lists all port forwarding rules for an IP address.", responseObject=FirewallRuleResponse.class) +public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListPortForwardingRulesCmd.class.getName()); + + private static final String s_name = "listportforwardingrulesresponse"; -@Implementation(description="Lists all port forwarding rules for an IP address.", responseObject=FirewallRuleResponse.class) -public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListPortForwardingRulesCmd.class.getName()); - - private static final String s_name = "listportforwardingrulesresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="the id of IP address of the port forwarding services") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="the id of IP address of the port forwarding services") private Long ipAddressId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getIpAddressId() { return ipAddressId; } - + public Long getId() { return id; } @@ -68,20 +69,20 @@ public class ListPortForwardingRulesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _rulesService.listPortForwardingRules(this); + Pair, Integer> result = _rulesService.listPortForwardingRules(this); ListResponse response = new ListResponse(); List fwResponses = new ArrayList(); - - for (PortForwardingRule fwRule : result) { + + for (PortForwardingRule fwRule : result.first()) { FirewallRuleResponse ruleData = _responseGenerator.createPortForwardingRuleResponse(fwRule); ruleData.setObjectName("portforwardingrule"); fwResponses.add(ruleData); } - response.setResponses(fwResponses); + response.setResponses(fwResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java index 37da43a2200..a52ebb77257 100644 --- a/api/src/com/cloud/api/commands/UpdatePortForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/firewall/UpdatePortForwardingRuleCmd.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.firewall; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.event.EventTypes; import com.cloud.network.IpAddress; import com.cloud.user.Account; -@Implementation(responseObject=FirewallRuleResponse.class, description="Updates a port forwarding rule. Only the private port and the virtual machine can be updated.") +@APICommand(name = "updatePortForwardingRule", responseObject=FirewallRuleResponse.class, description="Updates a port forwarding rule. Only the private port and the virtual machine can be updated.") public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdatePortForwardingRuleCmd.class.getName()); private static final String s_name = "updateportforwardingruleresponse"; @@ -46,15 +47,15 @@ public class UpdatePortForwardingRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the port fowarding rule. Valid values are TCP or UDP.") private String protocol; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the IP address id of the port forwarding rule") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the IP address id of the port forwarding rule") private Long publicIpId; @Parameter(name=ApiConstants.PUBLIC_PORT, type=CommandType.STRING, required=true, description="the public port of the port forwarding rule") private String publicPort; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine for the port forwarding rule") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="the ID of the virtual machine for the port forwarding rule") private Long virtualMachineId; ///////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java index 9974aca8429..3b4c4cd2c34 100644 --- a/api/src/com/cloud/api/commands/ListGuestOsCategoriesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCategoriesCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.guest; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GuestOSCategoryResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.storage.GuestOsCategory; +import com.cloud.utils.Pair; -@Implementation(description="Lists all supported OS categories for this cloud.", responseObject=GuestOSCategoryResponse.class) +@APICommand(name = "listOsCategories", description="Lists all supported OS categories for this cloud.", responseObject=GuestOSCategoryResponse.class) public class ListGuestOsCategoriesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -40,10 +41,10 @@ public class ListGuestOsCategoriesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list Os category by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="list Os category by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list os category by name", since="3.0.1") private String name; @@ -69,22 +70,22 @@ public class ListGuestOsCategoriesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _mgr.listGuestOSCategoriesByCriteria(this); + Pair, Integer> result = _mgr.listGuestOSCategoriesByCriteria(this); ListResponse response = new ListResponse(); List osCatResponses = new ArrayList(); - for (GuestOsCategory osCategory : result) { + for (GuestOsCategory osCategory : result.first()) { GuestOSCategoryResponse categoryResponse = new GuestOSCategoryResponse(); - categoryResponse.setId(osCategory.getId()); + categoryResponse.setId(osCategory.getUuid()); categoryResponse.setName(osCategory.getName()); categoryResponse.setObjectName("oscategory"); osCatResponses.add(categoryResponse); } - response.setResponses(osCatResponses); + response.setResponses(osCatResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListGuestOsCmd.java b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/ListGuestOsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java index 396c441f0af..3c145e9bd95 100644 --- a/api/src/com/cloud/api/commands/ListGuestOsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/guest/ListGuestOsCmd.java @@ -14,23 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.guest; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.response.GuestOSCategoryResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GuestOSResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.storage.GuestOS; +import com.cloud.utils.Pair; -@Implementation(description="Lists all supported OS types for this cloud.", responseObject=GuestOSResponse.class) +@APICommand(name = "listOsTypes", description="Lists all supported OS types for this cloud.", responseObject=GuestOSResponse.class) public class ListGuestOsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -40,14 +42,14 @@ public class ListGuestOsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list by Os type Id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="list by Os type Id") private Long id; - @IdentityMapper(entityTableName="guest_os_category") - @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.LONG, description="list by Os Category id") + @Parameter(name=ApiConstants.OS_CATEGORY_ID, type=CommandType.UUID, entityType = GuestOSCategoryResponse.class, + description="list by Os Category id") private Long osCategoryId; - + @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="list os by description", since="3.0.1") private String description; @@ -67,7 +69,7 @@ public class ListGuestOsCmd extends BaseListCmd { public String getDescription() { return description; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -76,23 +78,18 @@ public class ListGuestOsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _mgr.listGuestOSByCriteria(this); + Pair, Integer> result = _mgr.listGuestOSByCriteria(this); ListResponse response = new ListResponse(); List osResponses = new ArrayList(); - for (GuestOS guestOS : result) { - GuestOSResponse guestOSResponse = new GuestOSResponse(); - guestOSResponse.setDescription(guestOS.getDisplayName()); - guestOSResponse.setId(guestOS.getId()); - guestOSResponse.setOsCategoryId(guestOS.getCategoryId()); - - guestOSResponse.setObjectName("ostype"); + for (GuestOS guestOS : result.first()) { + GuestOSResponse guestOSResponse = _responseGenerator.createGuestOSResponse(guestOS); osResponses.add(guestOSResponse); } - response.setResponses(osResponses); + response.setResponses(osResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/AttachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/AttachIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java index 75f2ac71e99..1e154e2a07d --- a/api/src/com/cloud/api/commands/AttachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/AttachIsoCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Attaches an ISO to a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "attachIso", description="Attaches an ISO to a virtual machine.", responseObject=UserVmResponse.class) public class AttachIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AttachIsoCmd.class.getName()); @@ -41,12 +42,12 @@ public class AttachIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the virtual machine") private Long virtualMachineId; @@ -71,14 +72,14 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm vm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); if (vm == null) { throw new InvalidParameterValueException("Unable to find virtual machine by id " + getVirtualMachineId()); - } - + } + return vm.getAccountId(); } @@ -91,16 +92,16 @@ public class AttachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching ISO: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); + UserContext.current().setEventDetails("Vm Id: " +getVirtualMachineId()+ " ISO Id: "+getId()); boolean result = _templateService.attachIso(id, virtualMachineId); if (result) { UserVm userVm = _responseGenerator.findUserVmById(virtualMachineId); if (userVm != null) { - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to attach iso"); diff --git a/api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java similarity index 57% rename from api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java index 0af58555ea6..b449ff59180 100644 --- a/api/src/com/cloud/api/commands/ListIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/CopyIsoCmd.java @@ -14,29 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import org.apache.log4j.Logger; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.command.user.template.CopyTemplateCmd; -public class ListIsoPermissionsCmd extends ListTemplateOrIsoPermissionsCmd { - protected String getResponseName() { - return "listisopermissionsresponse"; - } - - @Override - public String getMediaType() { - return "iso"; - } - - @Override - protected Logger getLogger() { - return Logger.getLogger(ListIsoPermissionsCmd.class.getName()); - } - - protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return template.getFormat().equals(ImageFormat.ISO); - } +@APICommand(name = "copyIso", description="Copies an iso from one zone to another.", responseObject=TemplateResponse.class) +public class CopyIsoCmd extends CopyTemplateCmd { + public static final Logger s_logger = Logger.getLogger(CopyIsoCmd.class.getName()); + private static final String s_name = "copyisoresponse"; } + diff --git a/api/src/com/cloud/api/commands/DeleteIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/DeleteIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java index 70ce7312c49..44efbf88f2c --- a/api/src/com/cloud/api/commands/DeleteIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DeleteIsoCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes an ISO file.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteIso", description="Deletes an ISO file.", responseObject=SuccessResponse.class) public class DeleteIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteIsoCmd.class.getName()); private static final String s_name = "deleteisosresponse"; @@ -41,12 +42,12 @@ public class DeleteIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of the zone of the ISO file. If not specified, the ISO will be deleted from all the zones") private Long zoneId; @@ -70,11 +71,11 @@ public class DeleteIsoCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getStaticName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate iso = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -94,18 +95,18 @@ public class DeleteIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting iso " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ - UserContext.current().setEventDetails("ISO Id: "+getId()); + UserContext.current().setEventDetails("ISO Id: "+getId()); boolean result = _templateService.deleteIso(this); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); diff --git a/api/src/com/cloud/api/commands/DetachIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/DetachIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java index af318d7537c..eb1c6eed2d6 --- a/api/src/com/cloud/api/commands/DetachIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/DetachIsoCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.response.TemplateResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.uservm.UserVm; -@Implementation(description="Detaches any ISO file (if any) currently attached to a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "detachIso", description="Detaches any ISO file (if any) currently attached to a virtual machine.", responseObject=UserVmResponse.class) public class DetachIsoCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DetachIsoCmd.class.getName()); @@ -40,8 +41,8 @@ public class DetachIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="The ID of the virtual machine") private Long virtualMachineId; ///////////////////////////////////////////////////// @@ -68,7 +69,7 @@ public class DetachIsoCmd extends BaseAsyncCmd { return vm.getAccountId(); } else { throw new InvalidParameterValueException("Unable to find vm by id " + getVirtualMachineId()); - } + } } @Override @@ -80,14 +81,14 @@ public class DetachIsoCmd extends BaseAsyncCmd { public String getEventDescription() { return "detaching ISO from vm: " + getVirtualMachineId(); } - + @Override public void execute(){ boolean result = _templateService.detachIso(virtualMachineId); if (result) { - UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId); - UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); - response.setResponseName(DeployVMCmd.getResultObjectName()); + UserVm userVm = _entityMgr.findById(UserVm.class, virtualMachineId); + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", userVm).get(0); + response.setResponseName(DeployVMCmd.getResultObjectName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach iso"); diff --git a/api/src/com/cloud/api/commands/ExtractIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/ExtractIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java index a9fb606bb08..5f8303ec320 --- a/api/src/com/cloud/api/commands/ExtractIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ExtractIsoCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InternalErrorException; @@ -33,9 +30,9 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts an ISO", responseObject=ExtractResponse.class) +@APICommand(name = "extractIso", description="Extracts an ISO", responseObject=ExtractResponse.class) public class ExtractIsoCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractIsoCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractIsoCmd.class.getName()); private static final String s_name = "extractisoresponse"; @@ -43,17 +40,17 @@ public class ExtractIsoCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the ISO file") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + required=true, description="the ID of the ISO file") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the ISO would be extracted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="the ID of the zone where the ISO is originally located") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="the ID of the zone where the ISO is originally located") private Long zoneId; - + @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; @@ -109,19 +106,19 @@ public class ExtractIsoCmd extends BaseAsyncCmd { public static String getStaticName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); Long uploadId = _templateService.extract(this); if (uploadId != null){ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode); diff --git a/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java new file mode 100644 index 00000000000..0ca711f4664 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsoPermissionsCmd.java @@ -0,0 +1,46 @@ +// Licensedname = "listIsoPermissions", 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 org.apache.cloudstack.api.command.user.iso; + +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.log4j.Logger; + +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.template.VirtualMachineTemplate; + +@APICommand(name="listIsoPermissions", description="List iso visibility and all accounts that have permissions to view this iso.", responseObject=TemplatePermissionsResponse.class) +public class ListIsoPermissionsCmd extends BaseListTemplateOrIsoPermissionsCmd { + protected String getResponseName() { + return "listisopermissionsresponse"; + } + + @Override + public String getMediaType() { + return "iso"; + } + + @Override + protected Logger getLogger() { + return Logger.getLogger(ListIsoPermissionsCmd.class.getName()); + } + + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { + return template.getFormat().equals(ImageFormat.ISO); + } +} diff --git a/api/src/com/cloud/api/commands/ListIsosCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java old mode 100755 new mode 100644 similarity index 76% rename from api/src/com/cloud/api/commands/ListIsosCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java index 35a996e9df3..e6ccfff3449 --- a/api/src/com/cloud/api/commands/ListIsosCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/ListIsosCmd.java @@ -14,29 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import java.util.ArrayList; import java.util.List; import java.util.Set; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.async.AsyncJob; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.Pair; -@Implementation(description="Lists all available ISO files.", responseObject=TemplateResponse.class) +@APICommand(name = "listIsos", description="Lists all available ISO files.", responseObject=TemplateResponse.class) public class ListIsosCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListIsosCmd.class.getName()); @@ -52,8 +51,8 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list all isos by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = TemplateResponse.class, + description="list all isos by id") private Long id; @Parameter(name=ApiConstants.IS_PUBLIC, type=CommandType.BOOLEAN, description="true if the ISO is publicly available to all users, false otherwise.") @@ -63,19 +62,19 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { private Boolean ready; @Parameter(name=ApiConstants.ISO_FILTER, type=CommandType.STRING, description="possible values are \"featured\", \"self\", \"self-executable\",\"executable\", and \"community\". " + - "* featured-ISOs that are featured and are publicself-ISOs that have been registered/created by the owner. " + - "* selfexecutable-ISOs that have been registered/created by the owner that can be used to deploy a new VM. " + - "* executable-all ISOs that can be used to deploy a new VM " + - "* community-ISOs that are public.") + "* featured-ISOs that are featured and are publicself-ISOs that have been registered/created by the owner. " + + "* selfexecutable-ISOs that have been registered/created by the owner that can be used to deploy a new VM. " + + "* executable-all ISOs that can be used to deploy a new VM " + + "* community-ISOs that are public.") private String isoFilter = TemplateFilter.selfexecutable.toString(); @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list all isos by name") private String isoName; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of the zone") private Long zoneId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -112,7 +111,7 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public boolean listInReadyState() { Account account = UserContext.current().getCaller(); // It is account specific if account is admin type and domainId and accountName are not null @@ -121,29 +120,29 @@ public class ListIsosCmd extends BaseListTaggedResourcesCmd { TemplateFilter templateFilter = TemplateFilter.valueOf(getIsoFilter()); boolean onlyReady = (templateFilter == TemplateFilter.featured) || (templateFilter == TemplateFilter.selfexecutable) || (templateFilter == TemplateFilter.sharedexecutable) || (templateFilter == TemplateFilter.executable && isAccountSpecific) || (templateFilter == TemplateFilter.community); - + if (!onlyReady) { - if (isReady() != null && isReady().booleanValue() != onlyReady) { - onlyReady = isReady().booleanValue(); - } + if (isReady() != null && isReady().booleanValue() != onlyReady) { + onlyReady = isReady().booleanValue(); + } } - + return onlyReady; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Iso; + return AsyncJob.Type.Iso; } - + @Override public void execute(){ Set> isoZonePairSet = _mgr.listIsos(this); diff --git a/api/src/com/cloud/api/commands/RegisterIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/RegisterIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java index 34554772c4b..214d18de5cc --- a/api/src/com/cloud/api/commands/RegisterIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/RegisterIsoCmd.java @@ -14,28 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=TemplateResponse.class, description="Registers an existing ISO into the CloudStack Cloud.") +@APICommand(name = "registerIso", responseObject=TemplateResponse.class, description="Registers an existing ISO into the CloudStack Cloud.") public class RegisterIsoCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterIsoCmd.class.getName()); @@ -59,35 +56,35 @@ public class RegisterIsoCmd extends BaseCmd { @Parameter(name=ApiConstants.IS_EXTRACTABLE, type=CommandType.BOOLEAN, description="true if the iso or its derivatives are extractable; default is false") private Boolean extractable; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the ISO") private String isoName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS Type that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + description="the ID of the OS Type that best represents the OS of this ISO. If the iso is bootable this parameter needs to be passed") private Long osTypeId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL to where the ISO is currently being hosted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone you wish to register the ISO to.") - private Long zoneId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone you wish to register the ISO to.") + private Long zoneId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") private Long domainId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account name. Must be used with domainId.") private String accountName; - + @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this ISO") private String checksum; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Register iso for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Register iso for the project") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -111,7 +108,7 @@ public class RegisterIsoCmd extends BaseCmd { public Boolean isExtractable() { return extractable; } - + public String getIsoName() { return isoName; } @@ -129,36 +126,36 @@ public class RegisterIsoCmd extends BaseCmd { } public Long getDomainId() { - return domainId; - } + return domainId; + } - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } public String getChecksum() { return checksum; - } - + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } - + } + @Override public void execute() throws ResourceAllocationException{ VirtualMachineTemplate template = _templateService.registerIso(this); @@ -166,11 +163,11 @@ public class RegisterIsoCmd extends BaseCmd { ListResponse response = new ListResponse(); List templateResponses = _responseGenerator.createIsoResponses(template.getId(), zoneId, false); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register iso"); } - + } } diff --git a/api/src/com/cloud/api/commands/UpdateIsoCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/commands/UpdateIsoCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java index 92417912cc9..f54f8a66daa --- a/api/src/com/cloud/api/commands/UpdateIsoCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoCmd.java @@ -14,31 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates an ISO file.", responseObject=TemplateResponse.class) -public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { +@APICommand(name = "updateIso", description="Updates an ISO file.", responseObject=TemplateResponse.class) +public class UpdateIsoCmd extends BaseUpdateTemplateOrIsoCmd { public static final Logger s_logger = Logger.getLogger(UpdateIsoCmd.class.getName()); private static final String s_name = "updateisoresponse"; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + @Override public Boolean isPasswordEnabled() { return null; } - + @Override public String getFormat() { return null; @@ -52,7 +53,7 @@ public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -62,7 +63,7 @@ public class UpdateIsoCmd extends UpdateTemplateOrIsoCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualMachineTemplate result = _mgr.updateTemplate(this); diff --git a/api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java index 7173d91bb87..b7a2c5685e0 100644 --- a/api/src/com/cloud/api/commands/UpdateIsoPermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/iso/UpdateIsoPermissionsCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.iso; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; import org.apache.log4j.Logger; -import com.cloud.api.Implementation; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates iso permissions", responseObject=SuccessResponse.class) -public class UpdateIsoPermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd { +@APICommand(name = "updateIsoPermissions", description="Updates iso permissions", responseObject=SuccessResponse.class) +public class UpdateIsoPermissionsCmd extends BaseUpdateTemplateOrIsoPermissionsCmd { protected String getResponseName() { - return "updateisopermissionsresponse"; + return "updateisopermissionsresponse"; + } + + protected Logger getLogger() { + return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName()); } - protected Logger getLogger() { - return Logger.getLogger(UpdateIsoPermissionsCmd.class.getName()); - } - @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); diff --git a/api/src/com/cloud/api/commands/ListAsyncJobsCmd.java b/api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListAsyncJobsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java index bd6e80bd094..50ac52e025f 100644 --- a/api/src/com/cloud/api/commands/ListAsyncJobsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/job/ListAsyncJobsCmd.java @@ -14,21 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.job; import java.util.ArrayList; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.async.AsyncJob; +import com.cloud.utils.Pair; -@Implementation(description="Lists all pending asynchronous jobs for the account.", responseObject=AsyncJobResponse.class) +@APICommand(name = "listAsyncJobs", description="Lists all pending asynchronous jobs for the account.", responseObject=AsyncJobResponse.class) public class ListAsyncJobsCmd extends BaseListAccountResourcesCmd { private static final String s_name = "listasyncjobsresponse"; @@ -58,15 +60,10 @@ public class ListAsyncJobsCmd extends BaseListAccountResourcesCmd { @Override public void execute(){ - List result = _mgr.searchForAsyncJobs(this); - ListResponse response = new ListResponse(); - List jobResponses = new ArrayList(); - for (AsyncJob job : result) { - jobResponses.add(_responseGenerator.createAsyncJobResponse(job)); - } - response.setResponses(jobResponses); + ListResponse response = _queryService.searchForAsyncJobs(this); response.setResponseName(getCommandName()); this.setResponseObject(response); + } } diff --git a/api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java b/api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java rename to api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java index d011a7eb571..256d4ff5cc3 100644 --- a/api/src/com/cloud/api/commands/QueryAsyncJobResultCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/job/QueryAsyncJobResultCmd.java @@ -14,19 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.job; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.AsyncJobResponse; import com.cloud.user.Account; -@Implementation(description="Retrieves the current status of asynchronous job.", responseObject=AsyncJobResponse.class) +@APICommand(name = "queryAsyncJobResult", description="Retrieves the current status of asynchronous job.", responseObject=AsyncJobResponse.class) public class QueryAsyncJobResultCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(QueryAsyncJobResultCmd.class.getName()); @@ -36,8 +35,8 @@ public class QueryAsyncJobResultCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="async_job") - @Parameter(name=ApiConstants.JOB_ID, type=CommandType.LONG, required=true, description="the ID of the asychronous job") + @Parameter(name=ApiConstants.JOB_ID, type=CommandType.UUID, entityType=AsyncJobResponse.class, + required=true, description="the ID of the asychronous job") private Long id; ///////////////////////////////////////////////////// @@ -56,12 +55,12 @@ public class QueryAsyncJobResultCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ AsyncJobResponse response = _responseGenerator.queryJobResult(this); diff --git a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java index 2a88e878597..972673f4954 100644 --- a/api/src/com/cloud/api/commands/AssignToLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/AssignToLoadBalancerRuleCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.LoadBalancer; @@ -35,7 +36,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(description="Assigns virtual machine or a list of virtual machines to a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "assignToLoadBalancerRule", description="Assigns virtual machine or a list of virtual machines to a load balancer rule.", responseObject=SuccessResponse.class) public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AssignToLoadBalancerRuleCmd.class.getName()); @@ -45,12 +46,12 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, required=true, description="the list of IDs of the virtual machine that are being assigned to the load balancer rule(i.e. virtualMachineIds=1,2,3)") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the list of IDs of the virtual machine that are being assigned to the load balancer rule(i.e. virtualMachineIds=1,2,3)") private List virtualMachineIds; ///////////////////////////////////////////////////// @@ -92,7 +93,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "applying instances for load balancer: " + getLoadBalancerId() + " (ids: " + StringUtils.join(getVirtualMachineIds(), ",") + ")"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getLoadBalancerId()+" VmIds: "+StringUtils.join(getVirtualMachineIds(), ",")); @@ -104,7 +105,7 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to assign load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,10 +113,10 @@ public class AssignToLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java index c2410c882fa..dc80d312769 100644 --- a/api/src/com/cloud/api/commands/CreateLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLBStickinessPolicyCmd.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.Map; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.event.EventTypes; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.StickinessPolicy; -import com.cloud.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates a Load Balancer stickiness policy ", responseObject = LBStickinessResponse.class, since="3.0.0") +@APICommand(name = "createLBStickinessPolicy", description = "Creates a Load Balancer stickiness policy ", responseObject = LBStickinessResponse.class, since="3.0.0") @SuppressWarnings("rawtypes") public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger @@ -50,9 +50,9 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, required = true, description = "the ID of the load balancer rule") + + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") private Long lbRuleId; @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the LB Stickiness policy") @@ -117,7 +117,7 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { public void execute() throws ResourceAllocationException, ResourceUnavailableException { StickinessPolicy policy = null; boolean success = false; - + try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); success = _lbService.applyLBStickinessPolicy(this); @@ -131,9 +131,9 @@ public class CreateLBStickinessPolicyCmd extends BaseAsyncCreateCmd { } } finally { if (!success || (policy == null)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create stickiness policy "); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create stickiness policy "); } - } + } } @Override diff --git a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java index 80a86847a7e..4aacc8e19b2 100644 --- a/api/src/com/cloud/api/commands/CreateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/CreateLoadBalancerRuleCmd.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -44,7 +47,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) +@APICommand(name = "createLoadBalancerRule", description="Creates a load balancer rule", responseObject=LoadBalancerResponse.class) public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements LoadBalancer */{ public static final Logger s_logger = Logger.getLogger(CreateLoadBalancerRuleCmd.class.getName()); @@ -66,37 +69,37 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements @Parameter(name=ApiConstants.PRIVATE_PORT, type=CommandType.INTEGER, required=true, description="the private port of the private ip address/virtual machine where the network traffic will be load balanced to") private Integer privatePort; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, description="public ip address id from where the network traffic will be load balanced from") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="public ip address id from where the network traffic will be load balanced from") private Long publicIpId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="zone where the load balancer is going to be created. This parameter is required when LB service provider is ElasticLoadBalancerVm") private Long zoneId; @Parameter(name=ApiConstants.PUBLIC_PORT, type=CommandType.INTEGER, required=true, description="the public port from where the network traffic will be load balanced from") private Integer publicPort; @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for" + - " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + + " source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. If not specified 1) defaulted to false when LB" + " rule is being created for VPC guest network 2) in all other cases defaulted to true") private Boolean openFirewall; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the load balancer. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the load balancer") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID associated with the load balancer") private Long domainId; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="The guest network this " + - "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="The guest network this " + + "rule will be created for. Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -118,23 +121,23 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getSourceIpAddressId() { - if (publicIpId != null) { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr == null || !ipAddr.readyToUse()) { - throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); - } - } else if (getEntityId() != null) { - LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - return rule.getSourceIpAddressId(); - } - - return publicIpId; + if (publicIpId != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr == null || !ipAddr.readyToUse()) { + throw new InvalidParameterValueException("Unable to create load balancer rule, invalid IP address id " + ipAddr.getId()); + } + } else if (getEntityId() != null) { + LoadBalancer rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); + return rule.getSourceIpAddressId(); + } + + return publicIpId; } - + private Long getVpcId() { if (publicIpId != null) { IpAddress ipAddr = _networkService.getIp(publicIpId); @@ -146,36 +149,36 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } return null; } - - + + public Long getNetworkId() { if (networkId != null) { return networkId; - } - Long zoneId = getZoneId(); - - if (zoneId == null) { - Long ipId = getSourceIpAddressId(); - if (ipId == null) { - throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); - } } - + Long zoneId = getZoneId(); + + if (zoneId == null) { + Long ipId = getSourceIpAddressId(); + if (ipId == null) { + throw new InvalidParameterValueException("Either networkId or zoneId or publicIpId has to be specified"); + } + } + if (zoneId != null) { - DataCenter zone = _configService.getZone(zoneId); - if (zone.getNetworkType() == NetworkType.Advanced) { + DataCenter zone = _configService.getZone(zoneId); + if (zone.getNetworkType() == NetworkType.Advanced) { List networks = _networkService.getIsolatedNetworksOwnedByAccountInZone(getZoneId(), _accountService.getAccount(getEntityOwnerId())); if (networks.size() == 0) { String domain = _domainService.getDomain(getDomainId()).getName(); throw new InvalidParameterValueException("Account name=" + getAccountName() + " domain=" + domain + " doesn't have virtual networks in zone=" + zone.getName()); } - + if (networks.size() < 1) { - throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); + throw new InvalidParameterValueException("Account doesn't have any Isolated networks in the zone"); } else if (networks.size() > 1) { - throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); + throw new InvalidParameterValueException("Account has more than one Isolated network in the zone"); } - + return networks.get(0).getId(); } else { Network defaultGuestNetwork = _networkService.getExclusiveGuestNetwork(zoneId); @@ -186,23 +189,23 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } else { - IpAddress ipAddr = _networkService.getIp(publicIpId); - if (ipAddr.getAssociatedWithNetworkId() != null) { + IpAddress ipAddr = _networkService.getIp(publicIpId); + if (ipAddr.getAssociatedWithNetworkId() != null) { return ipAddr.getAssociatedWithNetworkId(); - } else { - throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); - } + } else { + throw new InvalidParameterValueException("Ip address id=" + publicIpId + " is not associated with any network"); + } } } public Integer getPublicPort() { return publicPort; } - + public String getName() { return loadBalancerRuleName; } - + public Boolean getOpenFirewall() { boolean isVpc = getVpcId() == null ? false : true; if (openFirewall != null) { @@ -217,7 +220,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements return true; } } - + public List getSourceCidrList() { if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); @@ -233,33 +236,33 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getCommandName() { return s_name; } - + @Override - public void execute() throws ResourceAllocationException, ResourceUnavailableException { - + public void execute() throws ResourceAllocationException, ResourceUnavailableException { + UserContext callerContext = UserContext.current(); boolean success = true; LoadBalancer rule = null; try { UserContext.current().setEventDetails("Rule Id: " + getEntityId()); - + if (getOpenFirewall()) { success = success && _firewallService.applyFirewallRules(getSourceIpAddressId(), callerContext.getCaller()); } // State might be different after the rule is applied, so get new object here rule = _entityMgr.findById(LoadBalancer.class, getEntityId()); - LoadBalancerResponse lbResponse = new LoadBalancerResponse(); + LoadBalancerResponse lbResponse = new LoadBalancerResponse(); if (rule != null) { lbResponse = _responseGenerator.createLoadBalancerResponse(rule); setResponseObject(lbResponse); } lbResponse.setResponseName(getCommandName()); } catch (Exception ex) { - s_logger.warn("Failed to create LB rule due to exception ", ex); + s_logger.warn("Failed to create LB rule due to exception ", ex); }finally { if (!success || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } @@ -270,7 +273,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements } } } - + @Override public void create() { //cidr list parameter is deprecated @@ -300,11 +303,11 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public String getProtocol() { return NetUtils.TCP_PROTO; } - - public long getAccountId() { + + public long getAccountId() { if (publicIpId != null) return _networkService.getIp(getSourceIpAddressId()).getAccountId(); - + Account account = null; if ((domainId != null) && (accountName != null)) { account = _responseGenerator.findAccountByNameDomain(accountName, domainId); @@ -334,16 +337,16 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public int getDefaultPortEnd() { return privatePort.intValue(); } - + @Override public long getEntityOwnerId() { return getAccountId(); } - + public String getAccountName() { return accountName; } - + public Long getZoneId() { return zoneId; } @@ -371,7 +374,7 @@ public class CreateLoadBalancerRuleCmd extends BaseAsyncCreateCmd /*implements public void setSourceIpAddressId(Long ipId) { this.publicIpId = ipId; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java index 55195f7180e..9329bd35aba 100644 --- a/api/src/com/cloud/api/commands/DeleteLBStickinessPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLBStickinessPolicyCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.response.LBStickinessResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.StickinessPolicy; @@ -33,7 +33,7 @@ import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Deletes a LB stickiness policy.", responseObject = SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteLBStickinessPolicy", description = "Deletes a LB stickiness policy.", responseObject = SuccessResponse.class, since="3.0.0") public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteLBStickinessPolicyCmd.class.getName()); private static final String s_name = "deleteLBstickinessrruleresponse"; @@ -41,8 +41,8 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="load_balancer_stickiness_policies") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "the ID of the LB stickiness policy") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = LBStickinessResponse.class, + required = true, description = "the ID of the LB stickiness policy") private Long id; // /////////////////////////////////////////////////// @@ -105,11 +105,11 @@ public class DeleteLBStickinessPolicyCmd extends BaseAsyncCmd { StickinessPolicy policy = _entityMgr.findById(StickinessPolicy.class, getId()); if (policy == null) { - throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find LB stickiness rule: " + id); } LoadBalancer lb = _lbService.findById(policy.getLoadBalancerId()); if (lb == null) { - throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); + throw new InvalidParameterValueException("Unable to find load balancer rule for stickiness rule: " + id); } return lb.getNetworkId(); } diff --git a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java index 72330c20912..d53155f17b9 100644 --- a/api/src/com/cloud/api/commands/DeleteLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/DeleteLoadBalancerRuleCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +29,7 @@ import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteLoadBalancerRule", description="Deletes a load balancer rule.", responseObject=SuccessResponse.class) public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteLoadBalancerRuleCmd.class.getName()); private static final String s_name = "deleteloadbalancerruleresponse"; @@ -41,8 +37,8 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; @@ -82,13 +78,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting load balancer: " + getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); boolean result = _firewallService.revokeRelatedFirewallRule(id, true); result = result && _lbService.deleteLoadBalancerRule(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -96,7 +92,7 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete load balancer"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -104,13 +100,13 @@ public class DeleteLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java index 6be47c13221..90708c0bfe0 100644 --- a/api/src/com/cloud/api/commands/ListLBStickinessPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLBStickinessPoliciesCmd.java @@ -14,26 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.StickinessPolicy; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Lists LBStickiness policies.", responseObject = LBStickinessResponse.class, since="3.0.0") +@APICommand(name = "listLBStickinessPolicies", description = "Lists LBStickiness policies.", responseObject = LBStickinessResponse.class, since="3.0.0") public class ListLBStickinessPoliciesCmd extends BaseListCmd { public static final Logger s_logger = Logger .getLogger(ListLBStickinessPoliciesCmd.class.getName()); @@ -43,11 +43,9 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.LBID, type = CommandType.LONG, required = true, description = "the ID of the load balancer rule") + @Parameter(name = ApiConstants.LBID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + required = true, description = "the ID of the load balancer rule") private Long lbRuleId; - - // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// @@ -55,8 +53,6 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { public Long getLbRuleId() { return lbRuleId; } - - // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// @@ -72,17 +68,17 @@ public class ListLBStickinessPoliciesCmd extends BaseListCmd { List spResponses = new ArrayList(); LoadBalancer lb = _lbService.findById(getLbRuleId()); ListResponse response = new ListResponse(); - + if (lb != null) { - //check permissions - Account caller = UserContext.current().getCaller(); - _accountService.checkAccess(caller, null, true, lb); + //check permissions + Account caller = UserContext.current().getCaller(); + _accountService.checkAccess(caller, null, true, lb); List stickinessPolicies = _lbService.searchForLBStickinessPolicies(this); LBStickinessResponse spResponse = _responseGenerator.createLBStickinessPolicyResponse(stickinessPolicies, lb); spResponses.add(spResponse); response.setResponses(spResponses); } - + response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java index d721914f5f9..374c6fb25e5 100644 --- a/api/src/com/cloud/api/commands/ListLoadBalancerRuleInstancesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRuleInstancesCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.uservm.UserVm; -@Implementation(description="List all virtual machine instances that are assigned to a load balancer rule.", responseObject=UserVmResponse.class) +@APICommand(name = "listLoadBalancerRuleInstances", description="List all virtual machine instances that are assigned to a load balancer rule.", responseObject=UserVmResponse.class) public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger (ListLoadBalancerRuleInstancesCmd.class.getName()); @@ -43,8 +43,8 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { @Parameter(name=ApiConstants.APPLIED, type=CommandType.BOOLEAN, description="true if listing all virtual machines currently applied to the load balancer rule; default is true") private Boolean applied; - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the load balancer rule") private Long id; ///////////////////////////////////////////////////// @@ -67,14 +67,14 @@ public class ListLoadBalancerRuleInstancesCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = _lbService.listLoadBalancerInstances(this); ListResponse response = new ListResponse(); List vmResponses = new ArrayList(); if (result != null) { - vmResponses = _responseGenerator.createUserVmResponse("loadbalancerruleinstance", result.toArray(new UserVm[result.size()])); + vmResponses = _responseGenerator.createUserVmResponse("loadbalancerruleinstance", result.toArray(new UserVm[result.size()])); } response.setResponses(vmResponses); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java similarity index 66% rename from api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java index 43b05402269..d0d4e8db85c 100644 --- a/api/src/com/cloud/api/commands/ListLoadBalancerRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/ListLoadBalancerRulesCmd.java @@ -14,23 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.network.rules.LoadBalancer; +import com.cloud.utils.Pair; -@Implementation(description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class) +@APICommand(name = "listLoadBalancerRules", description = "Lists load balancer rules.", responseObject = LoadBalancerResponse.class) public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListLoadBalancerRulesCmd.class.getName()); @@ -40,23 +44,23 @@ public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "the ID of the load balancer rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = FirewallRuleResponse.class, + description = "the ID of the load balancer rule") private Long id; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, description = "the name of the load balancer rule") private String loadBalancerRuleName; - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name = ApiConstants.PUBLIC_IP_ID, type = CommandType.LONG, description = "the public IP address id of the load balancer rule ") + @Parameter(name = ApiConstants.PUBLIC_IP_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, + description = "the public IP address id of the load balancer rule ") private Long publicIpId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.LONG, description = "the ID of the virtual machine of the load balancer rule") + @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, + description = "the ID of the virtual machine of the load balancer rule") private Long virtualMachineId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the availability zone ID") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the availability zone ID") private Long zoneId; // /////////////////////////////////////////////////// @@ -94,17 +98,17 @@ public class ListLoadBalancerRulesCmd extends BaseListTaggedResourcesCmd { @Override public void execute() { - List loadBalancers = _lbService.searchForLoadBalancers(this); + Pair, Integer> loadBalancers = _lbService.searchForLoadBalancers(this); ListResponse response = new ListResponse(); List lbResponses = new ArrayList(); if (loadBalancers != null) { - for (LoadBalancer loadBalancer : loadBalancers) { + for (LoadBalancer loadBalancer : loadBalancers.first()) { LoadBalancerResponse lbResponse = _responseGenerator.createLoadBalancerResponse(loadBalancer); lbResponse.setObjectName("loadbalancerrule"); lbResponses.add(lbResponse); } } - response.setResponses(lbResponses); + response.setResponses(lbResponses, loadBalancers.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java index abc850f7471..f56f06d15c5 100644 --- a/api/src/com/cloud/api/commands/RemoveFromLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/RemoveFromLoadBalancerRuleCmd.java @@ -14,20 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.LoadBalancer; @@ -35,22 +32,22 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(description="Removes a virtual machine or a list of virtual machines from a load balancer rule.", responseObject=SuccessResponse.class) +@APICommand(name = "removeFromLoadBalancerRule", description="Removes a virtual machine or a list of virtual machines from a load balancer rule.", responseObject=SuccessResponse.class) public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveFromLoadBalancerRuleCmd.class.getName()); private static final String s_name = "removefromloadbalancerruleresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the load balancer rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="The ID of the load balancer rule") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, required = true, collectionType=CommandType.LONG, description="the list of IDs of the virtual machines that are being removed from the load balancer rule (i.e. virtualMachineIds=1,2,3)") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_IDS, type=CommandType.LIST, required = true, collectionType=CommandType.UUID, entityType = UserVmResponse.class, + description="the list of IDs of the virtual machines that are being removed from the load balancer rule (i.e. virtualMachineIds=1,2,3)") private List virtualMachineIds; ///////////////////////////////////////////////////// @@ -104,7 +101,7 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove instance from load balancer rule"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,10 +109,10 @@ public class RemoveFromLoadBalancerRuleCmd extends BaseAsyncCmd { @Override public Long getSyncObjId() { - LoadBalancer lb = _lbService.findById(id); - if(lb == null){ - throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); - } + LoadBalancer lb = _lbService.findById(id); + if(lb == null){ + throw new InvalidParameterValueException("Unable to find load balancer rule: " + id); + } return lb.getNetworkId(); } } diff --git a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java index a110a8d9af1..8a86f74260d 100644 --- a/api/src/com/cloud/api/commands/UpdateLoadBalancerRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/loadbalancer/UpdateLoadBalancerRuleCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.loadbalancer; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Updates load balancer", responseObject=LoadBalancerResponse.class) +@APICommand(name = "updateLoadBalancerRule", description="Updates load balancer", responseObject=LoadBalancerResponse.class) public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateLoadBalancerRuleCmd.class.getName()); private static final String s_name = "updateloadbalancerruleresponse"; @@ -46,8 +42,8 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.DESCRIPTION, type=CommandType.STRING, description="the description of the load balancer rule", length=4096) private String description; - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the load balancer rule to update") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the id of the load balancer rule to update") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the load balancer rule") @@ -100,7 +96,7 @@ public class UpdateLoadBalancerRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return "updating load balancer rule"; } - + @Override public void execute(){ UserContext.current().setEventDetails("Load balancer Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java similarity index 87% rename from api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java index a688d134352..e612b84c835 100644 --- a/api/src/com/cloud/api/commands/CreateIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/CreateIpForwardingRuleCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +41,7 @@ import com.cloud.network.rules.StaticNatRule; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class) +@APICommand(name = "createIpForwardingRule", description="Creates an ip forwarding rule", responseObject=FirewallRuleResponse.class) public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements StaticNatRule { public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); @@ -51,22 +51,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP address id of the forwarding rule, already associated via associateIp") private Long ipAddressId; - + @Parameter(name=ApiConstants.START_PORT, type=CommandType.INTEGER, required=true, description="the start port for the rule") private Integer startPort; @Parameter(name=ApiConstants.END_PORT, type=CommandType.INTEGER, description="the end port for the rule") private Integer endPort; - + @Parameter(name=ApiConstants.PROTOCOL, type=CommandType.STRING, required=true, description="the protocol for the rule. Valid values are TCP or UDP.") private String protocol; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to forward traffic from") private List cidrlist; @@ -74,23 +74,23 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getEntityTable() { - return "firewall_rules"; + return "firewall_rules"; } - + public Long getIpAddressId() { return ipAddressId; } - + public int getStartPort() { return startPort; } - + public int getEndPort() { return endPort; } - + public Boolean getOpenFirewall() { if (openFirewall != null) { return openFirewall; @@ -109,17 +109,17 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta } @Override - public void execute() throws ResourceUnavailableException{ + public void execute() throws ResourceUnavailableException{ boolean result = true; FirewallRule rule = null; try { UserContext.current().setEventDetails("Rule Id: "+ getEntityId()); - + if (getOpenFirewall()) { result = result && _firewallService.applyFirewallRules(ipAddressId, UserContext.current().getCaller()); } - + result = result && _rulesService.applyStaticNatRules(ipAddressId, UserContext.current().getCaller()); rule = _entityMgr.findById(FirewallRule.class, getEntityId()); StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); @@ -128,26 +128,26 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta this.setResponseObject(fwResponse); } finally { if (!result || rule == null) { - + if (getOpenFirewall()) { _firewallService.revokeRelatedFirewallRule(getEntityId(), true); } - + _rulesService.revokeStaticNatRule(getEntityId(), true); - + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Error in creating ip forwarding rule on the domr"); } } } - @Override - public void create() { - - //cidr list parameter is deprecated + @Override + public void create() { + + //cidr list parameter is deprecated if (cidrlist != null) { throw new InvalidParameterValueException("Parameter cidrList is deprecated; if you need to open firewall rule for the specific cidr, please refer to createFirewallRule command"); } - + try { StaticNatRule rule = _rulesService.createStaticNatRule(this, getOpenFirewall()); this.setEntityId(rule.getId()); @@ -155,7 +155,7 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta s_logger.info("Unable to create Static Nat Rule due to ", e); throw new ServerApiException(BaseCmd.NETWORK_RULE_CONFLICT_ERROR, e.getMessage()); } - } + } @Override public long getEntityOwnerId() { @@ -178,16 +178,16 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ("Applying an ipforwarding 1:1 NAT rule for Ip: "+ip.getAddress()+" with virtual machine:"+ this.getVirtualMachineId()); } - + private long getVirtualMachineId() { Long vmId = _networkService.getIp(ipAddressId).getAssociatedWithVmId(); - + if (vmId == null) { throw new InvalidParameterValueException("Ip address is not associated with any network, unable to create static nat rule"); } return vmId; } - + @Override public String getDestIpAddress(){ return null; @@ -248,13 +248,20 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta IpAddress ip = _networkService.getIp(ipAddressId); return ip.getAccountId(); } - + @Override public String getXid() { // FIXME: We should allow for end user to specify Xid. return null; } - + + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -272,12 +279,12 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta } return ip; } - + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -287,22 +294,22 @@ public class CreateIpForwardingRuleCmd extends BaseAsyncCreateCmd implements Sta public List getSourceCidrList() { return null; } - + @Override public Long getRelated() { return null; } - @Override - public FirewallRuleType getType() { - return FirewallRuleType.User; - } - - @Override + @Override + public FirewallRuleType getType() { + return FirewallRuleType.User; + } + + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java index 475e09a017b..6300a412d54 100644 --- a/api/src/com/cloud/api/commands/DeleteIpForwardingRuleCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DeleteIpForwardingRuleCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes an ip forwarding rule", responseObject=SuccessResponse.class) +@APICommand(name = "deleteIpForwardingRule", description="Deletes an ip forwarding rule", responseObject=SuccessResponse.class) public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteIpForwardingRuleCmd.class.getName()); @@ -42,14 +43,13 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the id of the forwarding rule") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the id of the forwarding rule") private Long id; - // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -71,8 +71,8 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Rule Id: "+id); - boolean result = _firewallService.revokeRelatedFirewallRule(id, true); - result = result && _rulesService.revokeStaticNatRule(id, true); + boolean result = _firewallService.revokeRelatedFirewallRule(id, true); + result = result && _rulesService.revokeStaticNatRule(id, true); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); @@ -104,7 +104,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting an ipforwarding 1:1 NAT rule id:"+id); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -114,7 +114,7 @@ public class DeleteIpForwardingRuleCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _rulesService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DisableStaticNatCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java index 5983264d4c3..fbd0b5ce900 100644 --- a/api/src/com/cloud/api/commands/DisableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/DisableStaticNatCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; +import org.apache.cloudstack.api.command.user.firewall.DeletePortForwardingRuleCmd; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +34,7 @@ import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; -@Implementation(description="Disables static rule for given ip address", responseObject=SuccessResponse.class) +@APICommand(name = "disableStaticNat", description="Disables static rule for given ip address", responseObject=SuccessResponse.class) public class DisableStaticNatCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeletePortForwardingRuleCmd.class.getName()); private static final String s_name = "disablestaticnatresponse"; @@ -42,10 +43,10 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP address id for which static nat feature is being disableed") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP address id for which static nat feature is being disableed") private Long ipAddressId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -53,7 +54,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public Long getIpAddress() { return ipAddressId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -61,7 +62,7 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_DISABLE_STATIC_NAT; @@ -71,16 +72,16 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Disabling static nat for ip id=" + ipAddressId); } - + @Override public long getEntityOwnerId() { return _entityMgr.findById(IpAddress.class, ipAddressId).getAccountId(); } - + @Override public void execute() throws ResourceUnavailableException, NetworkRuleConflictException, InsufficientAddressCapacityException { boolean result = _rulesService.disableStaticNat(ipAddressId); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -88,8 +89,8 @@ public class DisableStaticNatCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to disable static nat"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; diff --git a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/EnableStaticNatCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java index 9e21b8378ff..79a8e2bc9ff 100644 --- a/api/src/com/cloud/api/commands/EnableStaticNatCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/EnableStaticNatCmd.java @@ -14,17 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; @@ -32,7 +34,7 @@ import com.cloud.network.IpAddress; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(description="Enables static nat for given ip address", responseObject=SuccessResponse.class) +@APICommand(name = "enableStaticNat", description="Enables static nat for given ip address", responseObject=SuccessResponse.class) public class EnableStaticNatCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(CreateIpForwardingRuleCmd.class.getName()); @@ -42,20 +44,19 @@ public class EnableStaticNatCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, required=true, description="the public IP " + - "address id for which static nat feature is being enabled") + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + required=true, description="the public IP " + + "address id for which static nat feature is being enabled") private Long ipAddressId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description="the ID of " + - "the virtual machine for enabling static nat feature") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of " + + "the virtual machine for enabling static nat feature") private Long virtualMachineId; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, description="The network of the vm the static nat will be enabled for." + - " Required when public Ip address is not associated with any Guest network yet (VPC case)") + " Required when public Ip address is not associated with any Guest network yet (VPC case)") private Long networkId; ///////////////////////////////////////////////////// @@ -69,18 +70,18 @@ public class EnableStaticNatCmd extends BaseCmd{ public Long getVirtualMachineId() { return virtualMachineId; } - + public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } else { ntwkId = networkId; } if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + + throw new InvalidParameterValueException("Unable to enable static nat for the ipAddress id=" + ipAddressId + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; @@ -94,7 +95,7 @@ public class EnableStaticNatCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId()); @@ -106,7 +107,7 @@ public class EnableStaticNatCmd extends BaseCmd{ } @Override - public void execute() throws ResourceUnavailableException{ + public void execute() throws ResourceUnavailableException{ try { boolean result = _rulesService.enableStaticNat(ipAddressId, virtualMachineId, getNetworkId(), false); if (result) { diff --git a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java b/api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java index f385fe04c79..e4aaff3e56f 100644 --- a/api/src/com/cloud/api/commands/ListIpForwardingRulesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/nat/ListIpForwardingRulesCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.nat; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.StaticNatRule; +import com.cloud.utils.Pair; -@Implementation(description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class) +@APICommand(name = "listIpForwardingRules", description="List the ip forwarding rules", responseObject=FirewallRuleResponse.class) public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListIpForwardingRulesCmd.class.getName()); @@ -42,17 +43,17 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.LONG, description="list the rule belonging to this public ip address") + + @Parameter(name=ApiConstants.IP_ADDRESS_ID, type=CommandType.UUID, entityType = IPAddressResponse.class, + description="list the rule belonging to this public ip address") private Long publicIpAddressId; - - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists rule with the specified ID.") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists rule with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="Lists all rules applied to the specified Vm.") + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="Lists all rules applied to the specified Vm.") private Long vmId; ///////////////////////////////////////////////////// @@ -64,15 +65,15 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - - public Long getPublicIpAddressId() { - return publicIpAddressId; - } - public Long getId() { + public Long getPublicIpAddressId() { + return publicIpAddressId; + } + + public Long getId() { return id; } @@ -82,19 +83,20 @@ public class ListIpForwardingRulesCmd extends BaseListProjectAndAccountResources @Override public void execute(){ - List result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(), this.getProjectId(), this.isRecursive(), this.listAll()); + Pair, Integer> result = _rulesService.searchStaticNatRules(publicIpAddressId, id, vmId, + this.getStartIndex(), this.getPageSizeVal(), this.getAccountName(), this.getDomainId(), this.getProjectId(), this.isRecursive(), this.listAll()); ListResponse response = new ListResponse(); List ipForwardingResponses = new ArrayList(); - for (FirewallRule rule : result) { + for (FirewallRule rule : result.first()) { StaticNatRule staticNatRule = _rulesService.buildStaticNatRule(rule, false); IpForwardingRuleResponse resp = _responseGenerator.createIpForwardingRuleResponse(staticNatRule); if (resp != null) { ipForwardingResponses.add(resp); } } - response.setResponses(ipForwardingResponses); + response.setResponses(ipForwardingResponses, result.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + } diff --git a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/CreateNetworkACLCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java index 033a496d35d..e2aba5b321e 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkACLCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkACLResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -42,7 +42,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.net.NetUtils; -@Implementation(description = "Creates a ACL rule the given network (the network has to belong to VPC)", +@APICommand(name = "createNetworkACL", description = "Creates a ACL rule the given network (the network has to belong to VPC)", responseObject = NetworkACLResponse.class) public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallRule { public static final Logger s_logger = Logger.getLogger(CreateNetworkACLCmd.class.getName()); @@ -53,7 +53,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = + @Parameter(name = ApiConstants.PROTOCOL, type = CommandType.STRING, required = true, description = "the protocol for the ACL rule. Valid values are TCP/UDP/ICMP.") private String protocol; @@ -62,30 +62,30 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR @Parameter(name = ApiConstants.END_PORT, type = CommandType.INTEGER, description = "the ending port of ACL") private Integer publicEndPort; - - @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, + + @Parameter(name = ApiConstants.CIDR_LIST, type = CommandType.LIST, collectionType = CommandType.STRING, description = "the cidr list to allow traffic from/to") private List cidrlist; - + @Parameter(name = ApiConstants.ICMP_TYPE, type = CommandType.INTEGER, description = "type of the icmp message being sent") private Integer icmpType; @Parameter(name = ApiConstants.ICMP_CODE, type = CommandType.INTEGER, description = "error code for this icmp message") private Integer icmpCode; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, required=true, + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="The network of the vm the ACL will be created for") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="the traffic type for the ACL," + - "can be Ingress or Egress, defaulted to Ingress if not specified") + "can be Ingress or Egress, defaulted to Ingress if not specified") private String trafficType; - + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + public String getEntityTable() { return "firewall_rules"; } @@ -108,21 +108,21 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return oneCidrList; } } - + public long getVpcId() { Network network = _networkService.getNetwork(getNetworkId()); if (network == null) { throw new InvalidParameterValueException("Invalid networkId is given"); } - + Long vpcId = network.getVpcId(); if (vpcId == null) { throw new InvalidParameterValueException("Can create network ACL only for the network belonging to the VPC"); } - + return vpcId; } - + @Override public FirewallRule.TrafficType getTrafficType() { if (trafficType == null) { @@ -144,7 +144,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public String getCommandName() { return s_name; } - + public void setSourceCidrList(List cidrs){ cidrlist = cidrs; } @@ -159,7 +159,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR success = _networkACLService.applyNetworkACLs(rule.getNetworkId(), callerContext.getCaller()); // State is different after the rule is applied, so get new object here - NetworkACLResponse aclResponse = new NetworkACLResponse(); + NetworkACLResponse aclResponse = new NetworkACLResponse(); if (rule != null) { aclResponse = _responseGenerator.createNetworkACLResponse(rule); setResponseObject(aclResponse); @@ -184,6 +184,13 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR return null; } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + @Override public Long getSourceIpAddressId() { return null; @@ -206,7 +213,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } else { return publicEndPort.intValue(); } - + return null; } @@ -247,7 +254,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR if (getSourceCidrList() != null) { for (String cidr: getSourceCidrList()){ if (!NetUtils.isValidCIDR(cidr)){ - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Source cidrs formatting error " + cidr); } } } @@ -288,7 +295,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public Long getSyncObjId() { return getNetworkId(); } - + @Override public Integer getIcmpCode() { if (icmpCode != null) { @@ -298,14 +305,14 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR } return null; } - + @Override public Integer getIcmpType() { if (icmpType != null) { return icmpType; } else if (protocol.equalsIgnoreCase(NetUtils.ICMP_PROTO)) { return -1; - + } return null; } @@ -319,7 +326,7 @@ public class CreateNetworkACLCmd extends BaseAsyncCreateCmd implements FirewallR public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/CreateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/CreateNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java index a53635722ef..3b2608729a4 100644 --- a/api/src/com/cloud/api/commands/CreateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/CreateNetworkCmd.java @@ -14,17 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -34,7 +39,7 @@ import com.cloud.network.Network.GuestType; import com.cloud.offering.NetworkOffering; import com.cloud.user.UserContext; -@Implementation(description="Creates a network", responseObject=NetworkResponse.class) +@APICommand(name = "createNetwork", description="Creates a network", responseObject=NetworkResponse.class) public class CreateNetworkCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateNetworkCmd.class.getName()); @@ -43,68 +48,68 @@ public class CreateNetworkCmd extends BaseCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of the network") private String displayText; - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, required=true, description="the network offering id") + + @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + required=true, description="the network offering id") private Long networkOfferingId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the Zone ID for the network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the Zone ID for the network") private Long zoneId; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID the network belongs to") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID the network belongs to") private Long physicalNetworkId; @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, description="the gateway of the network. Required " + - "for Shared networks and Isolated networks when it belongs to VPC") + "for Shared networks and Isolated networks when it belongs to VPC") private String gateway; - + @Parameter(name=ApiConstants.NETMASK, type=CommandType.STRING, description="the netmask of the network. Required " + "for Shared networks and Isolated networks when it belongs to VPC") private String netmask; - + @Parameter(name=ApiConstants.START_IP, type=CommandType.STRING, description="the beginning IP address in the network IP range") private String startIp; - + @Parameter(name=ApiConstants.END_IP, type=CommandType.STRING, description="the ending IP address in the network IP" + - " range. If not specified, will be defaulted to startIP") + " range. If not specified, will be defaulted to startIP") private String endIp; @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="the ID or VID of the network") private String vlan; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="Access control type; supported values" + - " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + - " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") + " are account and domain. In 3.0 all shared networks should have aclType=Domain, and all Isolated networks" + + " - Account. Account means that only the account owner can use the network, domain - all accouns in the domain can use the network") private String aclType; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="account who will own the network") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="domain ID of the account owning a network") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="domain ID of the account owning a network") private Long domainId; - + @Parameter(name=ApiConstants.SUBDOMAIN_ACCESS, type=CommandType.BOOLEAN, description="Defines whether to allow" + - " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") + " subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified") private Boolean subdomainAccess; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="the VPC network belongs to") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="the VPC network belongs to") private Long vpcId; @@ -130,7 +135,7 @@ public class CreateNetworkCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public String getNetmask() { return netmask; } @@ -142,11 +147,11 @@ public class CreateNetworkCmd extends BaseCmd { public String getEndIp() { return endIp; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } @@ -154,39 +159,39 @@ public class CreateNetworkCmd extends BaseCmd { public String getNetworkDomain() { return networkDomain; } - + public Long getProjectId() { return projectId; } public String getAclType() { - return aclType; - } + return aclType; + } - public Boolean getSubdomainAccess() { - return subdomainAccess; - } + public Boolean getSubdomainAccess() { + return subdomainAccess; + } - public Long getVpcId() { + public Long getVpcId() { return vpcId; } public Long getZoneId() { Long physicalNetworkId = getPhysicalNetworkId(); - + if (physicalNetworkId == null && zoneId == null) { throw new InvalidParameterValueException("Zone id is required"); } - + return zoneId; } - + public Long getPhysicalNetworkId() { NetworkOffering offering = _configService.getNetworkOffering(networkOfferingId); if (offering == null) { throw new InvalidParameterValueException("Unable to find network offering by id " + networkOfferingId); } - + if (physicalNetworkId != null) { if (offering.getGuestType() == GuestType.Shared) { return physicalNetworkId; @@ -208,19 +213,19 @@ public class CreateNetworkCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override - // an exception thrown by createNetwork() will be caught by the dispatcher. + // an exception thrown by createNetwork() will be caught by the dispatcher. public void execute() throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException{ Network result = _networkService.createGuestNetwork(this); if (result != null) { diff --git a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java index 0499f531c11..4b078ed7fe3 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkACLCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkACLCmd.java @@ -14,18 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +34,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.rules.FirewallRule; import com.cloud.user.UserContext; -@Implementation(description="Deletes a Network ACL", responseObject=SuccessResponse.class) +@APICommand(name = "deleteNetworkACL", description="Deletes a Network ACL", responseObject=SuccessResponse.class) public class DeleteNetworkACLCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetworkACLCmd.class.getName()); private static final String s_name = "deletenetworkaclresponse"; @@ -42,13 +43,13 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network ACL") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + required=true, description="the ID of the network ACL") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +58,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +66,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_FIREWALL_CLOSE; @@ -75,7 +76,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public String getEventDescription() { return ("Deleting Network ACL id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +89,12 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Network ACL Id: " + id); boolean result = _networkACLService.revokeNetworkACL(id, true); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +102,8 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network ACL"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -112,7 +113,7 @@ public class DeleteNetworkACLCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _firewallService.getFirewallRule(id).getNetworkId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.FirewallRule; diff --git a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/DeleteNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java index 5e1350ff15b..df070ff8ecb 100644 --- a/api/src/com/cloud/api/commands/DeleteNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/DeleteNetworkCmd.java @@ -14,24 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.response.NetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.Network; import com.cloud.user.UserContext; -@Implementation(description="Deletes a network", responseObject=SuccessResponse.class) +@APICommand(name = "deleteNetwork", description="Deletes a network", responseObject=SuccessResponse.class) public class DeleteNetworkCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteNetworkOfferingCmd.class.getName()); private static final String s_name = "deletenetworkresponse"; @@ -40,8 +37,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="the ID of the network") private Long id; @@ -62,7 +59,7 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public void execute(){ UserContext.current().setEventDetails("Network Id: " + id); @@ -74,8 +71,8 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -85,17 +82,17 @@ public class DeleteNetworkCmd extends BaseAsyncCmd{ public Long getSyncObjId() { return id; } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_DELETE; } - + @Override public String getEventDescription() { return "Deleting network: " + id; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); diff --git a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java similarity index 67% rename from api/src/com/cloud/api/commands/ListNetworkACLsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java index 3529558de71..f556ce1cbfd 100644 --- a/api/src/com/cloud/api/commands/ListNetworkACLsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkACLsCmd.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.network.rules.FirewallRule; +import com.cloud.utils.Pair; -@Implementation(description="Lists all network ACLs", responseObject=NetworkACLResponse.class) +@APICommand(name = "listNetworkACLs", description="Lists all network ACLs", responseObject=NetworkACLResponse.class) public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkACLsCmd.class.getName()); @@ -41,29 +41,29 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="firewall_rules") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="Lists network ACL with the specified ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = FirewallRuleResponse.class, + description="Lists network ACL with the specified ID.") private Long id; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list network ACLs by network Id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="list network ACLs by network Id") private Long networkId; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="list network ACLs by traffic type - Ingress or Egress") private String trafficType; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { return networkId; } - + public Long getId() { return id; } - + public String getTrafficType() { return trafficType; } @@ -76,19 +76,19 @@ public class ListNetworkACLsCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _networkACLService.listNetworkACLs(this); + Pair,Integer> result = _networkACLService.listNetworkACLs(this); ListResponse response = new ListResponse(); List aclResponses = new ArrayList(); - - for (FirewallRule acl : result) { + + for (FirewallRule acl : result.first()) { NetworkACLResponse ruleData = _responseGenerator.createNetworkACLResponse(acl); aclResponses.add(ruleData); } - response.setResponses(aclResponses); + response.setResponses(aclResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java index 70dd1be2e74..94bc71dc993 100644 --- a/api/src/com/cloud/api/commands/ListNetworkOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworkOfferingsCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.offering.NetworkOffering; - -@Implementation(description="Lists all available network offerings.", responseObject=NetworkOfferingResponse.class) +@APICommand(name = "listNetworkOfferings", description="Lists all available network offerings.", responseObject=NetworkOfferingResponse.class) public class ListNetworkOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetworkOfferingsCmd.class.getName()); private static final String _name = "listnetworkofferingsresponse"; @@ -39,73 +39,73 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list network offerings by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + description="list network offerings by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list network offerings by name") private String networkOfferingName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list network offerings by display text") private String displayText; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="list by traffic type") private String trafficType; - + @Parameter(name=ApiConstants.IS_DEFAULT, type=CommandType.BOOLEAN, description="true if need to list only default network offerings. Default value is false") - private Boolean isDefault; - + private Boolean isDefault; + @Parameter(name=ApiConstants.SPECIFY_VLAN, type=CommandType.BOOLEAN, description="the tags for the network offering.") private Boolean specifyVlan; - + @Parameter(name=ApiConstants.AVAILABILITY, type=CommandType.STRING, description="the availability of network offering. Default value is Required") private String availability; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list netowrk offerings available for network creation in specific zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="list netowrk offerings available for network creation in specific zone") private Long zoneId; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list network offerings by state") private String state; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to.") private Long networkId; - + @Parameter(name=ApiConstants.GUEST_IP_TYPE, type=CommandType.STRING, description="list network offerings by guest type: Shared or Isolated") private String guestIpType; @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list network offerings supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.SOURCE_NAT_SUPPORTED, type=CommandType.BOOLEAN, description="true if need to list only netwok offerings where source nat is supported, false otherwise") private Boolean sourceNatSupported; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if need to list only network offerings which support specifying ip ranges") private Boolean specifyIpRanges; - + @Parameter(name=ApiConstants.TAGS, type=CommandType.STRING, description="list network offerings by tags", length=4096) private String tags; - + @Parameter(name=ApiConstants.IS_TAGGED, type=CommandType.BOOLEAN, description="true if offering has tags specified") private Boolean isTagged; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="the network offering can be used" + - " only for network creation inside the VPC") + " only for network creation inside the VPC") private Boolean forVpc; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getNetworkOfferingName() { return networkOfferingName; } - + public String getDisplayText() { return displayText; } - + public String getTrafficType() { return trafficType; } @@ -117,7 +117,7 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { public Boolean getIsDefault() { return isDefault; } - + public Boolean getSpecifyVlan() { return specifyVlan; } @@ -147,14 +147,14 @@ public class ListNetworkOfferingsCmd extends BaseListCmd { } public Boolean getSourceNatSupported() { - return sourceNatSupported; - } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges; + return sourceNatSupported; } - public String getTags() { + public Boolean getSpecifyIpRanges() { + return specifyIpRanges; + } + + public String getTags() { return tags; } diff --git a/api/src/com/cloud/api/commands/ListNetworksCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListNetworksCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java index 61aff018edf..1f366c223a6 100644 --- a/api/src/com/cloud/api/commands/ListNetworksCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/ListNetworksCmd.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.network.Network; - -@Implementation(description="Lists all available networks.", responseObject=NetworkResponse.class) +@APICommand(name = "listNetworks", description="Lists all available networks.", responseObject=NetworkResponse.class) public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListNetworksCmd.class.getName()); private static final String _name = "listnetworksresponse"; @@ -39,50 +40,50 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list networks by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + description="list networks by id") private Long id; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the Zone ID of the network") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the Zone ID of the network") private Long zoneId; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the type of the network. Supported values are: Isolated and Shared") private String guestIpType; - + @Parameter(name=ApiConstants.IS_SYSTEM, type=CommandType.BOOLEAN, description="true if network is system, false otherwise") private Boolean isSystem; - + @Parameter(name=ApiConstants.ACL_TYPE, type=CommandType.STRING, description="list networks by ACL (access control list) type. Supported values are Account and Domain") private String aclType; - + @Parameter(name=ApiConstants.TRAFFIC_TYPE, type=CommandType.STRING, description="type of the traffic") private String trafficType; - - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="list networks by physical network id") + + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="list networks by physical network id") private Long physicalNetworkId; - + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list networks supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.RESTART_REQUIRED, type=CommandType.BOOLEAN, description="list networks by restartRequired") - + private Boolean restartRequired; - + @Parameter(name=ApiConstants.SPECIFY_IP_RANGES, type=CommandType.BOOLEAN, description="true if need to list only networks which support specifying ip ranges") private Boolean specifyIpRanges; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="List networks by VPC") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType = VpcResponse.class, + description="List networks by VPC") private Long vpcId; @Parameter(name=ApiConstants.CAN_USE_FOR_DEPLOY, type=CommandType.BOOLEAN, description="list networks available for vm deployment") private Boolean canUseForDeploy; - + @Parameter(name=ApiConstants.FOR_VPC, type=CommandType.BOOLEAN, description="the network belongs to vpc") private Boolean forVpc; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -90,7 +91,7 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public Long getId() { return id; } - + public Long getZoneId() { return zoneId; } @@ -102,10 +103,10 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { public Boolean getIsSystem() { return isSystem; } - + public String getAclType() { - return aclType; - } + return aclType; + } public String getTrafficType() { return trafficType; @@ -120,21 +121,21 @@ public class ListNetworksCmd extends BaseListTaggedResourcesCmd { } public Boolean getRestartRequired() { - return restartRequired; - } - - public Boolean getSpecifyIpRanges() { - return specifyIpRanges; + return restartRequired; } - public Long getVpcId() { + public Boolean getSpecifyIpRanges() { + return specifyIpRanges; + } + + public Long getVpcId() { return vpcId; - } - - public Boolean canUseForDeploy() { + } + + public Boolean canUseForDeploy() { return canUseForDeploy; } - + public Boolean getForVpc() { return forVpc; } diff --git a/api/src/com/cloud/api/commands/RestartNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/RestartNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java index 0141d24f438..ee9af3b0009 100644 --- a/api/src/com/cloud/api/commands/RestartNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/RestartNetworkCmd.java @@ -14,19 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -35,7 +31,7 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; -@Implementation(description="Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules", responseObject=IPAddressResponse.class) +@APICommand(name = "restartNetwork", description="Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules", responseObject=IPAddressResponse.class) public class RestartNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RestartNetworkCmd.class.getName()); private static final String s_name = "restartnetworkresponse"; @@ -44,9 +40,8 @@ public class RestartNetworkCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The id of the network to restart.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="The id of the network to restart.") private Long id; @Parameter(name=ApiConstants.CLEANUP, type=CommandType.BOOLEAN, required=false, description="If cleanup old network elements") @@ -56,7 +51,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getNetworkId() { Network network = _networkService.getNetwork(id); if (network == null) { @@ -65,7 +60,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { return network.getId(); } } - + public Boolean getCleanup() { if (cleanup != null) { return cleanup; @@ -87,7 +82,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public static String getResultObjectName() { return "addressinfo"; } - + @Override public void execute() throws ResourceUnavailableException, ResourceAllocationException, ConcurrentOperationException, InsufficientCapacityException { boolean result = _networkService.restartNetwork(this, getCleanup()); @@ -98,7 +93,7 @@ public class RestartNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart network"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -108,16 +103,16 @@ public class RestartNetworkCmd extends BaseAsyncCmd { public Long getSyncObjId() { return id; } - + public String getEventDescription() { return "Restarting network: " + getNetworkId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_RESTART; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); diff --git a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/UpdateNetworkCmd.java rename to api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java index 15d8451a81b..5ab8a6035ad 100644 --- a/api/src/com/cloud/api/commands/UpdateNetworkCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/network/UpdateNetworkCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.network; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -35,7 +35,7 @@ import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserContext; -@Implementation(description="Updates a network", responseObject=NetworkResponse.class) +@APICommand(name = "updateNetwork", description="Updates a network", responseObject=NetworkResponse.class) public class UpdateNetworkCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateNetworkCmd.class.getName()); @@ -44,46 +44,46 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the network") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = NetworkResponse.class, + required=true, description="the ID of the network") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the new name for the network") private String name; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the new display text for the network") private String displayText; - + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="network domain") private String networkDomain; - + @Parameter(name=ApiConstants.CHANGE_CIDR, type=CommandType.BOOLEAN, description="Force update even if cidr type is different") private Boolean changeCidr; - - @IdentityMapper(entityTableName="network_offerings") - @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.LONG, description="network offering ID") + + @Parameter(name=ApiConstants.NETWORK_OFFERING_ID, type=CommandType.UUID, entityType = NetworkOfferingResponse.class, + description="network offering ID") private Long networkOfferingId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + public String getNetworkName() { return name; } - + public String getDisplayText() { return displayText; } - + private String getNetworkDomain() { return networkDomain; } - + private Long getNetworkOfferingId() { return networkOfferingId; } @@ -102,7 +102,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Network network = _networkService.getNetwork(id); @@ -112,7 +112,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { return _networkService.getNetwork(id).getAccountId(); } } - + @Override public void execute() throws InsufficientCapacityException, ConcurrentOperationException{ User callerUser = _accountService.getActiveUser(UserContext.current().getCallerUserId()); @@ -121,7 +121,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { if (network == null) { throw new InvalidParameterValueException("Couldn't find network by id"); } - + Network result = null; if (network.getVpcId() != null) { result = _vpcService.updateVpcGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, @@ -130,7 +130,7 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { result = _networkService.updateGuestNetwork(getId(), getNetworkName(), getDisplayText(), callerAccount, callerUser, getNetworkDomain(), getNetworkOfferingId(), getChangeCidr()); } - + if (result != null) { NetworkResponse response = _responseGenerator.createNetworkResponse(result); response.setResponseName(getCommandName()); @@ -139,12 +139,12 @@ public class UpdateNetworkCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update network"); } } - + @Override public String getEventDescription() { return "Updating network: " + getId(); } - + @Override public String getEventType() { return EventTypes.EVENT_NETWORK_UPDATE; diff --git a/api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java index fbf655d7e88..7209429cfa0 100644 --- a/api/src/com/cloud/api/commands/ListDiskOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListDiskOfferingsCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.offering; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.offering.DiskOffering; -@Implementation(description="Lists all available disk offerings.", responseObject=DiskOfferingResponse.class) +@APICommand(name = "listDiskOfferings", description="Lists all available disk offerings.", responseObject=DiskOfferingResponse.class) public class ListDiskOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListDiskOfferingsCmd.class.getName()); @@ -40,12 +40,12 @@ public class ListDiskOfferingsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain of the disk offering.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the ID of the domain of the disk offering.") private Long domainId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the disk offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = DiskOfferingResponse.class, + description="ID of the disk offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the disk offering") diff --git a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java index 39cc7c80948..9fad577d8ad 100644 --- a/api/src/com/cloud/api/commands/ListServiceOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/offering/ListServiceOfferingsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.offering; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.offering.ServiceOffering; -@Implementation(description="Lists all available service offerings.", responseObject=ServiceOfferingResponse.class) +@APICommand(name = "listServiceOfferings", description="Lists all available service offerings.", responseObject=ServiceOfferingResponse.class) public class ListServiceOfferingsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); @@ -40,19 +41,19 @@ public class ListServiceOfferingsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="ID of the service offering") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = ServiceOfferingResponse.class, + description="ID of the service offering") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the service offering") private String serviceOfferingName; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to.") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to.") private Long virtualMachineId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain associated with the service offering") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the ID of the domain associated with the service offering") private Long domainId; @Parameter(name=ApiConstants.IS_SYSTEM_OFFERING, type=CommandType.BOOLEAN, description="is this a system vm offering") @@ -61,7 +62,7 @@ public class ListServiceOfferingsCmd extends BaseListCmd { @Parameter(name=ApiConstants.SYSTEM_VM_TYPE, type=CommandType.STRING, description="the system VM type. Possible types are \"consoleproxy\", \"secondarystoragevm\" or \"domainrouter\".") private String systemVmType; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -79,13 +80,13 @@ public class ListServiceOfferingsCmd extends BaseListCmd { } public Long getDomainId(){ - return domainId; + return domainId; } - + public Boolean getIsSystem() { return isSystem == null ? false : isSystem; } - + public String getSystemVmType(){ return systemVmType; } @@ -98,7 +99,7 @@ public class ListServiceOfferingsCmd extends BaseListCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ List offerings = _mgr.searchForServiceOfferings(this); diff --git a/api/src/com/cloud/api/commands/ActivateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java similarity index 75% rename from api/src/com/cloud/api/commands/ActivateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java index 20b5507734f..6cc9387ac2b 100644 --- a/api/src/com/cloud/api/commands/ActivateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ActivateProjectCmd.java @@ -14,25 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Activates a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "activateProject", description="Activates a project", responseObject=ProjectResponse.class, since="3.0.0") public class ActivateProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ActivateProjectCmd.class.getName()); @@ -41,9 +35,9 @@ public class ActivateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be modified") private Long id; ///////////////////////////////////////////////////// @@ -58,18 +52,19 @@ public class ActivateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + + @Override public long getEntityOwnerId() { - Project project= _projectService.getProject(id); + Project project= _projectService.getProject(getId()); //verify input parameters if (project == null) { - throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + throw new InvalidParameterValueException("Unable to find project by id " + getId()); + } + + return _projectService.getProjectOwner(getId()).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -78,7 +73,7 @@ public class ActivateProjectCmd extends BaseAsyncCmd { @Override public void execute(){ UserContext.current().setEventDetails("Project id: "+ getId()); - Project project = _projectService.activateProject(id); + Project project = _projectService.activateProject(getId()); if (project != null) { ProjectResponse response = _responseGenerator.createProjectResponse(project); response.setResponseName(getCommandName()); @@ -87,14 +82,14 @@ public class ActivateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to activate a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_ACTIVATE; } - + @Override public String getEventDescription() { return "Activating project: " + id; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/CreateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java similarity index 89% rename from api/src/com/cloud/api/commands/CreateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java index 12d1a2c6ea9..9500a972b36 100644 --- a/api/src/com/cloud/api/commands/CreateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/CreateProjectCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +29,7 @@ import com.cloud.projects.Project; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0") +@APICommand(name = "createProject", description = "Creates a project", responseObject = ProjectResponse.class, since = "3.0.0") public class CreateProjectCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateProjectCmd.class.getName()); @@ -46,8 +42,8 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account who will be Admin for the project") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "domain ID of the account owning a project") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "domain ID of the account owning a project") private Long domainId; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the project") @@ -146,4 +142,4 @@ public class CreateProjectCmd extends BaseAsyncCreateCmd { return "creating project"; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/DeleteProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/DeleteProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java index fb1b508826a..fb41a7f14ef 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Deletes a project", responseObject=SuccessResponse.class, since="3.0.0") +@APICommand(name = "deleteProject", description="Deletes a project", responseObject=SuccessResponse.class, since="3.0.0") public class DeleteProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectCmd.class.getName()); @@ -41,8 +41,8 @@ public class DeleteProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be deleted") private Long id; ///////////////////////////////////////////////////// @@ -74,26 +74,26 @@ public class DeleteProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_DELETE; } - + @Override public String getEventDescription() { return "Deleting project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java index a13bbda8cf0..67c7cefc252 100644 --- a/api/src/com/cloud/api/commands/DeleteProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/DeleteProjectInvitationCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") +@APICommand(name = "deleteProjectInvitation", description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class DeleteProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteProjectInvitationCmd.class.getName()); private static final String s_name = "deleteprojectinvitationresponse"; @@ -38,8 +38,8 @@ public class DeleteProjectInvitationCmd extends BaseAsyncCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "project_invitations") - @Parameter(name = ApiConstants.ID, required = true, type = CommandType.LONG, description = "id of the invitation") + @Parameter(name = ApiConstants.ID, type=CommandType.UUID, entityType=ProjectInvitationResponse.class, + required = true, description = "id of the invitation") private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java similarity index 61% rename from api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java index cb707805cde..4157daa7b4a 100644 --- a/api/src/com/cloud/api/commands/ListProjectInvitationsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectInvitationsCmd.java @@ -14,23 +14,19 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.projects.ProjectInvitation; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; -@Implementation(description = "Lists projects and provides detailed information for listed projects", responseObject = ProjectInvitationResponse.class, since = "3.0.0") +@APICommand(name = "listProjectInvitations", description = "Lists projects and provides detailed information for listed projects", responseObject = ProjectInvitationResponse.class, since = "3.0.0") public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListProjectInvitationsCmd.class.getName()); private static final String s_name = "listprojectinvitationsresponse"; @@ -38,8 +34,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "list by project id") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + description = "list by project id") private Long projectId; @Parameter(name = ApiConstants.ACTIVE_ONLY, type = CommandType.BOOLEAN, description = "if true, list only active invitations - having Pending state and ones that are not timed out yet") @@ -48,8 +44,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { @Parameter(name = ApiConstants.STATE, type = CommandType.STRING, description = "list invitations by state") private String state; - @IdentityMapper(entityTableName = "project_invitations") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, description = "list invitations by id") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=ProjectInvitationResponse.class, + description = "list invitations by id") private Long id; // /////////////////////////////////////////////////// @@ -82,17 +78,8 @@ public class ListProjectInvitationsCmd extends BaseListAccountResourcesCmd { @Override public void execute() { - List invites = _projectService.listProjectInvitations(id, projectId, this.getAccountName(), this.getDomainId(), state, activeOnly, this.getStartIndex(), this.getPageSizeVal(), - this.isRecursive(), this.listAll()); - ListResponse response = new ListResponse(); - List projectInvitationResponses = new ArrayList(); - for (ProjectInvitation invite : invites) { - ProjectInvitationResponse projectResponse = _responseGenerator.createProjectInvitationResponse(invite); - projectInvitationResponses.add(projectResponse); - } - response.setResponses(projectInvitationResponses); + ListResponse response = _queryService.listProjectInvitations(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListProjectsCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListProjectsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java index 187e52cfce1..321a19fe62d 100644 --- a/api/src/com/cloud/api/commands/ListProjectsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/ListProjectsCmd.java @@ -14,28 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; -import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.projects.Project; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectResponse; -@Implementation(description="Lists projects and provides detailed information for listed projects", responseObject=ProjectResponse.class, since="3.0.0") +import com.cloud.exception.InvalidParameterValueException; + +@APICommand(name = "listProjects", description="Lists projects and provides detailed information for listed projects", responseObject=ProjectResponse.class, since="3.0.0") public class ListProjectsCmd extends BaseListAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListProjectsCmd.class.getName()); private static final String s_name = "listprojectsresponse"; @@ -43,9 +40,9 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list projects by project ID") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="list projects by project ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list projects by name") @@ -53,13 +50,13 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list projects by display text") private String displayText; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list projects by state") private String state; - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "List projects by tags (key/value pairs)") private Map tags; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -75,12 +72,17 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { public String getDisplayText() { return displayText; } - + + + public String getState() { + return state; + } + @Override public String getCommandName() { return s_name; } - + public Map getTags() { Map tagsMap = null; if (tags != null && !tags.isEmpty()) { @@ -106,18 +108,8 @@ public class ListProjectsCmd extends BaseListAccountResourcesCmd { @Override public void execute(){ - List projects = _projectService.listProjects(id, name, displayText, state, - this.getAccountName(), this.getDomainId(), this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), - this.listAll(), this.isRecursive(), getTags()); - ListResponse response = new ListResponse(); - List projectResponses = new ArrayList(); - for (Project project : projects) { - ProjectResponse projectResponse = _responseGenerator.createProjectResponse(project); - projectResponses.add(projectResponse); - } - response.setResponses(projectResponses); + ListResponse response = _queryService.listProjects(this); response.setResponseName(getCommandName()); - this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/SuspendProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/SuspendProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java index 62f6da68cbc..120e4fe0c55 100644 --- a/api/src/com/cloud/api/commands/SuspendProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/SuspendProjectCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +28,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Suspends a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "suspendProject", description="Suspends a project", responseObject=ProjectResponse.class, since="3.0.0") public class SuspendProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(SuspendProjectCmd.class.getName()); @@ -43,8 +38,8 @@ public class SuspendProjectCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be suspended") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be suspended") private Long id; ///////////////////////////////////////////////////// @@ -77,26 +72,26 @@ public class SuspendProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to suspend a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_SUSPEND; } - + @Override public String getEventDescription() { return "Suspending project: " + id; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - -} \ No newline at end of file + +} diff --git a/api/src/com/cloud/api/commands/UpdateProjectCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/UpdateProjectCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java index 0c90e165d6a..bad117727e0 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectCmd.java @@ -14,25 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ProjectResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ProjectResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.projects.Project; import com.cloud.user.UserContext; -@Implementation(description="Updates a project", responseObject=ProjectResponse.class, since="3.0.0") +@APICommand(name = "updateProject", description="Updates a project", responseObject=ProjectResponse.class, since="3.0.0") public class UpdateProjectCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateProjectCmd.class.getName()); @@ -41,14 +40,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of the project to be modified") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ProjectResponse.class, + required=true, description="id of the project to be modified") private Long id; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="new Admin account for the project") private String accountName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="display text of the project") private String displayText; @@ -72,18 +71,18 @@ public class UpdateProjectCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Project project= _projectService.getProject(id); //verify input parameters if (project == null) { throw new InvalidParameterValueException("Unable to find project by id " + id); - } - - return _projectService.getProjectOwner(id).getId(); + } + + return _projectService.getProjectOwner(id).getId(); } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -101,14 +100,14 @@ public class UpdateProjectCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to update a project"); } } - + @Override public String getEventType() { return EventTypes.EVENT_PROJECT_UPDATE; } - + @Override public String getEventDescription() { return "Updating project: " + id; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java rename to api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java index 20cb8c1cad3..32e1a755484 100644 --- a/api/src/com/cloud/api/commands/UpdateProjectInvitationCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/project/UpdateProjectInvitationCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.project; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") +@APICommand(name = "updateProjectInvitation", description = "Accepts or declines project invitation", responseObject = SuccessResponse.class, since = "3.0.0") public class UpdateProjectInvitationCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateProjectInvitationCmd.class.getName()); private static final String s_name = "updateprojectinvitationresponse"; @@ -38,8 +34,8 @@ public class UpdateProjectInvitationCmd extends BaseAsyncCmd { // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, required = true, type = CommandType.LONG, description = "id of the project to join") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, entityType = ProjectResponse.class, + required = true, description = "id of the project to join") private Long projectId; @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "account that is joining the project") diff --git a/api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java index e1f7cd3e217..0d62c18f55d 100644 --- a/api/src/com/cloud/api/commands/GetCloudIdentifierCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/GetCloudIdentifierCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.CloudIdentifierResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.CloudIdentifierResponse; +import org.apache.cloudstack.api.response.UserResponse; import com.cloud.user.Account; -@Implementation(description="Retrieves a cloud identifier.", responseObject=CloudIdentifierResponse.class) +@APICommand(name = "getCloudIdentifier", description="Retrieves a cloud identifier.", responseObject=CloudIdentifierResponse.class) public class GetCloudIdentifierCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetCloudIdentifierCmd.class.getName()); private static final String s_name = "getcloudidentifierresponse"; @@ -38,11 +38,10 @@ public class GetCloudIdentifierCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user") - @Parameter(name=ApiConstants.USER_ID, type=CommandType.LONG, required=true, description="the user ID for the cloud identifier") + @Parameter(name=ApiConstants.USER_ID, type=CommandType.UUID, entityType = UserResponse.class, + required=true, description="the user ID for the cloud identifier") private Long userid; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -51,7 +50,6 @@ public class GetCloudIdentifierCmd extends BaseCmd { return userid; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -59,12 +57,12 @@ public class GetCloudIdentifierCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; } - + @Override public void execute(){ ArrayList result = _mgr.getCloudIdentifierResponse(userid); @@ -78,6 +76,6 @@ public class GetCloudIdentifierCmd extends BaseCmd { } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to get cloud identifier"); } - + } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ListHypervisorsCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/ListHypervisorsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java index e058df68bc2..c1e29d3f37e 100644 --- a/api/src/com/cloud/api/commands/ListHypervisorsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/ListHypervisorsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.HypervisorResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.HypervisorResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.user.Account; -@Implementation(description = "List hypervisors", responseObject = HypervisorResponse.class) +@APICommand(name = "listHypervisors", description = "List hypervisors", responseObject = HypervisorResponse.class) public class ListHypervisorsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeRouterCmd.class.getName()); private static final String s_name = "listhypervisorsresponse"; @@ -44,8 +45,8 @@ public class ListHypervisorsCmd extends BaseCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.LONG, description = "the zone id for listing hypervisors.") + @Parameter(name = ApiConstants.ZONE_ID, type = CommandType.UUID, entityType = ZoneResponse.class, + description = "the zone id for listing hypervisors.") private Long zoneId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/ListResourceLimitsCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListResourceLimitsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java index 58d03b3c8dd..12a8494bde8 100644 --- a/api/src/com/cloud/api/commands/ListResourceLimitsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/ListResourceLimitsCmd.java @@ -14,22 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; import com.cloud.configuration.ResourceLimit; -@Implementation(description="Lists resource limits.", responseObject=ResourceLimitResponse.class) +@APICommand(name = "listResourceLimits", description="Lists resource limits.", responseObject=ResourceLimitResponse.class) public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListResourceLimitsCmd.class.getName()); @@ -43,12 +43,12 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd private Long id; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description="Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") - private Integer resourceType; - + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") + private Integer resourceType; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -64,12 +64,12 @@ public class ListResourceLimitsCmd extends BaseListProjectAndAccountResourcesCmd ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public void execute(){ List result = _resourceLimitService.searchForLimits(id, finalyzeAccountId(this.getAccountName(), this.getDomainId(), this.getProjectId(), false), this.getDomainId(), resourceType, this.getStartIndex(), this.getPageSizeVal()); diff --git a/api/src/com/cloud/api/commands/UpdateResourceCountCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/UpdateResourceCountCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java index 6a71a4c7231..d2b6870f0ca 100644 --- a/api/src/com/cloud/api/commands/UpdateResourceCountCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceCountCmd.java @@ -14,27 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; import com.cloud.configuration.ResourceCount; import com.cloud.user.Account; import com.cloud.user.UserContext; - -@Implementation(description="Recalculate and update resource count for an account or domain.", responseObject=ResourceCountResponse.class) +@APICommand(name = "updateResourceCount", description="Recalculate and update resource count for an account or domain.", responseObject=ResourceCountResponse.class) public class UpdateResourceCountCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateResourceCountCmd.class.getName()); @@ -48,20 +45,20 @@ public class UpdateResourceCountCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Update resource count for a specified account. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, required=true, description="If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + required=true, description="If account parameter specified then updates resource counts for a specified account in this domain else update resource counts for all accounts & child domains in specified domain.") private Long domainId; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, description= "Type of resource to update. If specifies valid values are 0, 1, 2, 3, and 4. If not specified will update all resource counts" + - "0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") + "0 - Instance. Number of instances a user can create. " + + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") private Integer resourceType; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Update resource limits for project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Update resource limits for project") private Long projectId; ///////////////////////////////////////////////////// @@ -83,12 +80,12 @@ public class UpdateResourceCountCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); @@ -110,7 +107,7 @@ public class UpdateResourceCountCmd extends BaseCmd { @Override public void execute(){ - List result = _resourceLimitService.recalculateResourceCount(finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType()); + List result = _resourceLimitService.recalculateResourceCount(finalyzeAccountId(accountName, domainId, projectId, true), getDomainId(), getResourceType()); if ((result != null) && (result.size()>0)){ ListResponse response = new ListResponse(); @@ -129,4 +126,4 @@ public class UpdateResourceCountCmd extends BaseCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to recalculate resource counts"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java similarity index 69% rename from api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java rename to api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java index 4c2801d4e5b..262d12dc264 100644 --- a/api/src/com/cloud/api/commands/UpdateResourceLimitCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/resource/UpdateResourceLimitCmd.java @@ -14,27 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.resource; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; import com.cloud.configuration.ResourceLimit; import com.cloud.user.UserContext; -@Implementation(description="Updates resource limits for an account or domain.", responseObject=ResourceLimitResponse.class) +@APICommand(name = "updateResourceLimit", description="Updates resource limits for an account or domain.", responseObject=ResourceLimitResponse.class) public class UpdateResourceLimitCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpdateResourceLimitCmd.class.getName()); private static final String s_name = "updateresourcelimitresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -42,28 +39,28 @@ public class UpdateResourceLimitCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="Update resource for a specified account. Must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="Update resource limits for all accounts in specified domain. If used with the account parameter, updates resource limits for a specified account in specified domain.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Update resource limits for project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Update resource limits for project") private Long projectId; - @Parameter(name=ApiConstants.MAX, type=CommandType.LONG, description=" Maximum resource limit.") + @Parameter(name=ApiConstants.MAX, type=CommandType.LONG, description=" Maximum resource limit.") private Long max; @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.INTEGER, required=true, description="Type of resource to update. Values are 0, 1, 2, 3, and 4. 0 - Instance. Number of instances a user can create. " + - "1 - IP. Number of public IP addresses a user can own. " + - "2 - Volume. Number of disk volumes a user can create." + - "3 - Snapshot. Number of snapshots a user can create." + - "4 - Template. Number of templates that a user can register/create.") + "1 - IP. Number of public IP addresses a user can own. " + + "2 - Volume. Number of disk volumes a user can create." + + "3 - Snapshot. Number of snapshots a user can create." + + "4 - Template. Number of templates that a user can register/create.") private Integer resourceType; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getMax() { return max; } @@ -79,19 +76,19 @@ public class UpdateResourceLimitCmd extends BaseCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java index a6088d0b959..acafcbe19a9 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupEgressCmd.java @@ -14,23 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; + +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupRuleResponse; -import com.cloud.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +36,7 @@ import com.cloud.network.security.SecurityRule; import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; -@Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular egress rule for this security group", since="3.0.0") +@APICommand(name = "authorizeSecurityGroupEgress", responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular egress rule for this security group", since="3.0.0") @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName()); @@ -69,22 +67,19 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="an optional project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") + + @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with securityGroupName parameter", entityType=SecurityGroupResponse.class) private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -116,7 +111,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (securityGroupId != null && securityGroupName != null) { throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { @@ -124,11 +119,11 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { } securityGroupName = null; } - + if (securityGroupId == null) { throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); } - + return securityGroupId; } @@ -166,7 +161,7 @@ public class AuthorizeSecurityGroupEgressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } diff --git a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java index e8f8b986b4b..abd20fcc81d 100644 --- a/api/src/com/cloud/api/commands/AuthorizeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/AuthorizeSecurityGroupIngressCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import java.util.Collection; import java.util.HashMap; @@ -24,15 +24,16 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +42,7 @@ import com.cloud.user.UserContext; import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; -@Implementation(responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular ingress rule for this security group") +@APICommand(name = "authorizeSecurityGroupIngress", responseObject = SecurityGroupRuleResponse.class, description = "Authorizes a particular ingress rule for this security group") @SuppressWarnings("rawtypes") public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AuthorizeSecurityGroupIngressCmd.class.getName()); @@ -72,22 +73,19 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Parameter(name = ApiConstants.USER_SECURITY_GROUP_LIST, type = CommandType.MAP, description = "user to security group mapping") private Map userSecurityGroupList; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the security group. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="an optional project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with securityGroupName parameter") + + @Parameter(name=ApiConstants.SECURITY_GROUP_ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with securityGroupName parameter", entityType=SecurityGroupResponse.class) private Long securityGroupId; - + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="The name of the security group. Mutually exclusive with securityGroupName parameter") private String securityGroupName; @@ -119,7 +117,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (securityGroupId != null && securityGroupName != null) { throw new InvalidParameterValueException("securityGroupId and securityGroupName parameters are mutually exclusive"); } - + if (securityGroupName != null) { securityGroupId = _responseGenerator.getSecurityGroupId(securityGroupName, getEntityOwnerId()); if (securityGroupId == null) { @@ -127,11 +125,11 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { } securityGroupName = null; } - + if (securityGroupId == null) { throw new InvalidParameterValueException("Either securityGroupId or securityGroupName is required by authorizeSecurityGroupIngress command"); } - + return securityGroupId; } @@ -169,7 +167,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -210,7 +208,7 @@ public class AuthorizeSecurityGroupIngressCmd extends BaseAsyncCmd { @Override public void execute() { if(cidrList != null){ - for(String cidr : cidrList ){ + for(String cidr : cidrList ){ if (!NetUtils.isValidCIDR(cidr)){ throw new ServerApiException(BaseCmd.PARAM_ERROR, cidr + " is an Invalid CIDR "); } diff --git a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java index 62fae921f7d..c494355e15e 100644 --- a/api/src/com/cloud/api/commands/CreateSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/CreateSecurityGroupCmd.java @@ -14,22 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject = SecurityGroupResponse.class, description = "Creates a security group") +@APICommand(name = "createSecurityGroup", responseObject = SecurityGroupResponse.class, description = "Creates a security group") public class CreateSecurityGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSecurityGroupCmd.class.getName()); @@ -42,8 +43,7 @@ public class CreateSecurityGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "an optional account for the security group. Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, description = "an optional domainId for the security group. If the account parameter is used, domainId must also be used.", entityType = DomainResponse.class) private Long domainId; @Parameter(name = ApiConstants.DESCRIPTION, type = CommandType.STRING, description = "the description of the security group") @@ -52,8 +52,7 @@ public class CreateSecurityGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "name of the security group") private String securityGroupName; - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "Deploy vm for the project") + @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.UUID, description = "Deploy vm for the project", entityType=ProjectAccountResponse.class) private Long projectId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java similarity index 78% rename from api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java index 924e8a83d0f..15a00253b63 100644 --- a/api/src/com/cloud/api/commands/DeleteSecurityGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/DeleteSecurityGroupCmd.java @@ -14,22 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceInUseException; import com.cloud.user.UserContext; -@Implementation(description="Deletes security group", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSecurityGroup", description="Deletes security group", responseObject=SuccessResponse.class) public class DeleteSecurityGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteSecurityGroupCmd.class.getName()); private static final String s_name = "deletesecuritygroupresponse"; @@ -41,18 +43,15 @@ public class DeleteSecurityGroupCmd extends BaseCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account of the security group. Must be specified with domain ID") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID of account owning the security group") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, description="the domain ID of account owning the security group", entityType=DomainResponse.class) private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project of the security group") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, description="the project of the security group", entityType=ProjectAccountResponse.class) private Long projectId; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="The ID of the security group. Mutually exclusive with name parameter") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, description="The ID of the security group. Mutually exclusive with name parameter", entityType=SecurityGroupResponse.class) private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="The ID of the security group. Mutually exclusive with id parameter") private String name; @@ -68,7 +67,7 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } @@ -77,18 +76,18 @@ public class DeleteSecurityGroupCmd extends BaseCmd { if (id != null && name != null) { throw new InvalidParameterValueException("name and id parameters are mutually exclusive"); } - + if (name != null) { id = _responseGenerator.getSecurityGroupId(name, getEntityOwnerId()); if (id == null) { throw new InvalidParameterValueException("Unable to find security group by name " + name + " for the account id=" + getEntityOwnerId()); } } - + if (id == null) { throw new InvalidParameterValueException("Either id or name parameter is requred by deleteSecurityGroup command"); } - + return id; } @@ -102,17 +101,17 @@ public class DeleteSecurityGroupCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + @Override public void execute(){ try{ diff --git a/api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java similarity index 66% rename from api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java index 6da023af848..cf1ab84bad0 100644 --- a/api/src/com/cloud/api/commands/ListSecurityGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/ListSecurityGroupsCmd.java @@ -14,44 +14,39 @@ // 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 java.util.List; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.async.AsyncJob; -import com.cloud.network.security.SecurityGroupRules; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; - -@Implementation(description="Lists security groups", responseObject=SecurityGroupResponse.class) -public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSecurityGroupsCmd.class.getName()); - - private static final String s_name = "listsecuritygroupsresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="lists security groups by name") - private String securityGroupName; - - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="lists security groups by virtual machine id") +import com.cloud.async.AsyncJob; + +@APICommand(name = "listSecurityGroups", description="Lists security groups", responseObject=SecurityGroupResponse.class) +public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListSecurityGroupsCmd.class.getName()); + + private static final String s_name = "listsecuritygroupsresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.SECURITY_GROUP_NAME, type=CommandType.STRING, description="lists security groups by name") + private String securityGroupName; + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, description="lists security groups by virtual machine id", entityType=UserVmResponse.class) private Long virtualMachineId; - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list the security group by the id provided") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, description="list the security group by the id provided", entityType=SecurityGroupResponse.class) private Long id; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -62,9 +57,9 @@ public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { public Long getVirtualMachineId() { return virtualMachineId; } - + public Long getId(){ - return id; + return id; } ///////////////////////////////////////////////////// @@ -78,13 +73,11 @@ public class ListSecurityGroupsCmd extends BaseListTaggedResourcesCmd { @Override public void execute(){ - List securityGroups = _securityGroupService.searchForSecurityGroupRules(this); - - ListResponse response = _responseGenerator.createSecurityGroupResponses(securityGroups); + ListResponse response = _queryService.searchForSecurityGroups(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.SecurityGroup; diff --git a/api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java index 273c145bdbd..53d8fcf59c7 100644 --- a/api/src/com/cloud/api/commands/RevokeSecurityGroupEgressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupEgressCmd.java @@ -14,24 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; -@Implementation(responseObject = SuccessResponse.class, description = "Deletes a particular egress rule from this security group", since="3.0.0") +@APICommand(name = "revokeSecurityGroupEgress", responseObject = SuccessResponse.class, description = "Deletes a particular egress rule from this security group", since="3.0.0") public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupEgressCmd.class.getName()); @@ -41,8 +37,7 @@ public class RevokeSecurityGroupEgressCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="security_group_rule") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the egress rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, required = true, description = "The ID of the egress rule", entityType=SecurityGroupRuleResponse.class) private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java rename to api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java index 9782c1d03f6..1f56dee9bca 100644 --- a/api/src/com/cloud/api/commands/RevokeSecurityGroupIngressCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/securitygroup/RevokeSecurityGroupIngressCmd.java @@ -14,24 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.securitygroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.network.security.SecurityGroup; import com.cloud.user.Account; -@Implementation(responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group") +@APICommand(name = "revokeSecurityGroupIngress", responseObject = SuccessResponse.class, description = "Deletes a particular ingress rule from this security group") public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RevokeSecurityGroupIngressCmd.class.getName()); @@ -41,8 +41,7 @@ public class RevokeSecurityGroupIngressCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName="security_group_rule") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the ingress rule") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, required = true, description = "The ID of the ingress rule", entityType=SecurityGroupRuleResponse.class) private Long id; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java old mode 100755 new mode 100644 similarity index 73% rename from api/src/com/cloud/api/commands/CreateSnapshotCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java index d1b6d7ad41a..33469ac4882 --- a/api/src/com/cloud/api/commands/CreateSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotCmd.java @@ -14,18 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SnapshotResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -37,7 +35,7 @@ import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description = "Creates an instant snapshot of a volume.", responseObject = SnapshotResponse.class) +@APICommand(name = "createSnapshot", description = "Creates an instant snapshot of a volume.", responseObject = SnapshotResponse.class) public class CreateSnapshotCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateSnapshotCmd.class.getName()); private static final String s_name = "createsnapshotresponse"; @@ -49,24 +47,26 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "The account of the snapshot. The account parameter must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.") + @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.UUID, entityType = DomainResponse.class, + description = "The domain ID of the snapshot. If used with the account parameter, specifies a domain for the account associated with the disk volume.") private Long domainId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.LONG, required = true, description = "The ID of the disk volume") + @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.UUID, entityType = VolumeResponse.class, + required = true, description = "The ID of the disk volume") private Long volumeId; - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.LONG, description = "policy id of the snapshot, if this is null, then use MANUAL_POLICY.") + @Parameter(name = ApiConstants.POLICY_ID, type = CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description = "policy id of the snapshot, if this is null, then use MANUAL_POLICY.") private Long policyId; + private String syncObjectType = BaseAsyncCmd.snapshotHostSyncObject; + // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + public String getEntityTable() { - return "snapshots"; + return "snapshots"; } public String getAccountName() { @@ -89,6 +89,15 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { } } + private Long getHostId() { + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); + if (volume == null) { + throw new InvalidParameterValueException("Unable to find volume by id"); + } + return _snapshotService.getHostIdForSnapshotOperation(volume); + } + + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -104,23 +113,23 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { @Override public long getEntityOwnerId() { - + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { throw new PermissionDeniedException("Can't add resources to the project id=" + project.getId() + " in state=" + project.getState() + " as it's no longer active"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } @@ -161,4 +170,21 @@ public class CreateSnapshotCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create snapshot due to an internal error creating snapshot for volume " + volumeId); } } + + + @Override + public String getSyncObjType() { + if (getSyncObjId() != null) { + return syncObjectType; + } + return null; + } + + @Override + public Long getSyncObjId() { + if (getHostId() != null) { + return getHostId(); + } + return null; + } } diff --git a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java index 6708bf9e8b2..cafb79e0523 100644 --- a/api/src/com/cloud/api/commands/CreateSnapshotPolicyCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/CreateSnapshotPolicyCmd.java @@ -14,17 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.projects.Project; @@ -32,7 +29,7 @@ import com.cloud.storage.Volume; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.user.Account; -@Implementation(description="Creates a snapshot policy for the account.", responseObject=SnapshotPolicyResponse.class) +@APICommand(name = "createSnapshotPolicy", description="Creates a snapshot policy for the account.", responseObject=SnapshotPolicyResponse.class) public class CreateSnapshotPolicyCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSnapshotPolicyCmd.class.getName()); @@ -49,18 +46,18 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { private Integer maxSnaps; @Parameter(name=ApiConstants.SCHEDULE, type=CommandType.STRING, required=true, description="time the snapshot is scheduled to be taken. " + - "Format is:" + - "* if HOURLY, MM" + - "* if DAILY, MM:HH" + - "* if WEEKLY, MM:HH:DD (1-7)" + - "* if MONTHLY, MM:HH:DD (1-28)") + "Format is:" + + "* if HOURLY, MM" + + "* if DAILY, MM:HH" + + "* if WEEKLY, MM:HH:DD (1-7)" + + "* if MONTHLY, MM:HH:DD (1-28)") private String schedule; @Parameter(name=ApiConstants.TIMEZONE, type=CommandType.STRING, required=true, description="Specifies a timezone for this command. For more information on the timezone parameter, see Time Zone Format.") private String timezone; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long volumeId; @@ -97,30 +94,30 @@ public class CreateSnapshotPolicyCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume == null) { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } - + Account account = _accountService.getAccount(volume.getAccountId()); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(volume.getAccountId()); + Project project = _projectService.findByProjectAccountId(volume.getAccountId()); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); throw ex; } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return volume.getAccountId(); } - + @Override public void execute(){ SnapshotPolicy result = _snapshotService.createPolicy(this, _accountService.getAccount(getEntityOwnerId())); diff --git a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteSnapshotCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java index 97c25a50df0..6def8730cbd 100644 --- a/api/src/com/cloud/api/commands/DeleteSnapshotCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Snapshot; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a snapshot of a disk volume.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSnapshot", description="Deletes a snapshot of a disk volume.", responseObject=SuccessResponse.class) public class DeleteSnapshotCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteSnapshotCmd.class.getName()); private static final String s_name = "deletesnapshotresponse"; @@ -41,11 +37,10 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the snapshot") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotResponse.class, + required=true, description="The ID of the snapshot") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -82,13 +77,13 @@ public class DeleteSnapshotCmd extends BaseAsyncCmd { public String getEventDescription() { return "deleting snapshot: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Snapshot; + return AsyncJob.Type.Snapshot; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override diff --git a/api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java index ebd4d40d401..17f28d931ea --- a/api/src/com/cloud/api/commands/DeleteSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/DeleteSnapshotPoliciesCmd.java @@ -14,40 +14,39 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; -@Implementation(description="Deletes snapshot policies for the account.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSnapshotPolicies", description="Deletes snapshot policies for the account.", responseObject=SuccessResponse.class) public class DeleteSnapshotPoliciesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteSnapshotPoliciesCmd.class.getName()); private static final String s_name = "deletesnapshotpoliciesresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the Id of the snapshot policy") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description="the Id of the snapshot policy") private Long id; - @IdentityMapper(entityTableName="snapshot_policy") - @Parameter(name=ApiConstants.IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of snapshots policy IDs separated by comma") + @Parameter(name=ApiConstants.IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType = SnapshotPolicyResponse.class, + description="list of snapshots policy IDs separated by comma") private List ids; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -60,7 +59,6 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd { return ids; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -69,7 +67,7 @@ public class DeleteSnapshotPoliciesCmd extends BaseCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { return Account.ACCOUNT_ID_SYSTEM; diff --git a/api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java index c19924be627..647c503a445 100644 --- a/api/src/com/cloud/api/commands/ListSnapshotPoliciesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotPoliciesCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.storage.snapshot.SnapshotPolicy; -@Implementation(description="Lists snapshot policies.", responseObject=SnapshotPolicyResponse.class) +@APICommand(name = "listSnapshotPolicies", description="Lists snapshot policies.", responseObject=SnapshotPolicyResponse.class) public class ListSnapshotPoliciesCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSnapshotPoliciesCmd.class.getName()); @@ -40,8 +40,8 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long volumeId; ///////////////////////////////////////////////////// @@ -72,7 +72,7 @@ public class ListSnapshotPoliciesCmd extends BaseListCmd { policyResponses.add(policyResponse); } response.setResponses(policyResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListSnapshotsCmd.java b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ListSnapshotsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java index d7b2c9e05f9..5c6e79c9170 100644 --- a/api/src/com/cloud/api/commands/ListSnapshotsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/snapshot/ListSnapshotsCmd.java @@ -14,36 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.snapshot; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SnapshotResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.storage.Snapshot; +import com.cloud.utils.Pair; +@APICommand(name = "listSnapshots", description="Lists all available snapshots for the account.", responseObject=SnapshotResponse.class) +public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListSnapshotsCmd.class.getName()); + + private static final String s_name = "listsnapshotsresponse"; -@Implementation(description="Lists all available snapshots for the account.", responseObject=SnapshotResponse.class) -public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListSnapshotsCmd.class.getName()); - - private static final String s_name = "listsnapshotsresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="lists snapshot by snapshot ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = SnapshotResponse.class, + description="lists snapshot by snapshot ID") private Long id; @Parameter(name=ApiConstants.INTERVAL_TYPE, type=CommandType.STRING, description="valid values are HOURLY, DAILY, WEEKLY, and MONTHLY.") @@ -55,8 +55,8 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.SNAPSHOT_TYPE, type=CommandType.STRING, description="valid values are MANUAL or RECURRING.") private String snapshotType; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType = VolumeResponse.class, + description="the ID of the disk volume") private Long volumeId; ///////////////////////////////////////////////////// @@ -82,7 +82,7 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { public Long getVolumeId() { return volumeId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -91,24 +91,24 @@ public class ListSnapshotsCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Snapshot; + return AsyncJob.Type.Snapshot; } @Override public void execute(){ - List result = _snapshotService.listSnapshots(this); + Pair, Integer> result = _snapshotService.listSnapshots(this); ListResponse response = new ListResponse(); List snapshotResponses = new ArrayList(); - for (Snapshot snapshot : result) { + for (Snapshot snapshot : result.first()) { SnapshotResponse snapshotResponse = _responseGenerator.createSnapshotResponse(snapshot); snapshotResponse.setObjectName("snapshot"); snapshotResponses.add(snapshotResponse); } - response.setResponses(snapshotResponses); + response.setResponses(snapshotResponses, result.second()); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java similarity index 58% rename from api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java index f750ee88d88..bade8572f82 100644 --- a/api/src/com/cloud/api/commands/CreateSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/CreateSSHKeyPairCmd.java @@ -14,57 +14,58 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; import com.cloud.user.UserContext; -@Implementation(description="Create a new keypair and returns the private key", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "createSSHKeyPair", description="Create a new keypair and returns the private key", responseObject=SSHKeyPairResponse.class) public class CreateSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSSHKeyPairCmd.class.getName()); private static final String s_name = "createsshkeypairresponse"; - - + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + //Owner information @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the ssh key. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - + + public String getName() { + return name; + } + public String getAccountName() { return accountName; } - + public Long getDomainId() { return domainId; } @@ -72,31 +73,31 @@ public class CreateSSHKeyPairCmd extends BaseCmd { public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } + } - @Override - public void execute() { - SSHKeyPair r = _mgr.createSSHKeyPair(this); - SSHKeyPairResponse response = new SSHKeyPairResponse(r.getName(), r.getFingerprint(), r.getPrivateKey()); - response.setResponseName(getCommandName()); - response.setObjectName("keypair"); - this.setResponseObject(response); - } + @Override + public void execute() { + SSHKeyPair r = _mgr.createSSHKeyPair(this); + SSHKeyPairResponse response = new SSHKeyPairResponse(r.getName(), r.getFingerprint(), r.getPrivateKey()); + response.setResponseName(getCommandName()); + response.setObjectName("keypair"); + this.setResponseObject(response); + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java index d4f6b472f6d..9b6d403f48e 100644 --- a/api/src/com/cloud/api/commands/DeleteSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/DeleteSSHKeyPairCmd.java @@ -14,81 +14,81 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a keypair by name", responseObject=SuccessResponse.class) +@APICommand(name = "deleteSSHKeyPair", description="Deletes a keypair by name", responseObject=SuccessResponse.class) public class DeleteSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateSSHKeyPairCmd.class.getName()); private static final String s_name = "deletesshkeypairresponse"; - - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the keypair. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the keypair") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="the domain ID associated with the keypair") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project associated with keypair") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="the project associated with keypair") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - - public String getAccountName() { - return accountName; + ///////////////////////////////////////////////////// + + public String getName() { + return name; + } + + public String getAccountName() { + return accountName; } public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// + ///////////////////////////////////////////////////// @Override - public void execute() { - boolean result = _mgr.deleteSSHKeyPair(this); - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setSuccess(result); - this.setResponseObject(response); - } + public void execute() { + boolean result = _mgr.deleteSSHKeyPair(this); + SuccessResponse response = new SuccessResponse(getCommandName()); + response.setSuccess(result); + this.setResponseObject(response); + } - @Override - public String getCommandName() { - return s_name; - } - - @Override + @Override + public String getCommandName() { + return s_name; + } + + @Override public long getEntityOwnerId() { Account account = UserContext.current().getCaller(); if ((account == null) || isAdmin(account.getType())) { diff --git a/api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java similarity index 55% rename from api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java index 30675542457..27013dfd5f6 100644 --- a/api/src/com/cloud/api/commands/ListSSHKeyPairsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/ListSSHKeyPairsCmd.java @@ -14,75 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; +import com.cloud.utils.Pair; -@Implementation(description="List registered keypairs", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "listSSHKeyPairs", description="List registered keypairs", responseObject=SSHKeyPairResponse.class) public class ListSSHKeyPairsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListSSHKeyPairsCmd.class.getName()); private static final String s_name = "listsshkeypairsresponse"; - - + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="A key pair name to look for") - private String name; - - @Parameter(name="fingerprint", type=CommandType.STRING, description="A public key fingerprint to look for") + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="A key pair name to look for") + private String name; + + @Parameter(name="fingerprint", type=CommandType.STRING, description="A public key fingerprint to look for") private String fingerprint; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } - - public String getFingerprint() { - return fingerprint; - } - - + ///////////////////////////////////////////////////// + + public String getName() { + return name; + } + + public String getFingerprint() { + return fingerprint; + } + + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override - public void execute() { - List resultList = _mgr.listSSHKeyPairs(this); - List responses = new ArrayList(); - for (SSHKeyPair result : resultList) { - SSHKeyPairResponse r = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); - r.setObjectName("sshkeypair"); - responses.add(r); - } - + + @Override + public void execute() { + Pair, Integer> resultList = _mgr.listSSHKeyPairs(this); + List responses = new ArrayList(); + for (SSHKeyPair result : resultList.first()) { + SSHKeyPairResponse r = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); + r.setObjectName("sshkeypair"); + responses.add(r); + } + ListResponse response = new ListResponse(); - response.setResponses(responses); + response.setResponses(responses, resultList.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); - } + } - @Override - public String getCommandName() { - return s_name; - } + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java b/api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java similarity index 60% rename from api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java rename to api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java index 321be365fa4..2f08692f09b 100644 --- a/api/src/com/cloud/api/commands/RegisterSSHKeyPairCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/ssh/RegisterSSHKeyPairCmd.java @@ -14,97 +14,97 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.ssh; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SSHKeyPairResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SSHKeyPairResponse; import com.cloud.user.SSHKeyPair; import com.cloud.user.UserContext; -@Implementation(description="Register a public key in a keypair under a certain name", responseObject=SSHKeyPairResponse.class) +@APICommand(name = "registerSSHKeyPair", description="Register a public key in a keypair under a certain name", responseObject=SSHKeyPairResponse.class) public class RegisterSSHKeyPairCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterSSHKeyPairCmd.class.getName()); private static final String s_name = "registersshkeypairresponse"; - - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") - private String name; - - @Parameter(name="publickey", type=CommandType.STRING, required=true, description="Public key material of the keypair", length=5120) + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="Name of the keypair") + private String name; + + @Parameter(name="publickey", type=CommandType.STRING, required=true, description="Public key material of the keypair", length=5120) private String publicKey; //Owner information @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the ssh key. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId for the ssh key. If the account parameter is used, domainId must also be used.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="an optional project for the ssh key") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="an optional project for the ssh key") private Long projectId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getName() { - return name; - } + ///////////////////////////////////////////////////// - public String getPublicKey() { - return publicKey; - } + public String getName() { + return name; + } + + public String getPublicKey() { + return publicKey; + } + + public String getAccountName() { + return accountName; + } - public String getAccountName() { - return accountName; - } - public Long getDomainId() { return domainId; } - + public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } - - @Override - public void execute() { - SSHKeyPair result = _mgr.registerSSHKeyPair(this); + } + + @Override + public void execute() { + SSHKeyPair result = _mgr.registerSSHKeyPair(this); SSHKeyPairResponse response = new SSHKeyPairResponse(result.getName(), result.getFingerprint()); response.setResponseName(getCommandName()); - response.setObjectName("keypair"); + response.setObjectName("keypair"); this.setResponseObject(response); - } + } + + @Override + public String getCommandName() { + return s_name; + } - @Override - public String getCommandName() { - return s_name; - } - } diff --git a/api/src/com/cloud/api/commands/CreateTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/CreateTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java index d52c52fdd6b..54338bd24e2 100644 --- a/api/src/com/cloud/api/commands/CreateTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/CreateTagsCmd.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; import java.util.Collection; import java.util.HashMap; @@ -25,18 +25,17 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceTag; import com.cloud.server.ResourceTag.TaggedResourceType; -@Implementation(description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +@APICommand(name = "createTags", description = "Creates resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") public class CreateTagsCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(CreateTagsCmd.class.getName()); @@ -45,30 +44,30 @@ public class CreateTagsCmd extends BaseAsyncCmd{ // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, required=true, description = "Map of tags (key/value pairs)") private Map tag; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="type of the resource") private String resourceType; - - @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="list of resources to create the tags for") private List resourceIds; - + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="identifies client specific tag. " + - "When the value is not null, the tag can't be used by cloudStack code internally") + "When the value is not null, the tag can't be used by cloudStack code internally") private String customer; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public TaggedResourceType getResourceType(){ return _taggedResourceService.getResourceType(resourceType); - } - + } + public Map getTags() { Map tagsMap = null; if (!tag.isEmpty()) { @@ -84,11 +83,11 @@ public class CreateTagsCmd extends BaseAsyncCmd{ } return tagsMap; } - + public List getResourceIds() { return resourceIds; } - + public String getCustomer() { return customer; } @@ -111,7 +110,7 @@ public class CreateTagsCmd extends BaseAsyncCmd{ @Override public void execute() { List tags = _taggedResourceService.createTags(getResourceIds(), getResourceType(), getTags(), getCustomer()); - + if (tags != null && !tags.isEmpty()) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DeleteTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java similarity index 87% rename from api/src/com/cloud/api/commands/DeleteTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java index 03f734523e2..cf2ea9ec1cb 100644 --- a/api/src/com/cloud/api/commands/DeleteTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/DeleteTagsCmd.java @@ -15,7 +15,7 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; import java.util.Collection; import java.util.HashMap; @@ -25,16 +25,16 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.server.ResourceTag.TaggedResourceType; -@Implementation(description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") +@APICommand(name = "deleteTags", description = "Deleting resource tag(s)", responseObject = SuccessResponse.class, since = "Burbank") public class DeleteTagsCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteTagsCmd.class.getName()); @@ -43,14 +43,14 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ // /////////////////////////////////////////////////// // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - + @Parameter(name = ApiConstants.TAGS, type = CommandType.MAP, description = "Delete tags matching key/value pairs") private Map tag; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, required=true, description="Delete tag by resource type") private String resourceType; - - @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, + + @Parameter(name=ApiConstants.RESOURCE_IDS, type=CommandType.LIST, required=true, collectionType=CommandType.STRING, description="Delete tags for resource id(s)") private List resourceIds; @@ -58,11 +58,11 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public TaggedResourceType getResourceType(){ return _taggedResourceService.getResourceType(resourceType); - } - + } + public Map getTags() { Map tagsMap = null; if (tag != null && !tag.isEmpty()) { @@ -78,7 +78,7 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ } return tagsMap; } - + public List getResourceIds() { return resourceIds; } @@ -101,7 +101,7 @@ public class DeleteTagsCmd extends BaseAsyncCmd{ @Override public void execute() { boolean success = _taggedResourceService.deleteTags(getResourceIds(), getResourceType(), getTags()); - + if (success) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/ListTagsCmd.java b/api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java similarity index 68% rename from api/src/com/cloud/api/commands/ListTagsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java index 7206b1c882c..e3dc108a757 100644 --- a/api/src/com/cloud/api/commands/ListTagsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/tag/ListTagsCmd.java @@ -15,55 +15,43 @@ // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.tag; -import java.util.ArrayList; -import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.server.ResourceTag; - -@Implementation(description = "List resource tag(s)", responseObject = ResourceTagResponse.class, since = "Burbank") +@APICommand(name = "listTags", description = "List resource tag(s)", responseObject = ResourceTagResponse.class, since = "Burbank") public class ListTagsCmd extends BaseListProjectAndAccountResourcesCmd{ private static final String s_name = "listtagsresponse"; - + @Parameter(name=ApiConstants.RESOURCE_TYPE, type=CommandType.STRING, description="list by resource type") private String resourceType; - + @Parameter(name=ApiConstants.RESOURCE_ID, type=CommandType.STRING, description="list by resource id") private String resourceId; - + @Parameter(name=ApiConstants.KEY, type=CommandType.STRING, description="list by key") private String key; - + @Parameter(name=ApiConstants.VALUE, type=CommandType.STRING, description="list by value") private String value; - + @Parameter(name=ApiConstants.CUSTOMER, type=CommandType.STRING, description="list by customer name") private String customer; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @Override public void execute() { - - List tags = _taggedResourceService.listTags(this); - ListResponse response = new ListResponse(); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = _responseGenerator.createResourceTagResponse(tag, false); - tagResponses.add(tagResponse); - } - response.setResponses(tagResponses); - + + ListResponse response = _queryService.listTags(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } @@ -88,7 +76,7 @@ public class ListTagsCmd extends BaseListProjectAndAccountResourcesCmd{ public String getCommandName() { return s_name; } - + public String getCustomer() { return customer; } diff --git a/api/src/com/cloud/api/commands/CopyTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java old mode 100755 new mode 100644 similarity index 74% rename from api/src/com/cloud/api/commands/CopyTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java index d825bbce68c..c6461a75e28 --- a/api/src/com/cloud/api/commands/CopyTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CopyTemplateCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; @@ -36,25 +37,25 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Copies a template from one zone to another.", responseObject=TemplateResponse.class) +@APICommand(name = "copyTemplate", description="Copies a template from one zone to another.", responseObject=TemplateResponse.class) public class CopyTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CopyTemplateCmd.class.getName()); private static final String s_name = "copytemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.DESTINATION_ZONE_ID, type=CommandType.LONG, required=true, description="ID of the zone the template is being copied to.") + @Parameter(name=ApiConstants.DESTINATION_ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="ID of the zone the template is being copied to.") private Long destZoneId; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Template ID.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="Template ID.") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.SOURCE_ZONE_ID, type=CommandType.LONG, required=true, description="ID of the zone the template is currently hosted on.") + @Parameter(name=ApiConstants.SOURCE_ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="ID of the zone the template is currently hosted on.") private Long sourceZoneId; @@ -107,29 +108,29 @@ public class CopyTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "copying template: " + getId() + " from zone: " + getSourceZoneId() + " to zone: " + getDestinationZoneId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override public void execute() throws ResourceAllocationException{ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); VirtualMachineTemplate template = _templateService.copyTemplate(this); - + if (template != null){ List listResponse = _responseGenerator.createTemplateResponses(template.getId(), getDestinationZoneId(), false); TemplateResponse response = new TemplateResponse(); if (listResponse != null && !listResponse.isEmpty()) { response = listResponse.get(0); } - - response.setResponseName(getCommandName()); + + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to copy template"); @@ -137,7 +138,7 @@ public class CopyTemplateCmd extends BaseAsyncCmd { } catch (StorageUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); - } + } } } diff --git a/api/src/com/cloud/api/commands/CreateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java old mode 100755 new mode 100644 similarity index 81% rename from api/src/com/cloud/api/commands/CreateTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java index 05f18fb9a49..65cc8b9e9a4 --- a/api/src/com/cloud/api/commands/CreateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/CreateTemplateCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.Collection; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -43,7 +42,7 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject = StoragePoolResponse.class, description = "Creates a template of a virtual machine. " + "The virtual machine must be in a STOPPED state. " +@APICommand(name = "createTemplate", responseObject = StoragePoolResponse.class, description = "Creates a template of a virtual machine. " + "The virtual machine must be in a STOPPED state. " + "A template created from this command is automatically designated as a private template visible to the account that created it.") public class CreateTemplateCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateTemplateCmd.class.getName()); @@ -68,8 +67,8 @@ import com.cloud.user.UserContext; @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the template") private String templateName; - @IdentityMapper(entityTableName="guest_os") - @Parameter(name = ApiConstants.OS_TYPE_ID, type = CommandType.LONG, required = true, description = "the ID of the OS Type that best represents the OS of this template.") + @Parameter(name = ApiConstants.OS_TYPE_ID, type = CommandType.UUID, entityType = GuestOSResponse.class, + required = true, description = "the ID of the OS Type that best represents the OS of this template.") private Long osTypeId; @Parameter(name = ApiConstants.PASSWORD_ENABLED, type = CommandType.BOOLEAN, description = "true if the template supports the password reset feature; default is false") @@ -78,16 +77,16 @@ import com.cloud.user.UserContext; @Parameter(name = ApiConstants.REQUIRES_HVM, type = CommandType.BOOLEAN, description = "true if the template requres HVM, false otherwise") private Boolean requiresHvm; - @IdentityMapper(entityTableName="snapshots") - @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.LONG, description = "the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in") + @Parameter(name = ApiConstants.SNAPSHOT_ID, type = CommandType.UUID, entityType = SnapshotResponse.class, + description = "the ID of the snapshot the template is being created from. Either this parameter, or volumeId has to be passed in") private Long snapshotId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.LONG, description = "the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in") + @Parameter(name = ApiConstants.VOLUME_ID, type = CommandType.UUID, entityType = VolumeResponse.class, + description = "the ID of the disk volume the template is being created from. Either this parameter, or snapshotId has to be passed in") private Long volumeId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType = UserVmResponse.class, + description="Optional, VM ID. If this presents, it is going to create a baremetal template for VM this ID refers to. This is only for VM whose hypervisor type is BareMetal") private Long vmId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, description="Optional, only for baremetal hypervisor. The directory name where template stored on CIFS server") @@ -95,16 +94,16 @@ import com.cloud.user.UserContext; @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; // /////////////////////////////////////////////////// // ///////////////// Accessors /////////////////////// // /////////////////////////////////////////////////// - + public String getEntityTable() { - return "vm_template"; + return "vm_template"; } public Integer getBits() { @@ -158,17 +157,17 @@ import com.cloud.user.UserContext; public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// // /////////////////////////////////////////////////// @@ -192,29 +191,29 @@ import com.cloud.user.UserContext; if (volume != null) { accountId = volume.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); + throw new InvalidParameterValueException("Unable to find volume by id=" + volumeId); } } else { Snapshot snapshot = _entityMgr.findById(Snapshot.class, snapshotId); if (snapshot != null) { accountId = snapshot.getAccountId(); } else { - throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); + throw new InvalidParameterValueException("Unable to find snapshot by id=" + snapshotId); } } - + Account account = _accountService.getAccount(accountId); //Can create templates for enabled projects/accounts only if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - Project project = _projectService.findByProjectAccountId(accountId); + Project project = _projectService.findByProjectAccountId(accountId); if (project.getState() != Project.State.Active) { - PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); + PermissionDeniedException ex = new PermissionDeniedException("Can't add resources to the specified project id in state=" + project.getState() + " as it's no longer active"); ex.addProxyObject(project, project.getId(), "projectId"); } } else if (account.getState() == Account.State.disabled) { throw new PermissionDeniedException("The owner of template is disabled: " + account); } - + return accountId; } @@ -276,7 +275,7 @@ import com.cloud.user.UserContext; if (templateResponses != null && !templateResponses.isEmpty()) { response = templateResponses.get(0); } - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create private template"); diff --git a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/commands/DeleteTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java index bdbb95ba7e7..26f3e841f68 --- a/api/src/com/cloud/api/commands/DeleteTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/DeleteTemplateCmd.java @@ -14,39 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(responseObject=SuccessResponse.class, description="Deletes a template from the system. All virtual machines using the deleted template will not be affected.") +@APICommand(name = "deleteTemplate", responseObject=SuccessResponse.class, description="Deletes a template from the system. All virtual machines using the deleted template will not be affected.") public class DeleteTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DeleteTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteTemplateCmd.class.getName()); private static final String s_name = "deletetemplateresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the template") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of the template") private Long id; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of zone of the template") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="the ID of zone of the template") private Long zoneId; @@ -66,12 +63,12 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + public static String getStaticName() { return s_name; } @@ -95,15 +92,15 @@ public class DeleteTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "Deleting template " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Template Id: "+getId()); diff --git a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/commands/ExtractTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java index 975897e3789..521293cb275 --- a/api/src/com/cloud/api/commands/ExtractTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ExtractTemplateCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InternalErrorException; @@ -33,9 +30,9 @@ import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts a template", responseObject=ExtractResponse.class) +@APICommand(name = "extractTemplate", description="Extracts a template", responseObject=ExtractResponse.class) public class ExtractTemplateCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractTemplateCmd.class.getName()); private static final String s_name = "extracttemplateresponse"; @@ -43,20 +40,20 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the template") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = UserVmResponse.class, + required=true, description="the ID of the template") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the ISO would be extracted") private String url; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=false, description="the ID of the zone where the ISO is originally located" ) + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=false, description="the ID of the zone where the ISO is originally located" ) private Long zoneId; @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -76,16 +73,16 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { public String getMode() { return mode; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } + public static String getStaticName() { return s_name; } @@ -110,19 +107,19 @@ public class ExtractTemplateCmd extends BaseAsyncCmd { public String getEventDescription() { return "extracting template: " + getId() + " from zone: " + getZoneId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute(){ try { - UserContext.current().setEventDetails(getEventDescription()); + UserContext.current().setEventDetails(getEventDescription()); Long uploadId = _templateService.extract(this); if (uploadId != null){ ExtractResponse response = _responseGenerator.createExtractResponse(uploadId, id, zoneId, getEntityOwnerId(), mode); diff --git a/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java new file mode 100644 index 00000000000..7446195d5fb --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatePermissionsCmd.java @@ -0,0 +1,46 @@ +// Licensedname = "listTemplatePermissions", 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 org.apache.cloudstack.api.command.user.template; + +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.log4j.Logger; + +import com.cloud.storage.Storage.ImageFormat; +import com.cloud.template.VirtualMachineTemplate; + +@APICommand(name = "listTemplatePermissions", description="List template visibility and all accounts that have permissions to view this template.", responseObject=TemplatePermissionsResponse.class) +public class ListTemplatePermissionsCmd extends BaseListTemplateOrIsoPermissionsCmd { + protected String getResponseName() { + return "listtemplatepermissionsresponse"; + } + + @Override + public String getMediaType() { + return "template"; + } + + @Override + protected Logger getLogger() { + return Logger.getLogger(ListTemplatePermissionsCmd.class.getName()); + } + + protected boolean templateIsCorrectType(VirtualMachineTemplate template) { + return !template.getFormat().equals(ImageFormat.ISO); + } +} diff --git a/api/src/com/cloud/api/commands/ListTemplatesCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListTemplatesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java index 6e1e0b4b754..a1464ccdc4e --- a/api/src/com/cloud/api/commands/ListTemplatesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/ListTemplatesCmd.java @@ -14,28 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.util.ArrayList; import java.util.List; import java.util.Set; +import com.cloud.storage.template.TemplateInfo; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.async.AsyncJob; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.utils.Pair; -@Implementation(description="List all public, private, and privileged templates.", responseObject=TemplateResponse.class) +@APICommand(name = "listTemplates", description="List all public, private, and privileged templates.", responseObject=TemplateResponse.class) public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListTemplatesCmd.class.getName()); @@ -48,22 +50,22 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the hypervisor for which to restrict the search") private String hypervisor; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the template ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=TemplateResponse.class, + description="the template ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the template name") private String templateName; @Parameter(name=ApiConstants.TEMPLATE_FILTER, type=CommandType.STRING, required=true, description="possible values are \"featured\", \"self\", \"self-executable\", \"executable\", and \"community\"." + - "* featured-templates that are featured and are public" + - "* self-templates that have been registered/created by the owner" + - "* selfexecutable-templates that have been registered/created by the owner that can be used to deploy a new VM" + - "* executable-all templates that can be used to deploy a new VM* community-templates that are public.") + "* featured-templates that are featured and are public" + + "* self-templates that have been registered/created by the owner" + + "* selfexecutable-templates that have been registered/created by the owner that can be used to deploy a new VM" + + "* executable-all templates that can be used to deploy a new VM* community-templates that are public.") private String templateFilter; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list templates by zoneId") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + description="list templates by zoneId") private Long zoneId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -88,9 +90,9 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public boolean listInReadyState() { - + Account account = UserContext.current().getCaller(); // It is account specific if account is admin type and domainId and accountName are not null boolean isAccountSpecific = (account == null || isAdmin(account.getType())) && (getAccountName() != null) && (getDomainId() != null); @@ -109,11 +111,11 @@ public class ListTemplatesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Template; + return AsyncJob.Type.Template; } - + @Override public void execute(){ Set> templateZonePairSet = _mgr.listTemplates(this); diff --git a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java old mode 100755 new mode 100644 similarity index 79% rename from api/src/com/cloud/api/commands/RegisterTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java index d33f5048feb..b3677b9d3a1 --- a/api/src/com/cloud/api/commands/RegisterTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/RegisterTemplateCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; import java.net.URISyntaxException; import java.util.Collection; @@ -23,21 +23,23 @@ import java.util.Map; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.exception.ResourceAllocationException; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.UserContext; -@Implementation(description="Registers an existing template into the CloudStack cloud. ", responseObject=TemplateResponse.class) +@APICommand(name = "registerTemplate", description="Registers an existing template into the CloudStack cloud. ", responseObject=TemplateResponse.class) public class RegisterTemplateCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(RegisterTemplateCmd.class.getName()); @@ -68,13 +70,13 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the template") private String templateName; - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, required=true, description="the ID of the OS Type that best represents the OS of this template.") - @IdentityMapper(entityTableName="guest_os") + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType = GuestOSResponse.class, + required=true, description="the ID of the OS Type that best represents the OS of this template.") private Long osTypeId; @Parameter(name=ApiConstants.PASSWORD_ENABLED, type=CommandType.BOOLEAN, description="true if the template supports the password reset feature; default is false") private Boolean passwordEnabled; - + @Parameter(name=ApiConstants.SSHKEY_ENABLED, type=CommandType.BOOLEAN, description="true if the template supports the sshkey upload feature; default is false") private Boolean sshKeyEnabled; @@ -87,12 +89,12 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the template is hosted. Possible URL include http:// and https://") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone the template is to be hosted on") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone the template is to be hosted on") private Long zoneId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") private Long domainId; @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") @@ -103,11 +105,11 @@ public class RegisterTemplateCmd extends BaseCmd { @Parameter(name=ApiConstants.TEMPLATE_TAG, type=CommandType.STRING, description="the tag for this template.") private String templateTag; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Register template for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="Register template for the project") private Long projectId; - + @Parameter(name=ApiConstants.DETAILS, type=CommandType.MAP, description="Template details in key/value pairs.") protected Map details; @@ -150,7 +152,7 @@ public class RegisterTemplateCmd extends BaseCmd { public Boolean isPasswordEnabled() { return passwordEnabled; } - + public Boolean isSshKeyEnabled() { return sshKeyEnabled; } @@ -181,22 +183,22 @@ public class RegisterTemplateCmd extends BaseCmd { public String getChecksum() { return checksum; - } + } public String getTemplateTag() { return templateTag; } - + public Map getDetails() { - if (details == null || details.isEmpty()) { - return null; - } - - Collection paramsCollection = details.values(); - Map params = (Map) (paramsCollection.toArray())[0]; - return params; + if (details == null || details.isEmpty()) { + return null; + } + + Collection paramsCollection = details.values(); + Map params = (Map) (paramsCollection.toArray())[0]; + return params; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -216,9 +218,9 @@ public class RegisterTemplateCmd extends BaseCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; - } + } @Override public void execute() throws ResourceAllocationException{ @@ -228,7 +230,7 @@ public class RegisterTemplateCmd extends BaseCmd { ListResponse response = new ListResponse(); List templateResponses = _responseGenerator.createTemplateResponses(template.getId(), zoneId, false); response.setResponses(templateResponses); - response.setResponseName(getCommandName()); + response.setResponseName(getCommandName()); this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to register template"); diff --git a/api/src/com/cloud/api/commands/UpdateTemplateCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/commands/UpdateTemplateCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java index 47440e2b0d7..01ea200293e --- a/api/src/com/cloud/api/commands/UpdateTemplateCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplateCmd.java @@ -14,26 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.TemplateResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.TemplateResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(description="Updates attributes of a template.", responseObject=TemplateResponse.class) -public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { - public static final Logger s_logger = Logger.getLogger(UpdateTemplateCmd.class.getName()); +@APICommand(name = "updateTemplate", description="Updates attributes of a template.", responseObject=TemplateResponse.class) +public class UpdateTemplateCmd extends BaseUpdateTemplateOrIsoCmd { + public static final Logger s_logger = Logger.getLogger(UpdateTemplateCmd.class.getName()); private static final String s_name = "updatetemplateresponse"; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + @Override public Boolean isBootable() { return null; @@ -42,17 +43,17 @@ public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; } - + @SuppressWarnings("unchecked") public TemplateResponse getResponse() { return null; } - + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); @@ -62,7 +63,7 @@ public class UpdateTemplateCmd extends UpdateTemplateOrIsoCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ VirtualMachineTemplate result = _mgr.updateTemplate(this); diff --git a/api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java similarity index 50% rename from api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java index b71ed98ab4d..8f3e660bd1a 100644 --- a/api/src/com/cloud/api/commands/UpdateTemplatePermissionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/template/UpdateTemplatePermissionsCmd.java @@ -14,29 +14,30 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.template; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; import org.apache.log4j.Logger; -import com.cloud.api.Implementation; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.template.VirtualMachineTemplate; import com.cloud.user.Account; -@Implementation(responseObject=SuccessResponse.class, description="Updates a template visibility permissions. " + - "A public template is visible to all accounts within the same domain. " + - "A private template is visible only to the owner of the template. " + - "A priviledged template is a private template with account permissions added. " + - "Only accounts specified under the template permissions are visible to them.") -public class UpdateTemplatePermissionsCmd extends UpdateTemplateOrIsoPermissionsCmd { +@APICommand(name = "updateTemplatePermissions", responseObject=SuccessResponse.class, description="Updates a template visibility permissions. " + + "A public template is visible to all accounts within the same domain. " + + "A private template is visible only to the owner of the template. " + + "A priviledged template is a private template with account permissions added. " + + "Only accounts specified under the template permissions are visible to them.") +public class UpdateTemplatePermissionsCmd extends BaseUpdateTemplateOrIsoPermissionsCmd { protected String getResponseName() { - return "updatetemplatepermissionsresponse"; + return "updatetemplatepermissionsresponse"; } - - protected Logger getLogger() { - return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName()); - } - + + protected Logger getLogger() { + return Logger.getLogger(UpdateTemplatePermissionsCmd.class.getName()); + } + @Override public long getEntityOwnerId() { VirtualMachineTemplate template = _entityMgr.findById(VirtualMachineTemplate.class, getId()); diff --git a/api/src/com/cloud/api/commands/DeployVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/DeployVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java index f67ee8f6003..349f4a12d16 100644 --- a/api/src/com/cloud/api/commands/DeployVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DeployVMCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.Collection; @@ -24,16 +24,21 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; @@ -44,6 +49,8 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.IpAddress; +import com.cloud.network.Network; import com.cloud.offering.DiskOffering; import com.cloud.offering.ServiceOffering; import com.cloud.template.VirtualMachineTemplate; @@ -51,7 +58,8 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) + +@APICommand(name = "deployVirtualMachine", description="Creates and automatically starts a virtual machine based on a service offering, disk offering, and template.", responseObject=UserVmResponse.class) public class DeployVMCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(DeployVMCmd.class.getName()); @@ -61,16 +69,18 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="availability zone for the virtual machine") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="availability zone for the virtual machine") private Long zoneId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the ID of the service offering for the virtual machine") + @ACL + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=ServiceOfferingResponse.class, + required=true, description="the ID of the service offering for the virtual machine") private Long serviceOfferingId; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, required=true, description="the ID of the template for the virtual machine") + @ACL + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType=TemplateResponse.class, + required=true, description="the ID of the template for the virtual machine") private Long templateId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="host name for the virtual machine") @@ -83,18 +93,24 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the virtual machine. Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the virtual machine. If the account parameter is used, domainId must also be used.") private Long domainId; //Network information - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") + @ACL + @Parameter(name=ApiConstants.NETWORK_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=NetworkResponse.class, + description="list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter") private List networkIds; //DataDisk information - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.LONG, description="the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateId parameter passed is from a Template object, the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") + @ACL + @Parameter(name=ApiConstants.DISK_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the ID of the disk offering for the virtual machine. If the template is of ISO format," + + " the diskOfferingId is for the root disk volume. Otherwise this parameter is used to indicate the " + + "offering for the data disk volume. If the templateId parameter passed is from a Template object," + + " the diskOfferingId refers to a DATA Disk Volume created. If the templateId parameter passed is " + + "from an ISO object, the diskOfferingId refers to a ROOT Disk Volume created.") private Long diskOfferingId; @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="the arbitrary size for the DATADISK volume. Mutually exclusive with diskOfferingId") @@ -112,42 +128,53 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.SSH_KEYPAIR, type=CommandType.STRING, description="name of the ssh key pair used to login to the virtual machine") private String sshKeyPairName; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="destination Host ID to deploy the VM to - parameter available for root admin only") private Long hostId; - - @IdentityMapper(entityTableName="security_group") - @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.LONG, description="comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter") + + @ACL + @Parameter(name=ApiConstants.SECURITY_GROUP_IDS, type=CommandType.LIST, collectionType=CommandType.UUID, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups id that going to be applied to the virtual machine. " + + "Should be passed only when vm is created from a zone with Basic Network support." + + " Mutually exclusive with securitygroupnames parameter") private List securityGroupIdList; - - @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter") + + @ACL + @Parameter(name=ApiConstants.SECURITY_GROUP_NAMES, type=CommandType.LIST, collectionType=CommandType.STRING, entityType=SecurityGroupResponse.class, + description="comma separated list of security groups names that going to be applied to the virtual machine." + + " Should be passed only when vm is created from a zone with Basic Network support. " + + "Mutually exclusive with securitygroupids parameter") private List securityGroupNameList; - - @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, description = "ip to network mapping. Can't be specified with networkIds parameter. Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=204 - requests to use ip 10.10.10.11 in network id=204") + + @ACL(checkKeyAccess=true) + @Parameter(name = ApiConstants.IP_NETWORK_LIST, type = CommandType.MAP, entityType={Network.class,IpAddress.class}, + description = "ip to network mapping. Can't be specified with networkIds parameter." + + " Example: iptonetworklist[0].ip=10.10.10.11&iptonetworklist[0].networkid=204 - requests to" + + " use ip 10.10.10.11 in network id=204") private Map ipToNetworkList; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="the ip address for default vm's network") private String ipAddress; - + @Parameter(name=ApiConstants.KEYBOARD, type=CommandType.STRING, description="an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us") private String keyboard; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="Deploy vm for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="Deploy vm for the project") private Long projectId; - + @Parameter(name=ApiConstants.START_VM, type=CommandType.BOOLEAN, description="true if network offering supports specifying ip ranges; defaulted to true if not specified") private Boolean startVm; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getEntityTable() { - return "vm_instance"; + return "vm_instance"; } - + public String getAccountName() { if (accountName == null) { return UserContext.current().getCaller().getAccountName(); @@ -174,7 +201,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { return group; } - public HypervisorType getHypervisor() { + public HypervisorType getHypervisor() { return HypervisorType.getType(hypervisor); } @@ -182,7 +209,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (securityGroupNameList != null && securityGroupIdList != null) { throw new InvalidParameterValueException("securitygroupids parameter is mutually exclusive with securitygroupnames parameter"); } - + //transform group names to ids here if (securityGroupNameList != null) { List securityGroupIds = new ArrayList(); @@ -193,7 +220,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { securityGroupIds.add(groupId); } - } + } return securityGroupIds; } else { return securityGroupIdList; @@ -244,11 +271,11 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { public Long getHostId() { return hostId; } - + public boolean getStartVm() { return startVm == null ? true : startVm; } - + private Map getIpToNetworkMap() { if ((networkIds != null || ipAddress != null) && ipToNetworkList != null) { throw new InvalidParameterValueException("NetworkIds and ipAddress can't be specified along with ipToNetworkMap parameter"); @@ -265,7 +292,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { ipToNetworkMap.put(networkId, requestedIp); } } - + return ipToNetworkMap; } @@ -288,7 +315,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -320,7 +347,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { @Override public void execute(){ UserVm result; - + if (getStartVm()) { try { UserContext.current().setEventDetails("Vm Id: "+getEntityId()); @@ -334,7 +361,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); @@ -343,7 +370,7 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } else { result = _userVmService.getUserVm(getEntityId()); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); @@ -432,7 +459,6 @@ public class DeployVMCmd extends BaseAsyncCreateCmd { } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); - } + } } - } diff --git a/api/src/com/cloud/api/commands/DestroyVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java similarity index 80% rename from api/src/com/cloud/api/commands/DestroyVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java index 1f7a2bf68a7..db830d1a188 100644 --- a/api/src/com/cloud/api/commands/DestroyVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/DestroyVMCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -35,7 +30,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Destroys a virtual machine. Once destroyed, only the administrator can recover it.", responseObject=UserVmResponse.class) +@APICommand(name = "destroyVirtualMachine", description="Destroys a virtual machine. Once destroyed, only the administrator can recover it.", responseObject=UserVmResponse.class) public class DestroyVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DestroyVMCmd.class.getName()); @@ -45,8 +40,8 @@ public class DestroyVMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -85,13 +80,13 @@ public class DestroyVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "destroying vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -99,11 +94,11 @@ public class DestroyVMCmd extends BaseAsyncCmd { UserContext.current().setEventDetails("Vm Id: "+getId()); UserVm result; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.destroyVm(this); + result = _bareMetalVmService.destroyVm(this); } else { - result = _userVmService.destroyVm(this); + result = _userVmService.destroyVm(this); } - + if (result != null) { UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName("virtualmachine"); diff --git a/api/src/com/cloud/api/commands/GetVMPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java similarity index 66% rename from api/src/com/cloud/api/commands/GetVMPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java index a6a3c6d011c..cd3a5609d8c 100644 --- a/api/src/com/cloud/api/commands/GetVMPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/GetVMPasswordCmd.java @@ -14,36 +14,36 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.security.InvalidParameterException; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.GetVMPasswordResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.GetVMPasswordResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.user.Account; import com.cloud.uservm.UserVm; -@Implementation(responseObject=GetVMPasswordResponse.class, description="Returns an encrypted password for the VM") +@APICommand(name = "getVMPassword", responseObject=GetVMPasswordResponse.class, description="Returns an encrypted password for the VM") public class GetVMPasswordCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GetVMPasswordCmd.class.getName()); private static final String s_name = "getvmpasswordresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class + , required=true, description="The ID of the virtual machine") private Long id; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -52,20 +52,20 @@ public class GetVMPasswordCmd extends BaseCmd { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - - @Override - public void execute() { - String passwd = _mgr.getVMPassword(this); - if (passwd == null || passwd.equals("")) - throw new InvalidParameterException("No password for VM with id '" + getId() + "' found."); - - this.setResponseObject(new GetVMPasswordResponse(getCommandName(), passwd)); - } - + + @Override + public void execute() { + String passwd = _mgr.getVMPassword(this); + if (passwd == null || passwd.equals("")) + throw new InvalidParameterException("No password for VM with id '" + getId() + "' found."); + + this.setResponseObject(new GetVMPasswordResponse(getCommandName(), passwd)); + } + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -76,9 +76,8 @@ public class GetVMPasswordCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - @Override - public String getCommandName() { - return s_name; - } - + @Override + public String getCommandName() { + return s_name; + } } diff --git a/api/src/com/cloud/api/commands/ListVMsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java old mode 100755 new mode 100644 similarity index 58% rename from api/src/com/cloud/api/commands/ListVMsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java index 37dfcd32620..b74c8e70f13 --- a/api/src/com/cloud/api/commands/ListVMsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ListVMsCmd.java @@ -14,7 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import java.util.ArrayList; import java.util.EnumSet; @@ -22,19 +22,29 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IsoVmResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; + import com.cloud.async.AsyncJob; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.uservm.UserVm; -@Implementation(description="List the virtual machines owned by the account.", responseObject=UserVmResponse.class) + +@APICommand(name = "listVirtualMachines", description="List the virtual machines owned by the account.", responseObject=UserVmResponse.class) public class ListVMsCmd extends BaseListTaggedResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListVMsCmd.class.getName()); @@ -44,60 +54,63 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.GROUP_ID, type=CommandType.LONG, description="the group ID") + @Parameter(name=ApiConstants.GROUP_ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + description="the group ID") private Long groupId; - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="the host ID") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="the host ID") private Long hostId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="name of the virtual machine") private String instanceName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the pod ID") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the pod ID") private Long podId; @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="state of the virtual machine") private String state; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the availability zone ID") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the availability zone ID") private Long zoneId; - - @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, description="list by network type; true if need to list vms using Virtual Network, false otherwise") + + @Parameter(name=ApiConstants.FOR_VIRTUAL_NETWORK, type=CommandType.BOOLEAN, + description="list by network type; true if need to list vms using Virtual Network, false otherwise") private Boolean forVirtualNetwork; - - @IdentityMapper(entityTableName="networks") - @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.LONG, description="list by network id") + + @Parameter(name=ApiConstants.NETWORK_ID, type=CommandType.UUID, entityType=NetworkResponse.class, + description="list by network id") private Long networkId; @Parameter(name=ApiConstants.HYPERVISOR, type=CommandType.STRING, description="the target hypervisor for the template") private String hypervisor; - - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, description="the storage ID where vm's volumes belong to") + + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + description="the storage ID where vm's volumes belong to") private Long storageId; - @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, description="comma separated list of host details requested, " + - "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]. If no parameter is passed in, the details will be defaulted to all" ) - private List viewDetails; + @Parameter(name=ApiConstants.DETAILS, type=CommandType.LIST, collectionType=CommandType.STRING, + description="comma separated list of host details requested, " + + "value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, iso, volume, min]." + + " If no parameter is passed in, the details will be defaulted to all" ) + private List viewDetails; - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.LONG, description="list vms by template") + @Parameter(name=ApiConstants.TEMPLATE_ID, type=CommandType.UUID, entityType=TemplateResponse.class, + description="list vms by template") private Long templateId; - - @IdentityMapper(entityTableName="vm_template") - @Parameter(name=ApiConstants.ISO_ID, type=CommandType.LONG, description="list vms by iso") + + @Parameter(name=ApiConstants.ISO_ID, type=CommandType.UUID, entityType=IsoVmResponse.class, + description="list vms by iso") private Long isoId; - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list vms by vpc") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list vms by vpc") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -130,7 +143,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + public Boolean getForVirtualNetwork() { return forVirtualNetwork; } @@ -138,15 +151,15 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - + public Long getNetworkId() { return networkId; } - + public String getHypervisor() { - return hypervisor; - } - + return hypervisor; + } + public Long getStorageId() { return storageId; } @@ -154,7 +167,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getTemplateId() { return templateId; } - + public Long getIsoId() { return isoId; } @@ -162,7 +175,7 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { public Long getVpcId(){ return vpcId; } - + public EnumSet getDetails() throws InvalidParameterValueException { EnumSet dv; if (viewDetails==null || viewDetails.size() <=0){ @@ -182,34 +195,24 @@ public class ListVMsCmd extends BaseListTaggedResourcesCmd { } return dv; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } - + + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - @Override + @Override public void execute(){ - List result = _userVmService.searchForUserVMs(this); - ListResponse response = new ListResponse(); - EnumSet details = getDetails(); - List vmResponses; - if (details.contains(VMDetails.all)){ // for all use optimized version - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", result.toArray(new UserVm[result.size()])); - } - else { - vmResponses = _responseGenerator.createUserVmResponse("virtualmachine", getDetails(), result.toArray(new UserVm[result.size()])); - } - response.setResponses(vmResponses); + ListResponse response = _queryService.searchForUserVMs(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } - } diff --git a/api/src/com/cloud/api/commands/RebootVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/RebootVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java index 9d8a18c0450..45ebc287913 100644 --- a/api/src/com/cloud/api/commands/RebootVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RebootVMCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -35,17 +34,17 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Reboots a virtual machine.", responseObject=UserVmResponse.class) +@APICommand(name = "rebootVirtualMachine", description="Reboots a virtual machine.", responseObject=UserVmResponse.class) public class RebootVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RebootVMCmd.class.getName()); private static final String s_name = "rebootvirtualmachineresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; ///////////////////////////////////////////////////// @@ -84,25 +83,25 @@ public class RebootVMCmd extends BaseAsyncCmd { public String getEventDescription() { return "rebooting user vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } - + @Override public void execute() throws ResourceUnavailableException, InsufficientCapacityException{ UserContext.current().setEventDetails("Vm Id: "+getId()); UserVm result; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { - result = _bareMetalVmService.rebootVirtualMachine(this); + result = _bareMetalVmService.rebootVirtualMachine(this); } else { - result = _userVmService.rebootVirtualMachine(this); + result = _userVmService.rebootVirtualMachine(this); } - + if (result !=null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); response.setResponseName(getCommandName()); diff --git a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/ResetVMPasswordCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java index 1c036c81b20..a4c2b3772e9 100644 --- a/api/src/com/cloud/api/commands/ResetVMPasswordCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/ResetVMPasswordCmd.java @@ -14,18 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InsufficientCapacityException; @@ -34,20 +33,20 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject=UserVmResponse.class, description="Resets the password for virtual machine. " + - "The virtual machine must be in a \"Stopped\" state and the template must already " + - "support this feature for this command to take effect. [async]") +@APICommand(name = "resetPasswordForVirtualMachine", responseObject=UserVmResponse.class, description="Resets the password for virtual machine. " + + "The virtual machine must be in a \"Stopped\" state and the template must already " + + "support this feature for this command to take effect. [async]") public class ResetVMPasswordCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ResetVMPasswordCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ResetVMPasswordCmd.class.getName()); + + private static final String s_name = "resetpasswordforvirtualmachineresponse"; - private static final String s_name = "resetpasswordforvirtualmachineresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; // unexposed parameter needed for serializing/deserializing the command @@ -75,9 +74,9 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; - } + public String getCommandName() { + return s_name; + } @Override public long getEntityOwnerId() { @@ -98,13 +97,13 @@ public class ResetVMPasswordCmd extends BaseAsyncCmd { public String getEventDescription() { return "resetting password for vm: " + getId(); } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.VirtualMachine; + return AsyncJob.Type.VirtualMachine; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override diff --git a/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java new file mode 100644 index 00000000000..9b2452e355d --- /dev/null +++ b/api/src/org/apache/cloudstack/api/command/user/vm/RestoreVMCmd.java @@ -0,0 +1,88 @@ +// 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 org.apache.cloudstack.api.command.user.vm; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.event.EventTypes; +import com.cloud.exception.ConcurrentOperationException; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.uservm.UserVm; + +@APICommand(name = "restoreVirtualMachine", description="Restore a VM to original template or specific snapshot", responseObject=UserVmResponse.class, since="3.0.0") +public class RestoreVMCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(RestoreVMCmd.class); + private static final String s_name = "restorevmresponse"; + + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="Virtual Machine ID") + private Long vmId; + + @Override + public String getEventType() { + return EventTypes.EVENT_VM_RESTORE; + } + + @Override + public String getEventDescription() { + return "Restore a VM to orignal template or specific snapshot"; + } + + @Override + public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, + ResourceAllocationException { + UserVm result; + UserContext.current().setEventDetails("Vm Id: " + getVmId()); + result = _userVmService.restoreVM(this); + if (result != null) { + UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restore vm " + getVmId()); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + UserVm vm = _responseGenerator.findUserVmById(getVmId()); + if (vm == null) { + return Account.ACCOUNT_ID_SYSTEM; // bad id given, parent this command to SYSTEM so ERROR events are tracked + } + return vm.getAccountId(); + } + + public long getVmId() { + return vmId; + } +} diff --git a/api/src/com/cloud/api/commands/StartVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/StartVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java index c77213fd5f9..36199d13c24 100644 --- a/api/src/com/cloud/api/commands/StartVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StartVMCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +36,7 @@ import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; import com.cloud.utils.exception.ExecutionException; -@Implementation(responseObject = UserVmResponse.class, description = "Starts a virtual machine.") +@APICommand(name = "startVirtualMachine", responseObject = UserVmResponse.class, description = "Starts a virtual machine.") public class StartVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StartVMCmd.class.getName()); @@ -49,12 +46,12 @@ public class StartVMCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=UserVmResponse.class, + required = true, description = "The ID of the virtual machine") private Long id; - - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="destination Host ID to deploy the VM to - parameter available for root admin only", since="3.0.1") + + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="destination Host ID to deploy the VM to - parameter available for root admin only", since="3.0.1") private Long hostId; // /////////////////////////////////////////////////// @@ -64,10 +61,10 @@ public class StartVMCmd extends BaseAsyncCmd { public Long getId() { return id; } - + public Long getHostId() { return hostId; - } + } // /////////////////////////////////////////////////// // ///////////// API Implementation/////////////////// @@ -115,7 +112,7 @@ public class StartVMCmd extends BaseAsyncCmd { public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ResourceAllocationException { try { UserContext.current().setEventDetails("Vm Id: " + getId()); - + UserVm result ; if (_userVmService.getHypervisorTypeOfUserVM(getId()) == HypervisorType.BareMetal) { result = _bareMetalVmService.startVirtualMachine(this); diff --git a/api/src/com/cloud/api/commands/StopVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java similarity index 86% rename from api/src/com/cloud/api/commands/StopVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java index eaa617a4c69..8e589060520 100644 --- a/api/src/com/cloud/api/commands/StopVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/StopVMCmd.java @@ -14,18 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -34,7 +29,7 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject = UserVmResponse.class, description = "Stops a virtual machine.") +@APICommand(name = "stopVirtualMachine", responseObject = UserVmResponse.class, description = "Stops a virtual machine.") public class StopVMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(StopVMCmd.class.getName()); @@ -44,8 +39,9 @@ public class StopVMCmd extends BaseAsyncCmd { // ////////////// API parameters ///////////////////// // /////////////////////////////////////////////////// - @IdentityMapper(entityTableName = "vm_instance") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required = true, description = "The ID of the virtual machine") + @ACL + @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType=UserVmResponse.class, + required = true, description = "The ID of the virtual machine") private Long id; @Parameter(name = ApiConstants.FORCED, type = CommandType.BOOLEAN, required = false, description = "Force stop the VM " + diff --git a/api/src/com/cloud/api/commands/UpdateVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/UpdateVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java index 38d22730050..7f1e7efdc1a 100644 --- a/api/src/com/cloud/api/commands/UpdateVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpdateVMCmd.java @@ -14,29 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; + +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.exception.InsufficientCapacityException; +import com.cloud.exception.ResourceUnavailableException; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Updates properties of a virtual machine. The VM has to be stopped and restarted for the " + - "new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. " + - "Therefore, stop the VM manually before issuing this call.", responseObject=UserVmResponse.class) -public class UpdateVMCmd extends BaseCmd{ - public static final Logger s_logger = Logger.getLogger(UpdateVMCmd.class.getName()); - private static final String s_name = "updatevirtualmachineresponse"; - +@APICommand(name = "updateVirtualMachine", description="Updates properties of a virtual machine. The VM has to be stopped and restarted for the " + + "new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. " + + "Therefore, stop the VM manually before issuing this call.", responseObject=UserVmResponse.class) +public class UpdateVMCmd extends BaseCmd{ + public static final Logger s_logger = Logger.getLogger(UpdateVMCmd.class.getName()); + private static final String s_name = "updatevirtualmachineresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @@ -50,17 +53,17 @@ public class UpdateVMCmd extends BaseCmd{ @Parameter(name=ApiConstants.HA_ENABLE, type=CommandType.BOOLEAN, description="true if high-availability is enabled for the virtual machine, false otherwise") private Boolean haEnable; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; - - @IdentityMapper(entityTableName="guest_os") - @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.LONG, description="the ID of the OS type that best represents this VM.") + + @Parameter(name=ApiConstants.OS_TYPE_ID, type=CommandType.UUID, entityType=GuestOSResponse.class, + description="the ID of the OS type that best represents this VM.") private Long osTypeId; - + @Parameter(name=ApiConstants.USER_DATA, type=CommandType.STRING, description="an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Currently only HTTP GET is supported. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding.", length=2048) private String userData; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -81,7 +84,7 @@ public class UpdateVMCmd extends BaseCmd{ public Long getId() { return id; } - + public String getUserData() { return userData; } @@ -98,11 +101,11 @@ public class UpdateVMCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -114,7 +117,8 @@ public class UpdateVMCmd extends BaseCmd{ } @Override - public void execute(){ + public void execute() throws ResourceUnavailableException, + InsufficientCapacityException, ServerApiException { UserContext.current().setEventDetails("Vm Id: "+getId()); UserVm result = _userVmService.updateVirtualMachine(this); if (result != null){ diff --git a/api/src/com/cloud/api/commands/UpgradeVMCmd.java b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java similarity index 77% rename from api/src/com/cloud/api/commands/UpgradeVMCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java index 56ddb820cb2..f2c3882bd3c 100644 --- a/api/src/com/cloud/api/commands/UpgradeVMCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vm/UpgradeVMCmd.java @@ -14,26 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vm; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.UserVmResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.UserVmResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.offering.ServiceOffering; import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + - "The virtual machine must be in a \"Stopped\" state for " + - "this command to take effect.") +@APICommand(name = "changeServiceForVirtualMachine", responseObject=UserVmResponse.class, description="Changes the service offering for a virtual machine. " + + "The virtual machine must be in a \"Stopped\" state for " + + "this command to take effect.") public class UpgradeVMCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(UpgradeVMCmd.class.getName()); private static final String s_name = "changeserviceforvirtualmachineresponse"; @@ -42,12 +40,12 @@ public class UpgradeVMCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the virtual machine") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description="The ID of the virtual machine") private Long id; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.LONG, required=true, description="the service offering ID to apply to the virtual machine") + @Parameter(name=ApiConstants.SERVICE_OFFERING_ID, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + required=true, description="the service offering ID to apply to the virtual machine") private Long serviceOfferingId; ///////////////////////////////////////////////////// @@ -72,9 +70,9 @@ public class UpgradeVMCmd extends BaseCmd { } public static String getResultObjectName() { - return "virtualmachine"; + return "virtualmachine"; } - + @Override public long getEntityOwnerId() { UserVm userVm = _entityMgr.findById(UserVm.class, getId()); @@ -84,16 +82,16 @@ public class UpgradeVMCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ UserContext.current().setEventDetails("Vm Id: "+getId()); - + ServiceOffering serviceOffering = _configService.getServiceOffering(serviceOfferingId); if (serviceOffering == null) { throw new InvalidParameterValueException("Unable to find service offering: " + serviceOfferingId); } - + UserVm result = _userVmService.upgradeVirtualMachine(this); if (result != null){ UserVmResponse response = _responseGenerator.createUserVmResponse("virtualmachine", result).get(0); diff --git a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/CreateVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java index a5cdcd757f2..9c2c6027ac9 100644 --- a/api/src/com/cloud/api/commands/CreateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/CreateVMGroupCmd.java @@ -14,21 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.APICommand; + +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; import com.cloud.user.UserContext; import com.cloud.vm.InstanceGroup; -@Implementation(description = "Creates a vm group", responseObject = InstanceGroupResponse.class) +@APICommand(name = "createInstanceGroup", description = "Creates a vm group", responseObject = InstanceGroupResponse.class) public class CreateVMGroupCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateVMGroupCmd.class.getName()); @@ -41,15 +40,16 @@ public class CreateVMGroupCmd extends BaseCmd { @Parameter(name = ApiConstants.NAME, type = CommandType.STRING, required = true, description = "the name of the instance group") private String groupName; - @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, description = "the account of the instance group. The account parameter must be used with the domainId parameter.") + @Parameter(name = ApiConstants.ACCOUNT, type = CommandType.STRING, + description = "the account of the instance group. The account parameter must be used with the domainId parameter.") private String accountName; - @IdentityMapper(entityTableName = "domain") - @Parameter(name = ApiConstants.DOMAIN_ID, type = CommandType.LONG, description = "the domain ID of account owning the instance group") + @Parameter(name = ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description = "the domain ID of account owning the instance group") private Long domainId; - @IdentityMapper(entityTableName = "projects") - @Parameter(name = ApiConstants.PROJECT_ID, type = CommandType.LONG, description = "The project of the instance group") + @Parameter(name = ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectAccountResponse.class, + description = "The project of the instance group") private Long projectId; // /////////////////////////////////////////////////// diff --git a/api/src/com/cloud/api/commands/DeleteVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java similarity index 81% rename from api/src/com/cloud/api/commands/DeleteVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java index 18983fb20fa..47c2f764db6 100644 --- a/api/src/com/cloud/api/commands/DeleteVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/DeleteVMGroupCmd.java @@ -14,21 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.user.Account; import com.cloud.vm.InstanceGroup; -@Implementation(description="Deletes a vm group", responseObject=SuccessResponse.class) +@APICommand(name = "deleteInstanceGroup", description="Deletes a vm group", responseObject=SuccessResponse.class) public class DeleteVMGroupCmd extends BaseCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVMGroupCmd.class.getName()); private static final String s_name = "deleteinstancegroupresponse"; @@ -37,8 +35,8 @@ public class DeleteVMGroupCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the instance group") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + required=true, description="the ID of the instance group") private Long id; ///////////////////////////////////////////////////// @@ -57,7 +55,7 @@ public class DeleteVMGroupCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { InstanceGroup group = _entityMgr.findById(InstanceGroup.class, getId()); @@ -67,7 +65,7 @@ public class DeleteVMGroupCmd extends BaseCmd{ return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute(){ boolean result = _userVmService.deleteVmGroup(this); diff --git a/api/src/com/cloud/api/commands/ListVMGroupsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/ListVMGroupsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java index 33cc9273f04..8a581b02e12 100644 --- a/api/src/com/cloud/api/commands/ListVMGroupsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/ListVMGroupsCmd.java @@ -14,23 +14,18 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.vmgroup; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.vm.InstanceGroup; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; -@Implementation(description="Lists vm groups", responseObject=InstanceGroupResponse.class) +@APICommand(name = "listInstanceGroups", description="Lists vm groups", responseObject=InstanceGroupResponse.class) public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger(ListVMGroupsCmd.class.getName()); @@ -40,8 +35,8 @@ public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list instance groups by ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + description="list instance groups by ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list instance groups by name") @@ -64,22 +59,13 @@ public class ListVMGroupsCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { + public String getCommandName() { return s_name; } @Override public void execute(){ - List groups = _mgr.searchForVmGroups(this); - ListResponse response = new ListResponse(); - List responses = new ArrayList(); - for (InstanceGroup group : groups) { - InstanceGroupResponse groupResponse = _responseGenerator.createInstanceGroupResponse(group); - groupResponse.setObjectName("instancegroup"); - responses.add(groupResponse); - } - - response.setResponses(responses); + ListResponse response = _queryService.searchForVmGroups(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/UpdateVMGroupCmd.java b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVMGroupCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java index 27057d48e73..09313c0f797 100644 --- a/api/src/com/cloud/api/commands/UpdateVMGroupCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vmgroup/UpdateVMGroupCmd.java @@ -14,21 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vmgroup; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.InstanceGroupResponse; import com.cloud.user.Account; import com.cloud.vm.InstanceGroup; -@Implementation(description="Updates a vm group", responseObject=InstanceGroupResponse.class) +@APICommand(name = "updateInstanceGroup", description="Updates a vm group", responseObject=InstanceGroupResponse.class) public class UpdateVMGroupCmd extends BaseCmd{ private static final String s_name = "updateinstancegroupresponse"; @@ -38,8 +34,8 @@ public class UpdateVMGroupCmd extends BaseCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="instance_group") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Instance group ID") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=InstanceGroupResponse.class, + required=true, description="Instance group ID") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="new instance group name") @@ -65,7 +61,7 @@ public class UpdateVMGroupCmd extends BaseCmd{ public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { InstanceGroup group = _entityMgr.findById(InstanceGroup.class, getId()); diff --git a/api/src/com/cloud/api/commands/AttachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java old mode 100755 new mode 100644 similarity index 63% rename from api/src/com/cloud/api/commands/AttachVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java index bfd1a84865e..e48e4e43093 --- a/api/src/com/cloud/api/commands/AttachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/AttachVolumeCmd.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Attaches a disk volume to a virtual machine.", responseObject=VolumeResponse.class) +@APICommand(name = "attachVolume", description="Attaches a disk volume to a virtual machine.", responseObject=VolumeResponse.class) public class AttachVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(AttachVolumeCmd.class.getName()); private static final String s_name = "attachvolumeresponse"; ///////////////////////////////////////////////////// @@ -42,24 +42,24 @@ public class AttachVolumeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.DEVICE_ID, type=CommandType.LONG, description="the ID of the device to map the volume to within the guest OS. " + - "If no deviceId is passed in, the next available deviceId will be chosen. " + - "Possible values for a Linux OS are:" + - "* 1 - /dev/xvdb" + - "* 2 - /dev/xvdc" + - "* 4 - /dev/xvde" + - "* 5 - /dev/xvdf" + - "* 6 - /dev/xvdg" + - "* 7 - /dev/xvdh" + - "* 8 - /dev/xvdi" + - "* 9 - /dev/xvdj") + "If no deviceId is passed in, the next available deviceId will be chosen. " + + "Possible values for a Linux OS are:" + + "* 1 - /dev/xvdb" + + "* 2 - /dev/xvdc" + + "* 4 - /dev/xvde" + + "* 5 - /dev/xvdf" + + "* 6 - /dev/xvdg" + + "* 7 - /dev/xvdh" + + "* 8 - /dev/xvdi" + + "* 9 - /dev/xvdj") private Long deviceId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the disk volume") private Long id; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, required=true, description=" the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + required=true, description=" the ID of the virtual machine") private Long virtualMachineId; @@ -88,13 +88,13 @@ public class AttachVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -115,7 +115,7 @@ public class AttachVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "attaching volume: " + getId() + " to vm: " + getVirtualMachineId(); } - + @Override public void execute(){ UserContext.current().setEventDetails("Volume Id: "+getId()+" VmId: "+getVirtualMachineId()); diff --git a/api/src/com/cloud/api/commands/CreateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/CreateVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java index d0585fe1547..512685f77f6 100644 --- a/api/src/com/cloud/api/commands/CreateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/CreateVolumeCmd.java @@ -14,27 +14,27 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceAllocationException; +import com.cloud.storage.Snapshot; import com.cloud.storage.Volume; import com.cloud.user.UserContext; -@Implementation(responseObject=VolumeResponse.class, description="Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.") +@APICommand(name = "createVolume", responseObject=VolumeResponse.class, description="Creates a disk volume from a disk offering. This disk volume must still be attached to a virtual machine to make use of it.") public class CreateVolumeCmd extends BaseAsyncCreateCmd { - public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(CreateVolumeCmd.class.getName()); private static final String s_name = "createvolumeresponse"; ///////////////////////////////////////////////////// @@ -43,17 +43,18 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the disk volume. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="the project associated with the volume. Mutually exclusive with account parameter") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="the project associated with the volume. Mutually exclusive with account parameter") private Long projectId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the disk offering. If used with the account parameter returns the disk volume associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the disk offering. If used with the account parameter" + + " returns the disk volume associated with the account for the specified domain.") private Long domainId; - @IdentityMapper(entityTableName="disk_offering") - @Parameter(name=ApiConstants.DISK_OFFERING_ID,required = false, type=CommandType.LONG, description="the ID of the disk offering. Either diskOfferingId or snapshotId must be passed in.") + @Parameter(name=ApiConstants.DISK_OFFERING_ID,required = false, type=CommandType.UUID, entityType=DiskOfferingResponse.class, + description="the ID of the disk offering. Either diskOfferingId or snapshotId must be passed in.") private Long diskOfferingId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the disk volume") @@ -62,21 +63,21 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { @Parameter(name=ApiConstants.SIZE, type=CommandType.LONG, description="Arbitrary volume size") private Long size; - @IdentityMapper(entityTableName="snapshots") - @Parameter(name=ApiConstants.SNAPSHOT_ID, type=CommandType.LONG, description="the snapshot ID for the disk volume. Either diskOfferingId or snapshotId must be passed in.") + @Parameter(name=ApiConstants.SNAPSHOT_ID, type=CommandType.UUID, entityType=SnapshotResponse.class, + description="the snapshot ID for the disk volume. Either diskOfferingId or snapshotId must be passed in.") private Long snapshotId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the availability zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the ID of the availability zone") private Long zoneId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getEntityTable() { - return "volumes"; + return "volumes"; } public String getAccountName() { @@ -118,22 +119,22 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "volume"; + return "volume"; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + @Override public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } @@ -146,7 +147,7 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { public String getEventDescription() { return "creating volume: " + getVolumeName() + ((getSnapshotId() == null) ? "" : " from snapshot: " + getSnapshotId()); } - + @Override public void create() throws ResourceAllocationException{ @@ -155,9 +156,9 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { this.setEntityId(volume.getId()); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create volume"); - } + } } - + @Override public void execute(){ UserContext.current().setEventDetails("Volume Id: "+getEntityId()+((getSnapshotId() == null) ? "" : " from snapshot: " + getSnapshotId())); @@ -165,7 +166,18 @@ public class CreateVolumeCmd extends BaseAsyncCreateCmd { if (volume != null) { VolumeResponse response = _responseGenerator.createVolumeResponse(volume); //FIXME - have to be moved to ApiResponseHelper - response.setSnapshotId(getSnapshotId()); // if the volume was created from a snapshot, snapshotId will be set so we pass it back in the response + if (getSnapshotId() != null) { + Snapshot snap = _entityMgr.findById(Snapshot.class, getSnapshotId()); + if (snap != null) { + response.setSnapshotId(snap.getUuid()); // if the volume was + // created from a + // snapshot, + // snapshotId will + // be set so we pass + // it back in the + // response + } + } response.setResponseName(getCommandName()); this.setResponseObject(response); } else { diff --git a/api/src/com/cloud/api/commands/DeleteVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/DeleteVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java index a998311321a..2b2e94cab6b 100644 --- a/api/src/com/cloud/api/commands/DeleteVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DeleteVolumeCmd.java @@ -14,33 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.VolumeResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +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.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Deletes a detached disk volume.", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVolume", description="Deletes a detached disk volume.", responseObject=SuccessResponse.class) public class DeleteVolumeCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DeleteVolumeCmd.class.getName()); private static final String s_name = "deletevolumeresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="The ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="The ID of the disk volume") private Long id; @@ -63,9 +63,9 @@ public class DeleteVolumeCmd extends BaseCmd { } public static String getResultObjectName() { - return "volume"; + return "volume"; } - + @Override public long getEntityOwnerId() { Volume volume = _entityMgr.findById(Volume.class, getId()); @@ -75,11 +75,11 @@ public class DeleteVolumeCmd extends BaseCmd { return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked } - + @Override public void execute() throws ConcurrentOperationException { UserContext.current().setEventDetails("Volume Id: "+getId()); - boolean result = _storageService.deleteVolume(id); + boolean result = _storageService.deleteVolume(id, UserContext.current().getCaller()); if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); diff --git a/api/src/com/cloud/api/commands/DetachVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/commands/DetachVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java index 3a3557da8e9..c8ecddea699 --- a/api/src/com/cloud/api/commands/DetachVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/DetachVolumeCmd.java @@ -14,18 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.UserVmResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.storage.Volume; @@ -33,24 +29,24 @@ import com.cloud.user.Account; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; -@Implementation(description="Detaches a disk volume from a virtual machine.", responseObject=VolumeResponse.class) +@APICommand(name = "detachVolume", description="Detaches a disk volume from a virtual machine.", responseObject=VolumeResponse.class) public class DetachVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(DetachVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(DetachVolumeCmd.class.getName()); private static final String s_name = "detachvolumeresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + description="the ID of the disk volume") private Long id; @Parameter(name=ApiConstants.DEVICE_ID, type=CommandType.LONG, description="the device ID on the virtual machine where volume is detached from") private Long deviceId; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine where the volume is detached from") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine where the volume is detached from") private Long virtualMachineId; ///////////////////////////////////////////////////// @@ -77,17 +73,17 @@ public class DetachVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + public static String getResultObjectName() { - return "volume"; + return "volume"; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -139,4 +135,4 @@ public class DetachVolumeCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to detach volume"); } } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java old mode 100755 new mode 100644 similarity index 70% rename from api/src/com/cloud/api/commands/ExtractVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java index 2a9dbff9e70..7f6cd052470 --- a/api/src/com/cloud/api/commands/ExtractVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ExtractVolumeCmd.java @@ -14,20 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; import java.net.URISyntaxException; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExtractResponse; import com.cloud.async.AsyncJob; import com.cloud.dc.DataCenter; import com.cloud.event.EventTypes; @@ -36,9 +37,9 @@ import com.cloud.storage.Volume; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Extracts volume", responseObject=ExtractResponse.class) +@APICommand(name = "extractVolume", description="Extracts volume", responseObject=ExtractResponse.class) public class ExtractVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(ExtractVolumeCmd.class.getName()); + public static final Logger s_logger = Logger.getLogger(ExtractVolumeCmd.class.getName()); private static final String s_name = "extractvolumeresponse"; @@ -46,18 +47,18 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the volume") private Long id; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=false, description="the url to which the volume would be extracted") private String url; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone where the volume is located") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the zone where the volume is located") private Long zoneId; - + @Parameter(name=ApiConstants.MODE, type=CommandType.STRING, required=true, description="the mode of extraction - HTTP_DOWNLOAD or FTP_UPLOAD") private String mode; @@ -76,7 +77,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { public Long getZoneId() { return zoneId; } - + public String getMode() { return mode; } @@ -86,20 +87,20 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; - } - + public String getCommandName() { + return s_name; + } + public static String getStaticName() { return s_name; } - + public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + public Long getInstanceId() { - return getId(); + return getId(); } @Override @@ -122,7 +123,7 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Extraction job"; } - + @Override public void execute(){ try { @@ -133,15 +134,17 @@ public class ExtractVolumeCmd extends BaseAsyncCmd { ExtractResponse response = new ExtractResponse(); response.setResponseName(getCommandName()); response.setObjectName("volume"); - response.setIdentityTableName("volumes"); - response.setId(id); - response.setName(_entityMgr.findById(Volume.class, id).getName()); - response.setZoneId(zoneId); - response.setZoneName(_entityMgr.findById(DataCenter.class, zoneId).getName()); + Volume vol = _entityMgr.findById(Volume.class, id); + response.setId(vol.getUuid()); + response.setName(vol.getName()); + DataCenter zone = _entityMgr.findById(DataCenter.class, id); + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); response.setMode(mode); - response.setUploadId(uploadId); + response.setUploadId(uploadInfo.getUuid()); response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(getEntityOwnerId()); + Account account = _entityMgr.findById(Account.class, getEntityOwnerId()); + response.setAccountId(account.getUuid()); response.setUrl(uploadInfo.getUploadUrl()); this.setResponseObject(response); } else { diff --git a/api/src/com/cloud/api/commands/ListVolumesCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java old mode 100755 new mode 100644 similarity index 60% rename from api/src/com/cloud/api/commands/ListVolumesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java index e0393a9b76b..9ba4f346869 --- a/api/src/com/cloud/api/commands/ListVolumesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/ListVolumesCmd.java @@ -14,60 +14,54 @@ // 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 java.util.ArrayList; -import java.util.List; +package org.apache.cloudstack.api.command.user.volume; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; import com.cloud.async.AsyncJob; -import com.cloud.storage.Volume; -@Implementation(description="Lists all volumes.", responseObject=VolumeResponse.class) -public class ListVolumesCmd extends BaseListTaggedResourcesCmd { - public static final Logger s_logger = Logger.getLogger(ListVolumesCmd.class.getName()); - - private static final String s_name = "listvolumesresponse"; - +@APICommand(name = "listVolumes", description="Lists all volumes.", responseObject=VolumeResponse.class) +public class ListVolumesCmd extends BaseListTaggedResourcesCmd { + public static final Logger s_logger = Logger.getLogger(ListVolumesCmd.class.getName()); + + private static final String s_name = "listvolumesresponse"; + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.HOST_ID, type=CommandType.LONG, description="list volumes on specified host") + @Parameter(name=ApiConstants.HOST_ID, type=CommandType.UUID, entityType=HostResponse.class, + description="list volumes on specified host") private Long hostId; - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the disk volume") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VolumeResponse.class, + description="the ID of the disk volume") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the disk volume") private String volumeName; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_ID, type=CommandType.LONG, description="the pod id the disk volume belongs to") + @Parameter(name=ApiConstants.POD_ID, type=CommandType.UUID, entityType=PodResponse.class, + description="the pod id the disk volume belongs to") private Long podId; @Parameter(name=ApiConstants.TYPE, type=CommandType.STRING, description="the type of disk volume") private String type; - @IdentityMapper(entityTableName="vm_instance") - @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.LONG, description="the ID of the virtual machine") + @Parameter(name=ApiConstants.VIRTUAL_MACHINE_ID, type=CommandType.UUID, entityType=UserVmResponse.class, + description="the ID of the virtual machine") private Long virtualMachineId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="the ID of the availability zone") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="the ID of the availability zone") private Long zoneId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -100,7 +94,7 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { public Long getZoneId() { return zoneId; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -109,25 +103,15 @@ public class ListVolumesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public AsyncJob.Type getInstanceType() { - return AsyncJob.Type.Volume; + return AsyncJob.Type.Volume; } - + @Override public void execute(){ - List volumes = _storageService.searchForVolumes(this); - - ListResponse response = new ListResponse(); - List volResponses = new ArrayList(); - for (Volume volume : volumes) { - VolumeResponse volResponse = _responseGenerator.createVolumeResponse(volume); - volResponse.setObjectName("volume"); - volResponses.add(volResponse); - } - - response.setResponses(volResponses); + ListResponse response = _queryService.searchForVolumes(this); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/MigrateVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java similarity index 57% rename from api/src/com/cloud/api/commands/MigrateVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java index 58f5d917ff2..30e672ada1b 100644 --- a/api/src/com/cloud/api/commands/MigrateVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/MigrateVolumeCmd.java @@ -14,38 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.volume; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.storage.Volume; import com.cloud.user.Account; -@Implementation(description="Migrate volume", responseObject=VolumeResponse.class, since="3.0.0") +@APICommand(name = "migrateVolume", description="Migrate volume", responseObject=VolumeResponse.class, since="3.0.0") public class MigrateVolumeCmd extends BaseAsyncCmd { - private static final String s_name = "migratevolumeresponse"; - - ///////////////////////////////////////////////////// + private static final String s_name = "migratevolumeresponse"; + + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="volumes") - @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.LONG, required=true, description="the ID of the volume") + @Parameter(name=ApiConstants.VOLUME_ID, type=CommandType.UUID, entityType=VolumeResponse.class, + required=true, description="the ID of the volume") private Long volumeId; - @IdentityMapper(entityTableName="storage_pool") - @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.LONG, required=true, description="destination storage pool ID to migrate the volume to") + @Parameter(name=ApiConstants.STORAGE_ID, type=CommandType.UUID, entityType=StoragePoolResponse.class, + required=true, description="destination storage pool ID to migrate the volume to") private Long storageId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +55,7 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { } public Long getStoragePoolId() { - return storageId; + return storageId; } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -65,10 +65,10 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { public String getCommandName() { return s_name; } - + @Override public long getEntityOwnerId() { - Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); + Volume volume = _entityMgr.findById(Volume.class, getVolumeId()); if (volume != null) { return volume.getAccountId(); } @@ -85,22 +85,22 @@ public class MigrateVolumeCmd extends BaseAsyncCmd { public String getEventDescription() { return "Attempting to migrate volume Id: " + getVolumeId() + " to storage pool Id: "+ getStoragePoolId(); } - - + + @Override public void execute(){ - Volume result; - try { - result = _storageService.migrateVolume(getVolumeId(), getStoragePoolId()); - if (result != null) { - VolumeResponse response = _responseGenerator.createVolumeResponse(result); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } - } catch (ConcurrentOperationException e) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate volume: "); - } - + Volume result; + try { + result = _storageService.migrateVolume(getVolumeId(), getStoragePoolId()); + if (result != null) { + VolumeResponse response = _responseGenerator.createVolumeResponse(result); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } + } catch (ConcurrentOperationException e) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to migrate volume: "); + } + } } diff --git a/api/src/com/cloud/api/commands/UploadVolumeCmd.java b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java old mode 100755 new mode 100644 similarity index 61% rename from api/src/com/cloud/api/commands/UploadVolumeCmd.java rename to api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java index 299b04df386..4167ffd6460 --- a/api/src/com/cloud/api/commands/UploadVolumeCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/volume/UploadVolumeCmd.java @@ -14,134 +14,131 @@ // 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 org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VolumeResponse; +package org.apache.cloudstack.api.command.user.volume; + +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.event.EventTypes; -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.Volume; -import com.cloud.user.UserContext; - -@Implementation(description="Uploads a data disk.", responseObject=VolumeResponse.class) -public class UploadVolumeCmd extends BaseAsyncCmd { - public static final Logger s_logger = Logger.getLogger(UploadVolumeCmd.class.getName()); - private static final String s_name = "uploadvolumeresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, required=true, description="the format for the volume. Possible values include QCOW2, OVA, and VHD.") - private String format; - - @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the volume") - private String volumeName; - - @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the volume is hosted. Possible URL include http:// and https://") - private String url; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the zone the volume is to be hosted on") - private Long zoneId; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId. If the account parameter is used, domainId must also be used.") - private Long domainId; - - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") - private String accountName; - - @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this volume") - private String checksum; - - ///////////////////////////////////////////////////// - /////////////////// Accessors /////////////////////// - ///////////////////////////////////////////////////// - - public String getFormat() { - return format; - } - - public String getVolumeName() { - return volumeName; - } - - public String getUrl() { - return url; - } - - public Long getZoneId() { - return zoneId; - } - - public Long getDomainId() { - return domainId; - } - - public String getAccountName() { - return accountName; - } - - public String getChecksum() { - return checksum; - } - - ///////////////////////////////////////////////////// - /////////////// API Implementation/////////////////// - ///////////////////////////////////////////////////// - - @Override - public void execute() throws ResourceUnavailableException, - InsufficientCapacityException, ServerApiException, - ConcurrentOperationException, ResourceAllocationException, - NetworkRuleConflictException { - - Volume volume = _storageService.uploadVolume(this); - if (volume != null){ - VolumeResponse response = _responseGenerator.createVolumeResponse(volume); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload volume"); - } - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - Long accountId = finalyzeAccountId(accountName, domainId, null, true); - if (accountId == null) { - return UserContext.current().getCaller().getId(); - } - - return accountId; - } - - @Override - public String getEventDescription() { - return "uploading volume: " + getVolumeName() + " in the zone " + getZoneId(); - } - - @Override - public String getEventType() { - return EventTypes.EVENT_VOLUME_UPLOAD; - } - -} +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.Volume; +import com.cloud.user.UserContext; + +@APICommand(name = "uploadVolume", description="Uploads a data disk.", responseObject=VolumeResponse.class) +public class UploadVolumeCmd extends BaseAsyncCmd { + public static final Logger s_logger = Logger.getLogger(UploadVolumeCmd.class.getName()); + private static final String s_name = "uploadvolumeresponse"; + + ///////////////////////////////////////////////////// + //////////////// API parameters ///////////////////// + ///////////////////////////////////////////////////// + + @Parameter(name=ApiConstants.FORMAT, type=CommandType.STRING, required=true, description="the format for the volume. Possible values include QCOW2, OVA, and VHD.") + private String format; + + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the volume") + private String volumeName; + + @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required=true, description="the URL of where the volume is hosted. Possible URL include http:// and https://") + private String url; + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required=true, description="the ID of the zone the volume is to be hosted on") + private Long zoneId; + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="an optional domainId. If the account parameter is used, domainId must also be used.") + private Long domainId; + + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional accountName. Must be used with domainId.") + private String accountName; + + @Parameter(name=ApiConstants.CHECKSUM, type=CommandType.STRING, description="the MD5 checksum value of this volume") + private String checksum; + + ///////////////////////////////////////////////////// + /////////////////// Accessors /////////////////////// + ///////////////////////////////////////////////////// + + public String getFormat() { + return format; + } + + public String getVolumeName() { + return volumeName; + } + + public String getUrl() { + return url; + } + + public Long getZoneId() { + return zoneId; + } + + public Long getDomainId() { + return domainId; + } + + public String getAccountName() { + return accountName; + } + + public String getChecksum() { + return checksum; + } + + ///////////////////////////////////////////////////// + /////////////// API Implementation/////////////////// + ///////////////////////////////////////////////////// + + @Override + public void execute() throws ResourceUnavailableException, + InsufficientCapacityException, ServerApiException, + ConcurrentOperationException, ResourceAllocationException, + NetworkRuleConflictException { + + Volume volume = _storageService.uploadVolume(this); + if (volume != null){ + VolumeResponse response = _responseGenerator.createVolumeResponse(volume); + response.setResponseName(getCommandName()); + this.setResponseObject(response); + } else { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to upload volume"); + } + } + + @Override + public String getCommandName() { + return s_name; + } + + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, null, true); + if (accountId == null) { + return UserContext.current().getCaller().getId(); + } + + return accountId; + } + + @Override + public String getEventDescription() { + return "uploading volume: " + getVolumeName() + " in the zone " + getZoneId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_VOLUME_UPLOAD; + } + +} diff --git a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java similarity index 85% rename from api/src/com/cloud/api/commands/CreateStaticRouteCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java index bf287e97200..85a0ae45ae8 100644 --- a/api/src/com/cloud/api/commands/CreateStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateStaticRouteCmd.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.StaticRouteResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -36,16 +36,15 @@ import com.cloud.network.vpc.StaticRoute; import com.cloud.network.vpc.VpcGateway; import com.cloud.user.UserContext; -@Implementation(description="Creates a static route", responseObject=StaticRouteResponse.class) +@APICommand(name = "createStaticRoute", description="Creates a static route", responseObject=StaticRouteResponse.class) public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ private static final String s_name = "createstaticrouteresponse"; public static final Logger s_logger = Logger.getLogger(CreateStaticRouteCmd.class.getName()); - - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, required=true, - description="the gateway id we are creating static route for") + + @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + required=true, description="the gateway id we are creating static route for") private Long gatewayId; - + @Parameter(name = ApiConstants.CIDR, required = true, type = CommandType.STRING, description = "static route cidr") private String cidr; @@ -100,7 +99,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ // State is different after the route is applied, so get new object here route = _entityMgr.findById(StaticRoute.class, getEntityId()); - StaticRouteResponse routeResponse = new StaticRouteResponse(); + StaticRouteResponse routeResponse = new StaticRouteResponse(); if (route != null) { routeResponse = _responseGenerator.createStaticRouteResponse(route); setResponseObject(routeResponse); @@ -113,7 +112,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } } } - + @Override public String getCommandName() { return s_name; @@ -127,7 +126,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } return _vpcService.getVpc(gateway.getVpcId()).getAccountId(); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -141,7 +140,7 @@ public class CreateStaticRouteCmd extends BaseAsyncCreateCmd{ } return gateway.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/CreateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/CreateVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java index 35b526dc5af..df16c8edc88 100644 --- a/api/src/com/cloud/api/commands/CreateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/CreateVPCCmd.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,56 +37,55 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.UserContext; -@Implementation(description="Creates a VPC", responseObject=VpcResponse.class) +@APICommand(name = "createVPC", description="Creates a VPC", responseObject=VpcResponse.class) public class CreateVPCCmd extends BaseAsyncCreateCmd{ public static final Logger s_logger = Logger.getLogger(CreateVPCCmd.class.getName()); private static final String s_name = "createvpcresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the VPC. " + - "Must be used with the domainId parameter.") + "Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the VPC. " + - "If used with the account parameter returns the VPC associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the VPC. " + + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="create VPC for the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="create VPC for the project") private Long projectId; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required=true, description="the ID of the availability zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + required=true, description="the ID of the availability zone") private Long zoneId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=true, description="the name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, required=true, description="the display text of " + "the VPC") private String displayText; - + @Parameter(name=ApiConstants.CIDR, type=CommandType.STRING, required=true, description="the cidr of the VPC. All VPC " + - "guest networks' cidrs should be within this CIDR") + "guest networks' cidrs should be within this CIDR") private String cidr; - - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.LONG, required=true, description="the ID of the VPC offering") + + @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class, + required=true, description="the ID of the VPC offering") private Long vpcOffering; - - @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, + + @Parameter(name=ApiConstants.NETWORK_DOMAIN, type=CommandType.STRING, description="VPC network domain. All networks inside the VPC will belong to this domain") private String networkDomain; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getAccountName() { return accountName; } @@ -103,7 +105,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public String getCidr() { return cidr; } - + public String getDisplayText() { return displayText; } @@ -111,7 +113,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public Long getVpcOffering() { return vpcOffering; } - + public String getNetworkDomain() { return networkDomain; } @@ -126,7 +128,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create a VPC"); } } - + @Override public void execute() { Vpc vpc = null; @@ -139,13 +141,13 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); throw new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, ex.getMessage()); } - + if (vpc != null) { VpcResponse response = _responseGenerator.createVpcResponse(vpc); response.setResponseName(getCommandName()); @@ -171,7 +173,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ public String getEventDescription() { return "creating VPC. Id: " + getEntityId(); } - + @Override public String getCommandName() { return s_name; @@ -183,7 +185,7 @@ public class CreateVPCCmd extends BaseAsyncCreateCmd{ if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } } diff --git a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java index fa3c04dd257..c9e4463db14 100644 --- a/api/src/com/cloud/api/commands/DeleteStaticRouteCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteStaticRouteCmd.java @@ -14,18 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.async.AsyncJob; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.StaticRoute; import com.cloud.user.UserContext; -@Implementation(description="Deletes a static route", responseObject=SuccessResponse.class) +@APICommand(name = "deleteStaticRoute", description="Deletes a static route", responseObject=SuccessResponse.class) public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteStaticRouteCmd.class.getName()); private static final String s_name = "deletestaticrouteresponse"; @@ -42,13 +39,13 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="static_routes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the static route") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = StaticRouteResponse.class, + required=true, description="the ID of the static route") private Long id; // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// @@ -57,7 +54,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -65,7 +62,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getCommandName() { return s_name; } - + @Override public String getEventType() { return EventTypes.EVENT_STATIC_ROUTE_DELETE; @@ -75,7 +72,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ public String getEventDescription() { return ("Deleting static route id=" + id); } - + @Override public long getEntityOwnerId() { if (ownerId == null) { @@ -88,12 +85,12 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ } return ownerId; } - + @Override public void execute() throws ResourceUnavailableException { UserContext.current().setEventDetails("Route Id: " + id); boolean result = _vpcService.revokeStaticRoute(id); - + if (result) { SuccessResponse response = new SuccessResponse(getCommandName()); this.setResponseObject(response); @@ -101,8 +98,8 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete static route"); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; @@ -116,7 +113,7 @@ public class DeleteStaticRouteCmd extends BaseAsyncCmd{ } return route.getVpcId(); } - + @Override public AsyncJob.Type getInstanceType() { return AsyncJob.Type.StaticRoute; diff --git a/api/src/com/cloud/api/commands/DeleteVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/DeleteVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java index 21b84020b99..ed4e754f736 100644 --- a/api/src/com/cloud/api/commands/DeleteVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/DeleteVPCCmd.java @@ -14,26 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; - -@Implementation(description="Deletes a VPC", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVPC", description="Deletes a VPC", responseObject=SuccessResponse.class) public class DeleteVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(DeleteVPCCmd.class.getName()); private static final String s_name = "deletevpcresponse"; @@ -42,11 +37,10 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="the ID of the VPC") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = VpcResponse.class, + required=true, description="the ID of the VPC") private Long id; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -55,7 +49,6 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ return id; } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -79,13 +72,13 @@ public class DeleteVPCCmd extends BaseAsyncCmd{ this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete VPC"); - } + } }catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } } diff --git a/api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java index 203d51745d6..08da25df279 100644 --- a/api/src/com/cloud/api/commands/ListPrivateGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListPrivateGatewaysCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; import com.cloud.network.vpc.PrivateGateway; +import com.cloud.utils.Pair; -@Implementation(description="List private gateways", responseObject=PrivateGatewayResponse.class) +@APICommand(name = "listPrivateGateways", description="List private gateways", responseObject=PrivateGatewayResponse.class) public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCmd{ public static final Logger s_logger = Logger.getLogger(ListPrivateGatewaysCmd.class.getName()); @@ -39,23 +40,23 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list private gateway by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + description="list private gateway by id") private Long id; - + @Parameter(name=ApiConstants.IP_ADDRESS, type=CommandType.STRING, description="list gateways by ip address") private String ipAddress; - + @Parameter(name=ApiConstants.VLAN, type=CommandType.STRING, description="list gateways by vlan") private String vlan; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list gateways by vpc") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list gateways by vpc") private Long vpcId; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list gateways by state") private String state; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -68,15 +69,15 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm public String getIpAddress() { return ipAddress; } - + public Long getVpcId() { return vpcId; } - + public Long getId() { return id; } - + public String getState() { return state; } @@ -88,19 +89,19 @@ public class ListPrivateGatewaysCmd extends BaseListProjectAndAccountResourcesCm public String getCommandName() { return s_name; } - + @Override public void execute() { - List gateways = _vpcService.listPrivateGateway(this); + Pair, Integer> gateways = _vpcService.listPrivateGateway(this); ListResponse response = new ListResponse(); List projectResponses = new ArrayList(); - for (PrivateGateway gateway : gateways) { + for (PrivateGateway gateway : gateways.first()) { PrivateGatewayResponse gatewayResponse = _responseGenerator.createPrivateGatewayResponse(gateway); projectResponses.add(gatewayResponse); } - response.setResponses(projectResponses); + response.setResponses(projectResponses, gateways.second()); response.setResponseName(getCommandName()); - + this.setResponseObject(response); } } diff --git a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java similarity index 61% rename from api/src/com/cloud/api/commands/ListStaticRoutesCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java index 3cd828678f3..e9fada0a314 100644 --- a/api/src/com/cloud/api/commands/ListStaticRoutesCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListStaticRoutesCmd.java @@ -14,36 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; import com.cloud.network.vpc.StaticRoute; +import com.cloud.utils.Pair; +import org.apache.cloudstack.api.response.VpcResponse; -@Implementation(description="Lists all static routes", responseObject=StaticRouteResponse.class) +@APICommand(name = "listStaticRoutes", description="Lists all static routes", responseObject=StaticRouteResponse.class) public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { private static final String s_name = "liststaticroutesresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="static_routes") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list static route by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=StaticRouteResponse.class, + description="list static route by id") private Long id; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="list static routes by vpc id") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list static routes by vpc id") private Long vpcId; - - @IdentityMapper(entityTableName="vpc_gateways") - @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.LONG, description="list static routes by gateway id") + + @Parameter(name=ApiConstants.GATEWAY_ID, type=CommandType.UUID, entityType=PrivateGatewayResponse.class, + description="list static routes by gateway id") private Long gatewayId; public Long getId() { @@ -57,7 +59,7 @@ public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { public Long getGatewayId() { return gatewayId; } - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -65,20 +67,20 @@ public class ListStaticRoutesCmd extends BaseListTaggedResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List result = _vpcService.listStaticRoutes(this); + Pair, Integer> result = _vpcService.listStaticRoutes(this); ListResponse response = new ListResponse(); List routeResponses = new ArrayList(); - - for (StaticRoute route : result) { + + for (StaticRoute route : result.first()) { StaticRouteResponse ruleData = _responseGenerator.createStaticRouteResponse(route); routeResponses.add(ruleData); } - response.setResponses(routeResponses); + response.setResponses(routeResponses, result.second()); response.setResponseName(getCommandName()); - this.setResponseObject(response); + this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java index 397c04a5ce2..f776302d3c1 100644 --- a/api/src/com/cloud/api/commands/ListVPCOfferingsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCOfferingsCmd.java @@ -14,52 +14,51 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; import com.cloud.network.vpc.VpcOffering; -@Implementation(description="Lists VPC offerings", responseObject=VpcOfferingResponse.class) +@APICommand(name = "listVPCOfferings", description="Lists VPC offerings", responseObject=VpcOfferingResponse.class) public class ListVPCOfferingsCmd extends BaseListCmd{ public static final Logger s_logger = Logger.getLogger(ListVPCOfferingsCmd.class.getName()); private static final String _name = "listvpcofferingsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list VPC offerings by id") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class, + description="list VPC offerings by id") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list VPC offerings by name") private String vpcOffName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="list VPC offerings by display text") private String displayText; - + @Parameter(name=ApiConstants.IS_DEFAULT, type=CommandType.BOOLEAN, description="true if need to list only default " + - "VPC offerings. Default value is false") + "VPC offerings. Default value is false") private Boolean isDefault; - - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, + + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list VPC offerings supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list VPC offerings by state") private String state; - - + + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -82,11 +81,11 @@ public class ListVPCOfferingsCmd extends BaseListCmd{ public List getSupportedServices() { return supportedServices; } - + public String getState() { return state; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -107,7 +106,7 @@ public class ListVPCOfferingsCmd extends BaseListCmd{ this.setResponseObject(response); } - + @Override public String getCommandName() { return _name; diff --git a/api/src/com/cloud/api/commands/ListVPCsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java similarity index 76% rename from api/src/com/cloud/api/commands/ListVPCsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java index 6f9acc16fec..6d3c8bd06c7 100644 --- a/api/src/com/cloud/api/commands/ListVPCsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/ListVPCsCmd.java @@ -14,77 +14,79 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.VpcResponse; +import org.apache.cloudstack.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.VpcOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ListResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListTaggedResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListTaggedResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; import com.cloud.network.vpc.Vpc; -@Implementation(description="Lists VPCs", responseObject=VpcResponse.class) +@APICommand(name = "listVPCs", description="Lists VPCs", responseObject=VpcResponse.class) public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public static final Logger s_logger = Logger.getLogger(ListVPCsCmd.class.getName()); private static final String s_name = "listvpcsresponse"; - + ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="list VPC by id") + //////////////////////////////////////////////////// + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="list VPC by id") private Long id; - - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="list by zone") + + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description="list by zone") private Long zoneId; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="list by name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="List by display text of " + "the VPC") private String displayText; - + @Parameter(name=ApiConstants.CIDR, type=CommandType.STRING, description="list by cidr of the VPC. All VPC " + "guest networks' cidrs should be within this CIDR") private String cidr; - - @IdentityMapper(entityTableName="vpc_offerings") - @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.LONG, description="list by ID of the VPC offering") + + @Parameter(name=ApiConstants.VPC_OFF_ID, type=CommandType.UUID, entityType=VpcOfferingResponse.class + , description="list by ID of the VPC offering") private Long VpcOffId; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="list by account associated with the VPC. " + "Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="list by domain ID associated with the VPC. " + + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="list by domain ID associated with the VPC. " + "If used with the account parameter returns the VPC associated with the account for the specified domain.") private Long domainId; - - @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, + + @Parameter(name=ApiConstants.SUPPORTED_SERVICES, type=CommandType.LIST, collectionType=CommandType.STRING, description="list VPC supporting certain services") private List supportedServices; - + @Parameter(name=ApiConstants.STATE, type=CommandType.STRING, description="list VPCs by state") private String state; - + @Parameter(name=ApiConstants.RESTART_REQUIRED, type=CommandType.BOOLEAN, description="list VPCs by restartRequired option") private Boolean restartRequired; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getAccountName() { return accountName; } @@ -104,7 +106,7 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public String getCidr() { return cidr; } - + public String getDisplayText() { return displayText; } @@ -112,23 +114,23 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ public Long getVpcOffId() { return VpcOffId; } - + public Long getId() { return id; } - + public List getSupportedServices() { return supportedServices; } - + public String getState() { return state; } - + public Boolean getRestartRequired() { return restartRequired; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -136,8 +138,8 @@ public class ListVPCsCmd extends BaseListTaggedResourcesCmd{ @Override public void execute() { List vpcs = _vpcService.listVpcs(getId(), getVpcName(), getDisplayText(), - getSupportedServices(), getCidr(), getVpcOffId(), getState(), getAccountName(), getDomainId(), - this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getZoneId(), this.isRecursive(), + getSupportedServices(), getCidr(), getVpcOffId(), getState(), getAccountName(), getDomainId(), + this.getKeyword(), this.getStartIndex(), this.getPageSizeVal(), getZoneId(), this.isRecursive(), this.listAll(), getRestartRequired(), getTags(), getProjectId()); ListResponse response = new ListResponse(); List offeringResponses = new ArrayList(); diff --git a/api/src/com/cloud/api/commands/RestartVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java similarity index 84% rename from api/src/com/cloud/api/commands/RestartVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java index bbb5cddbd63..4a23e6e6595 100644 --- a/api/src/com/cloud/api/commands/RestartVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/RestartVPCCmd.java @@ -14,19 +14,14 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,7 +29,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Restarts a VPC", responseObject=VpcResponse.class) +@APICommand(name = "restartVPC", description="Restarts a VPC", responseObject=VpcResponse.class) public class RestartVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(RestartVPCCmd.class.getName()); private static final String _name = "restartvpcresponse"; @@ -42,20 +37,20 @@ public class RestartVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="the id of the VPC") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -64,7 +59,7 @@ public class RestartVPCCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { Vpc vpc = _entityMgr.findById(Vpc.class, getId()); @@ -84,13 +79,13 @@ public class RestartVPCCmd extends BaseAsyncCmd{ this.setResponseObject(response); } else { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to restart VPC"); - } + } } catch (ResourceUnavailableException ex) { s_logger.warn("Exception: ", ex); throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } catch (ConcurrentOperationException ex) { s_logger.warn("Exception: ", ex); - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, ex.getMessage()); } catch (InsufficientCapacityException ex) { s_logger.info(ex); s_logger.trace(ex); diff --git a/api/src/com/cloud/api/commands/UpdateVPCCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java similarity index 83% rename from api/src/com/cloud/api/commands/UpdateVPCCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java index 0331be66bc4..2dc64dba267 100644 --- a/api/src/com/cloud/api/commands/UpdateVPCCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpc/UpdateVPCCmd.java @@ -14,23 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpc; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpcResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.VpcResponse; import com.cloud.event.EventTypes; import com.cloud.network.vpc.Vpc; import com.cloud.user.Account; -@Implementation(description="Updates a VPC", responseObject=VpcResponse.class) +@APICommand(name = "updateVPC", description="Updates a VPC", responseObject=VpcResponse.class) public class UpdateVPCCmd extends BaseAsyncCmd{ public static final Logger s_logger = Logger.getLogger(UpdateVPCCmd.class.getName()); private static final String _name = "updatevpcresponse"; @@ -38,14 +37,14 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the id of the VPC") + + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="the id of the VPC") private Long id; @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, description="the name of the VPC") private String vpcName; - + @Parameter(name=ApiConstants.DISPLAY_TEXT, type=CommandType.STRING, description="the display text of the VPC") private String displayText; @@ -53,19 +52,19 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public String getVpcName() { return vpcName; } - + public String getDisplayText() { return displayText; } - + public Long getId() { return id; } - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -74,7 +73,7 @@ public class UpdateVPCCmd extends BaseAsyncCmd{ public String getCommandName() { return _name; } - + @Override public long getEntityOwnerId() { Vpc vpc = _entityMgr.findById(Vpc.class, getId()); diff --git a/api/src/com/cloud/api/commands/AddVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java similarity index 53% rename from api/src/com/cloud/api/commands/AddVpnUserCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java index 10dc11a6e43..674dc6a5809 100644 --- a/api/src/com/cloud/api/commands/AddVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/AddVpnUserCmd.java @@ -14,25 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCreateCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; import com.cloud.domain.Domain; import com.cloud.event.EventTypes; import com.cloud.network.VpnUser; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Adds vpn users", responseObject=VpnUsersResponse.class) +@APICommand(name = "addVpnUser", description="Adds vpn users", responseObject=VpnUsersResponse.class) public class AddVpnUserCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(AddVpnUserCmd.class.getName()); @@ -43,108 +44,111 @@ public class AddVpnUserCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="username for the vpn user") private String userName; - + @Parameter(name=ApiConstants.PASSWORD, type=CommandType.STRING, required=true, description="password for the username") private String password; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the vpn user. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="add vpn user to the specific project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="add vpn user to the specific project") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } - public Long getDomainId() { - return domainId; - } + public Long getDomainId() { + return domainId; + } + + public String getUserName() { + return userName; + } + + public String getPassword() { + return password; + } + + public Long getProjectId() { + return projectId; + } - public String getUserName() { - return userName; - } - - public String getPassword() { - return password; - } - - public Long getProjectId() { - return projectId; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - + public String getEntityTable() { - return "vpn_users"; + return "vpn_users"; } - @Override - public String getEventDescription() { - return "Add Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); - } + @Override + public String getEventDescription() { + return "Add Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); + } - @Override - public String getEventType() { - return EventTypes.EVENT_VPN_USER_ADD; - } + @Override + public String getEventType() { + return EventTypes.EVENT_VPN_USER_ADD; + } @Override public void execute(){ - VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); - Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); - if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); - } - - VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getId()); - vpnResponse.setUserName(vpnUser.getUsername()); - vpnResponse.setAccountName(account.getAccountName()); - - vpnResponse.setDomainId(account.getDomainId()); - vpnResponse.setDomainName(_entityMgr.findById(Domain.class, account.getDomainId()).getName()); - - vpnResponse.setResponseName(getCommandName()); - vpnResponse.setObjectName("vpnuser"); - this.setResponseObject(vpnResponse); + VpnUser vpnUser = _entityMgr.findById(VpnUser.class, getEntityId()); + Account account = _entityMgr.findById(Account.class, vpnUser.getAccountId()); + if (!_ravService.applyVpnUsers(vpnUser.getAccountId(), userName)) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); + } + + VpnUsersResponse vpnResponse = new VpnUsersResponse(); + vpnResponse.setId(vpnUser.getUuid()); + vpnResponse.setUserName(vpnUser.getUsername()); + vpnResponse.setAccountName(account.getAccountName()); + + Domain domain = _entityMgr.findById(Domain.class, account.getDomainId()); + if (domain != null) { + vpnResponse.setDomainId(domain.getUuid()); + vpnResponse.setDomainName(domain.getName()); + } + + vpnResponse.setResponseName(getCommandName()); + vpnResponse.setObjectName("vpnuser"); + this.setResponseObject(vpnResponse); } @Override public void create() { Account owner = _accountService.getAccount(getEntityOwnerId()); - + VpnUser vpnUser = _ravService.addVpnUser(owner.getId(), userName, password); if (vpnUser == null) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to add vpn user"); } setEntityId(vpnUser.getId()); - } + } } diff --git a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java index 6787d1fb78f..37952f8777a 100644 --- a/api/src/com/cloud/api/commands/CreateRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateRemoteAccessVpnCmd.java @@ -14,19 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; @@ -34,7 +30,7 @@ import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.IpAddress; import com.cloud.network.RemoteAccessVpn; -@Implementation(description="Creates a l2tp/ipsec remote access vpn", responseObject=RemoteAccessVpnResponse.class) +@APICommand(name = "createRemoteAccessVpn", description="Creates a l2tp/ipsec remote access vpn", responseObject=RemoteAccessVpnResponse.class) public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateRemoteAccessVpnCmd.class.getName()); @@ -43,61 +39,61 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; @Parameter(name="iprange", type=CommandType.STRING, required=false, description="the range of ip addresses to allocate to vpn clients. The first ip in the range will be taken by the vpn server") private String ipRange; - + @Deprecated @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the VPN. Must be used with domainId.") private String accountName; @Deprecated - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the VPN. If the account parameter is used, domainId must also be used.") private Long domainId; - + @Parameter(name = ApiConstants.OPEN_FIREWALL, type = CommandType.BOOLEAN, description = "if true, firewall rule for source/end pubic port is automatically created; if false - firewall rule has to be created explicitely. Has value true by default") private Boolean openFirewall; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getEntityTable() { - return "user_ip_address"; + return "user_ip_address"; } - + public Long getPublicIpId() { - return publicIpId; - } - - public String getAccountName() { - return accountName; - } - - public Long getDomainId() { - return domainId; - } - - public String getIpRange() { - return ipRange; - } - - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } - - public Boolean getOpenFirewall() { - if (openFirewall != null) { - return openFirewall; - } else { - return true; - } + return publicIpId; } - + + public String getAccountName() { + return accountName; + } + + public Long getDomainId() { + return domainId; + } + + public String getIpRange() { + return ipRange; + } + + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } + + public Boolean getOpenFirewall() { + if (openFirewall != null) { + return openFirewall; + } else { + return true; + } + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// @@ -108,42 +104,42 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { return s_name; } - @Override - public long getEntityOwnerId() { - IpAddress ip = _networkService.getIp(publicIpId); - - if (ip == null) { - throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); - } - - return ip.getAccountId(); + @Override + public long getEntityOwnerId() { + IpAddress ip = _networkService.getIp(publicIpId); + + if (ip == null) { + throw new InvalidParameterValueException("Unable to find ip address by id=" + publicIpId); + } + + return ip.getAccountId(); } - @Override - public String getEventDescription() { - return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Create Remote Access VPN for account " + getEntityOwnerId() + " using public ip id=" + publicIpId; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_CREATE; - } - public long getNetworkId() { IpAddress ip = _entityMgr.findById(IpAddress.class, getPublicIpId()); Long ntwkId = null; - + if (ip.getAssociatedWithNetworkId() != null) { ntwkId = ip.getAssociatedWithNetworkId(); } - + if (ntwkId == null) { - throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + + throw new InvalidParameterValueException("Unable to create remote access vpn for the ipAddress id=" + getPublicIpId() + " as ip is not associated with any network and no networkId is passed in"); } return ntwkId; } - + @Override public void create() { try { @@ -176,8 +172,8 @@ public class CreateRemoteAccessVpnCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; diff --git a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java similarity index 82% rename from api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java index 61af0fa01b1..7f85fb4ebf6 100644 --- a/api/src/com/cloud/api/commands/CreateVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnConnectionCmd.java @@ -14,31 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.event.EventTypes; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.IpAddress; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.vpc.Vpc; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "createVpnConnection", description="Create site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnConnectionCmd.class.getName()); @@ -47,12 +39,12 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.S2S_VPN_GATEWAY_ID, type=CommandType.LONG, required=true, description="id of the vpn gateway") + @Parameter(name=ApiConstants.S2S_VPN_GATEWAY_ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + required=true, description="id of the vpn gateway") private Long vpnGatewayId; - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.S2S_CUSTOMER_GATEWAY_ID, type=CommandType.LONG, required=true, description="id of the customer gateway") + @Parameter(name=ApiConstants.S2S_CUSTOMER_GATEWAY_ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of the customer gateway") private Long customerGatewayId; ///////////////////////////////////////////////////// @@ -60,13 +52,13 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_vpn_connection"; + return "s2s_vpn_connection"; } - + public Long getVpnGatewayId() { return vpnGatewayId; } - + public Long getCustomerGatewayId() { return customerGatewayId; } @@ -129,8 +121,8 @@ public class CreateVpnConnectionCmd extends BaseAsyncCreateCmd { throw new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, ex.getMessage()); } } - - + + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; diff --git a/api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java index 9754f1c0f2c..65085182e0c 100644 --- a/api/src/com/cloud/api/commands/CreateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnCustomerGatewayCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Creates site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "createVpnCustomerGateway", description="Creates site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnCustomerGatewayCmd.class.getName()); @@ -60,7 +59,7 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.IKE_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 1 VPN connection to the customer gateway, in seconds") private Long ikeLifetime; - + @Parameter(name=ApiConstants.ESP_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 2 VPN connection to the customer gateway, in seconds") private Long espLifetime; @@ -69,20 +68,20 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the gateway. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the gateway. " + - "If used with the account parameter returns the gateway associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the gateway. If used with the account parameter returns the " + + "gateway associated with the account for the specified domain.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_customer_gateway"; + return "s2s_customer_gateway"; } - + public String getName() { return name; } @@ -137,8 +136,8 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { accountId = UserContext.current().getCaller().getId(); @@ -146,16 +145,16 @@ public class CreateVpnCustomerGatewayCmd extends BaseAsyncCmd { return accountId; } - @Override - public String getEventDescription() { - return "Create site-to-site VPN customer gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Create site-to-site VPN customer gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_CREATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_CREATE; - } - @Override public void execute(){ Site2SiteCustomerGateway result = _s2sVpnService.createCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java index 445c52a4734..89965bd842c 100644 --- a/api/src/com/cloud/api/commands/CreateVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/CreateVpnGatewayCmd.java @@ -14,35 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.vpc.Vpc; -import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Creates site to site vpn local gateway", responseObject=Site2SiteVpnGatewayResponse.class) +@APICommand(name = "createVpnGateway", description="Creates site to site vpn local gateway", responseObject=Site2SiteVpnGatewayResponse.class) public class CreateVpnGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(CreateVpnGatewayCmd.class.getName()); - + private static final String s_name = "createvpngatewayresponse"; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn gateway") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + required=true, description="public ip address id of the vpn gateway") private Long vpcId; ///////////////////////////////////////////////////// @@ -95,7 +93,7 @@ public class CreateVpnGatewayCmd extends BaseAsyncCmd { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to create VPN gateway"); } } - + @Override public String getSyncObjType() { return BaseAsyncCmd.vpcSyncObject; diff --git a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java similarity index 59% rename from api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java index c924fd9fe13..a634a0a7c5a 100644 --- a/api/src/com/cloud/api/commands/DeleteRemoteAccessVpnCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteRemoteAccessVpnCmd.java @@ -14,22 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.RemoteAccessVpn; +import com.cloud.user.UserContext; -@Implementation(description="Destroys a l2tp/ipsec remote access vpn", responseObject=SuccessResponse.class) +@APICommand(name = "deleteRemoteAccessVpn", description="Destroys a l2tp/ipsec remote access vpn", responseObject=SuccessResponse.class) public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteRemoteAccessVpnCmd.class.getName()); @@ -38,54 +40,53 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; - + // unexposed parameter needed for events logging - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, expose=false) + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType=AccountResponse.class, expose=false) private Long ownerId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - if (ownerId == null) { - RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); - if(vpnEntity != null) - return vpnEntity.getAccountId(); - - throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); - } - return ownerId; + @Override + public long getEntityOwnerId() { + if (ownerId == null) { + RemoteAccessVpn vpnEntity = _entityMgr.findById(RemoteAccessVpn.class, publicIpId); + if(vpnEntity != null) + return vpnEntity.getAccountId(); + + throw new InvalidParameterValueException("The specified public ip is not allocated to any account"); + } + return ownerId; } - @Override - public String getEventDescription() { - return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; - } + @Override + public String getEventDescription() { + return "Delete Remote Access VPN for account " + getEntityOwnerId() + " for ip id=" + publicIpId; + } - @Override - public String getEventType() { - return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; - } + @Override + public String getEventType() { + return EventTypes.EVENT_REMOTE_ACCESS_VPN_DESTROY; + } @Override public void execute() throws ResourceUnavailableException { - _ravService.destroyRemoteAccessVpn(publicIpId); + _ravService.destroyRemoteAccessVpn(publicIpId, UserContext.current().getCaller()); } - + @Override public String getSyncObjType() { return BaseAsyncCmd.networkSyncObject; @@ -95,5 +96,5 @@ public class DeleteRemoteAccessVpnCmd extends BaseAsyncCmd { public Long getSyncObjId() { return _ravService.getRemoteAccessVpn(publicIpId).getNetworkId(); } - + } diff --git a/api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java similarity index 74% rename from api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java index afcd562fbda..a079e8bcc30 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnConnectionCmd.java @@ -14,25 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(description="Delete site to site vpn connection", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnConnection", description="Delete site to site vpn connection", responseObject=SuccessResponse.class) public class DeleteVpnConnectionCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnConnectionCmd.class.getName()); @@ -41,8 +36,8 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + required=true, description="id of vpn connection") private Long id; ///////////////////////////////////////////////////// @@ -50,9 +45,9 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_vpn_connection"; + return "s2s_vpn_connection"; } - + public Long getId() { return id; } @@ -67,8 +62,8 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteVpnConnection conn = _entityMgr.findById(Site2SiteVpnConnection.class, getId()); if (conn != null) { return conn.getAccountId(); @@ -76,16 +71,16 @@ public class DeleteVpnConnectionCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN connection for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN connection for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CONNECTION_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CONNECTION_DELETE; - } - @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java similarity index 72% rename from api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java index df853234dd2..ef5ff3db438 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnCustomerGatewayCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; import com.cloud.user.Account; -@Implementation(description="Delete site to site vpn customer gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnCustomerGateway", description="Delete site to site vpn customer gateway", responseObject=SuccessResponse.class) public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnCustomerGatewayCmd.class.getName()); @@ -39,8 +35,8 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; ///////////////////////////////////////////////////// @@ -48,9 +44,9 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_customer_gateway"; + return "s2s_customer_gateway"; } - + public Long getId() { return id; } @@ -65,8 +61,8 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteCustomerGateway gw = _entityMgr.findById(Site2SiteCustomerGateway.class, getId()); if (gw != null) { return gw.getAccountId(); @@ -74,16 +70,16 @@ public class DeleteVpnCustomerGatewayCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN customer gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN customer gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_DELETE; - } - @Override public void execute(){ boolean result = _s2sVpnService.deleteCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java index b29f193ac71..f9b9e35a420 100644 --- a/api/src/com/cloud/api/commands/DeleteVpnGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/DeleteVpnGatewayCmd.java @@ -14,23 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.user.Account; -@Implementation(description="Delete site to site vpn gateway", responseObject=SuccessResponse.class) +@APICommand(name = "deleteVpnGateway", description="Delete site to site vpn gateway", responseObject=SuccessResponse.class) public class DeleteVpnGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteVpnGatewayCmd.class.getName()); @@ -39,8 +35,8 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; ///////////////////////////////////////////////////// @@ -48,9 +44,9 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_vpn_gateway"; + return "s2s_vpn_gateway"; } - + public Long getId() { return id; } @@ -65,8 +61,8 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Site2SiteVpnGateway gw = _entityMgr.findById(Site2SiteVpnGateway.class, getId()); if (gw != null) { return gw.getAccountId(); @@ -74,16 +70,16 @@ public class DeleteVpnGatewayCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Delete site-to-site VPN gateway for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Delete site-to-site VPN gateway for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_GATEWAY_DELETE; - } - @Override public void execute(){ boolean result = false; diff --git a/api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java similarity index 70% rename from api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java index 4260e3a3ee3..4b6a2058bee 100644 --- a/api/src/com/cloud/api/commands/ListRemoteAccessVpnsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListRemoteAccessVpnsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.IPAddressResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; import com.cloud.network.RemoteAccessVpn; +import com.cloud.utils.Pair; -@Implementation(description="Lists remote access vpns", responseObject=RemoteAccessVpnResponse.class) +@APICommand(name = "listRemoteAccessVpns", description="Lists remote access vpns", responseObject=RemoteAccessVpnResponse.class) public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListRemoteAccessVpnsCmd.class.getName()); @@ -39,16 +40,15 @@ public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesC ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="user_ip_address") - @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.LONG, required=true, description="public ip address id of the vpn server") + @Parameter(name=ApiConstants.PUBLIC_IP_ID, type=CommandType.UUID, entityType=IPAddressResponse.class, + required=true, description="public ip address id of the vpn server") private Long publicIpId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getPublicIpId() { return publicIpId; } @@ -64,15 +64,15 @@ public class ListRemoteAccessVpnsCmd extends BaseListProjectAndAccountResourcesC @Override public void execute(){ - List vpns = _ravService.searchForRemoteAccessVpns(this); + Pair, Integer> vpns = _ravService.searchForRemoteAccessVpns(this); ListResponse response = new ListResponse(); List vpnResponses = new ArrayList(); - if (vpns != null && !vpns.isEmpty()) { - for (RemoteAccessVpn vpn : vpns) { + if (vpns.first() != null && !vpns.first().isEmpty()) { + for (RemoteAccessVpn vpn : vpns.first()) { vpnResponses.add(_responseGenerator.createRemoteAccessVpnResponse(vpn)); } } - response.setResponses(vpnResponses); + response.setResponses(vpnResponses, vpns.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java similarity index 61% rename from api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java index 512f9458f27..56f8aa547e8 100644 --- a/api/src/com/cloud/api/commands/ListVpnConnectionsCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnConnectionsCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.network.Site2SiteVpnConnection; +import com.cloud.utils.Pair; -@Implementation(description="Lists site to site vpn connection gateways", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "listVpnConnections", description="Lists site to site vpn connection gateways", responseObject=Site2SiteVpnConnectionResponse.class) public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnConnectionsCmd.class.getName()); @@ -39,20 +40,19 @@ public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + description="id of the vpn connection") private Long id; - - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="id of vpc") + + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, + description="id of vpc") private Long vpcId; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -72,20 +72,19 @@ public class ListVpnConnectionsCmd extends BaseListProjectAndAccountResourcesCmd @Override public void execute(){ - List conns = _s2sVpnService.searchForVpnConnections(this); + Pair, Integer> conns = _s2sVpnService.searchForVpnConnections(this); ListResponse response = new ListResponse(); List connResponses = new ArrayList(); - if (conns != null && !conns.isEmpty()) { - for (Site2SiteVpnConnection conn : conns) { - if (conn == null) { - continue; - } - Site2SiteVpnConnectionResponse site2SiteVpnConnectonRes = _responseGenerator.createSite2SiteVpnConnectionResponse(conn); - site2SiteVpnConnectonRes.setObjectName("vpnconnection"); - connResponses.add(site2SiteVpnConnectonRes); + for (Site2SiteVpnConnection conn : conns.first()) { + if (conn == null) { + continue; } + Site2SiteVpnConnectionResponse site2SiteVpnConnectonRes = _responseGenerator.createSite2SiteVpnConnectionResponse(conn); + site2SiteVpnConnectonRes.setObjectName("vpnconnection"); + connResponses.add(site2SiteVpnConnectonRes); } - response.setResponses(connResponses); + + response.setResponses(connResponses, conns.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java similarity index 63% rename from api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java index 1e8b06ba81e..0e4209ba873 100644 --- a/api/src/com/cloud/api/commands/ListVpnCustomerGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnCustomerGatewaysCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.network.Site2SiteCustomerGateway; +import com.cloud.utils.Pair; -@Implementation(description="Lists site to site vpn customer gateways", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "listVpnCustomerGateways", description="Lists site to site vpn customer gateways", responseObject=Site2SiteCustomerGatewayResponse.class) public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnCustomerGatewaysCmd.class.getName()); @@ -40,15 +40,15 @@ public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourc //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + description="id of the customer gateway") private Long id; ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -64,20 +64,19 @@ public class ListVpnCustomerGatewaysCmd extends BaseListProjectAndAccountResourc @Override public void execute(){ - List gws = _s2sVpnService.searchForCustomerGateways(this); + Pair, Integer> gws = _s2sVpnService.searchForCustomerGateways(this); ListResponse response = new ListResponse(); List gwResponses = new ArrayList(); - if (gws != null && !gws.isEmpty()) { - for (Site2SiteCustomerGateway gw : gws) { - if (gw == null) { - continue; - } - Site2SiteCustomerGatewayResponse site2SiteCustomerGatewayRes = _responseGenerator.createSite2SiteCustomerGatewayResponse(gw); - site2SiteCustomerGatewayRes.setObjectName("vpncustomergateway"); - gwResponses.add(site2SiteCustomerGatewayRes); + for (Site2SiteCustomerGateway gw : gws.first()) { + if (gw == null) { + continue; } + Site2SiteCustomerGatewayResponse site2SiteCustomerGatewayRes = _responseGenerator.createSite2SiteCustomerGatewayResponse(gw); + site2SiteCustomerGatewayRes.setObjectName("vpncustomergateway"); + gwResponses.add(site2SiteCustomerGatewayRes); } - response.setResponses(gwResponses); + + response.setResponses(gwResponses, gws.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java index 63b212b0e31..63f70e3efe0 100644 --- a/api/src/com/cloud/api/commands/ListVpnGatewaysCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnGatewaysCmd.java @@ -14,40 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; - +package org.apache.cloudstack.api.command.user.vpn; + import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.VpcResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; import com.cloud.network.Site2SiteVpnGateway; +import com.cloud.utils.Pair; + +@APICommand(name = "listVpnGateways", description="Lists site 2 site vpn gateways", responseObject=Site2SiteVpnGatewayResponse.class) +public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { + public static final Logger s_logger = Logger.getLogger (ListVpnGatewaysCmd.class.getName()); + + private static final String s_name = "listvpngatewaysresponse"; -@Implementation(description="Lists site 2 site vpn gateways", responseObject=Site2SiteVpnGatewayResponse.class) -public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { - public static final Logger s_logger = Logger.getLogger (ListVpnGatewaysCmd.class.getName()); - - private static final String s_name = "listvpngatewaysresponse"; - ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="id of the vpn gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnGatewayResponse.class, + description="id of the vpn gateway") private Long id; - @IdentityMapper(entityTableName="vpc") - @Parameter(name=ApiConstants.VPC_ID, type=CommandType.LONG, description="id of vpc") + @Parameter(name=ApiConstants.VPC_ID, type=CommandType.UUID, entityType=VpcResponse.class, description="id of vpc") private Long vpcId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -65,27 +65,26 @@ public class ListVpnGatewaysCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// @Override - public String getCommandName() { - return s_name; + public String getCommandName() { + return s_name; } @Override public void execute(){ - List gws = _s2sVpnService.searchForVpnGateways(this); + Pair, Integer> gws = _s2sVpnService.searchForVpnGateways(this); ListResponse response = new ListResponse(); List gwResponses = new ArrayList(); - if (gws != null && !gws.isEmpty()) { - for (Site2SiteVpnGateway gw : gws) { - if (gw == null) { - continue; - } - Site2SiteVpnGatewayResponse site2SiteVpnGatewayRes = _responseGenerator.createSite2SiteVpnGatewayResponse(gw); - site2SiteVpnGatewayRes.setObjectName("vpngateway"); - gwResponses.add(site2SiteVpnGatewayRes); - } + for (Site2SiteVpnGateway gw : gws.first()) { + if (gw == null) { + continue; + } + Site2SiteVpnGatewayResponse site2SiteVpnGatewayRes = _responseGenerator.createSite2SiteVpnGatewayResponse(gw); + site2SiteVpnGatewayRes.setObjectName("vpngateway"); + gwResponses.add(site2SiteVpnGatewayRes); } - response.setResponses(gwResponses); + + response.setResponses(gwResponses, gws.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); - } -} + } +} diff --git a/api/src/com/cloud/api/commands/ListVpnUsersCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java similarity index 73% rename from api/src/com/cloud/api/commands/ListVpnUsersCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java index 9bc77ffb805..fb12f65faa5 100644 --- a/api/src/com/cloud/api/commands/ListVpnUsersCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ListVpnUsersCmd.java @@ -14,23 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListProjectAndAccountResourcesCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.VpnUsersResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListProjectAndAccountResourcesCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.VpnUsersResponse; import com.cloud.network.VpnUser; +import com.cloud.utils.Pair; -@Implementation(description="Lists vpn users", responseObject=VpnUsersResponse.class) +@APICommand(name = "listVpnUsers", description="Lists vpn users", responseObject=VpnUsersResponse.class) public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { public static final Logger s_logger = Logger.getLogger (ListVpnUsersCmd.class.getName()); @@ -39,13 +39,13 @@ public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="vpn_users") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the vpn user") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=VpnUsersResponse.class, + description="The uuid of the Vpn user") private Long id; @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, description="the username of the vpn user.") private String userName; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -66,18 +66,18 @@ public class ListVpnUsersCmd extends BaseListProjectAndAccountResourcesCmd { public String getCommandName() { return s_name; } - + @Override public void execute(){ - List vpnUsers = _ravService.searchForVpnUsers(this); + Pair, Integer> vpnUsers = _ravService.searchForVpnUsers(this); ListResponse response = new ListResponse(); List vpnResponses = new ArrayList(); - for (VpnUser vpnUser : vpnUsers) { + for (VpnUser vpnUser : vpnUsers.first()) { vpnResponses.add(_responseGenerator.createVpnUserResponse(vpnUser)); } - response.setResponses(vpnResponses); + response.setResponses(vpnResponses, vpnUsers.second()); response.setResponseName(getCommandName()); this.setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java similarity index 62% rename from api/src/com/cloud/api/commands/RemoveVpnUserCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java index 28fe3670c24..bdad7e31dd9 100644 --- a/api/src/com/cloud/api/commands/RemoveVpnUserCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/RemoveVpnUserCmd.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.event.EventTypes; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Removes vpn user", responseObject=SuccessResponse.class) +@APICommand(name = "removeVpnUser", description="Removes vpn user", responseObject=SuccessResponse.class) public class RemoveVpnUserCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(RemoveVpnUserCmd.class.getName()); @@ -41,81 +42,80 @@ public class RemoveVpnUserCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// @Parameter(name=ApiConstants.USERNAME, type=CommandType.STRING, required=true, description="username for the vpn user") private String userName; - + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for the vpn user. Must be used with domainId.") private String accountName; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="remove vpn user from the project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType=ProjectResponse.class, + description="remove vpn user from the project") private Long projectId; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for the vpn user. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } - public Long getDomainId() { - return domainId; - } + public Long getDomainId() { + return domainId; + } - public String getUserName() { - return userName; - } + public String getUserName() { + return userName; + } + + public Long getProjecId() { + return projectId; + } - public Long getProjecId() { - return projectId; - } - ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - @Override + @Override public String getCommandName() { return s_name; } - @Override - public long getEntityOwnerId() { - Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); + @Override + public long getEntityOwnerId() { + Long accountId = finalyzeAccountId(accountName, domainId, projectId, true); if (accountId == null) { return UserContext.current().getCaller().getId(); } - + return accountId; } - @Override - public String getEventDescription() { - return "Remove Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); - } + @Override + public String getEventDescription() { + return "Remove Remote Access VPN user for account " + getEntityOwnerId() + " username= " + getUserName(); + } - - @Override - public String getEventType() { - return EventTypes.EVENT_VPN_USER_REMOVE; - } + @Override + public String getEventType() { + return EventTypes.EVENT_VPN_USER_REMOVE; + } @Override public void execute(){ Account owner = _accountService.getAccount(getEntityOwnerId()); - boolean result = _ravService.removeVpnUser(owner.getId(), userName); + boolean result = _ravService.removeVpnUser(owner.getId(), userName, UserContext.current().getCaller()); if (!result) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to remove vpn user"); } - + if (!_ravService.applyVpnUsers(owner.getId(), userName)) { throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to apply vpn user removal"); - } + } SuccessResponse response = new SuccessResponse(getCommandName()); setResponseObject(response); } diff --git a/api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java similarity index 71% rename from api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java index a2ceedbabdd..0d7632ac1aa 100644 --- a/api/src/com/cloud/api/commands/ResetVpnConnectionCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/ResetVpnConnectionCmd.java @@ -14,25 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Reset site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) +@APICommand(name = "resetVpnConnection", description="Reset site to site vpn connection", responseObject=Site2SiteVpnConnectionResponse.class) public class ResetVpnConnectionCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ResetVpnConnectionCmd.class.getName()); @@ -41,33 +37,34 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_vpn_connection") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of vpn connection") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteVpnConnectionResponse.class, + required=true, description="id of vpn connection") private Long id; - @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for connection. Must be used with domainId.") + @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="an optional account for connection. " + + "Must be used with domainId.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="an optional domainId for connection. If the account parameter is used, domainId must also be used.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="an optional domainId for connection. If the account parameter is used, domainId must also be used.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_vpn_connection"; + return "s2s_vpn_connection"; } - + public Long getDomainId() { return domainId; } - + public Long getAccountId() { return getEntityOwnerId(); } - + public Long getId() { return id; } @@ -82,8 +79,8 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { return UserContext.current().getCaller().getId(); @@ -91,16 +88,16 @@ public class ResetVpnConnectionCmd extends BaseAsyncCmd { return Account.ACCOUNT_ID_SYSTEM; } - @Override - public String getEventDescription() { - return "Reset site-to-site VPN connection for account " + getEntityOwnerId(); - } + @Override + public String getEventDescription() { + return "Reset site-to-site VPN connection for account " + getEntityOwnerId(); + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CONNECTION_RESET; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CONNECTION_RESET; - } - @Override public void execute(){ try { diff --git a/api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java similarity index 79% rename from api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java rename to api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java index 491c1f6e49b..f2778e06103 100644 --- a/api/src/com/cloud/api/commands/UpdateVpnCustomerGatewayCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/vpn/UpdateVpnCustomerGatewayCmd.java @@ -14,24 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.vpn; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; import com.cloud.event.EventTypes; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.user.Account; import com.cloud.user.UserContext; -@Implementation(description="Update site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) +@APICommand(name = "updateVpnCustomerGateway", description="Update site to site vpn customer gateway", responseObject=Site2SiteCustomerGatewayResponse.class) public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(UpdateVpnCustomerGatewayCmd.class.getName()); @@ -40,13 +35,13 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="s2s_customer_gateway") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="id of customer gateway") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=Site2SiteCustomerGatewayResponse.class, + required=true, description="id of customer gateway") private Long id; - + @Parameter(name=ApiConstants.NAME, type=CommandType.STRING, required=false, description="name of this customer gateway") private String name; - + @Parameter(name=ApiConstants.GATEWAY, type=CommandType.STRING, required=true, description="public ip address id of the customer gateway") private String gatewayIp; @@ -64,7 +59,7 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.IKE_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 1 VPN connection to the customer gateway, in seconds") private Long ikeLifetime; - + @Parameter(name=ApiConstants.ESP_LIFETIME, type=CommandType.LONG, required=false, description="Lifetime of phase 2 VPN connection to the customer gateway, in seconds") private Long espLifetime; @@ -73,24 +68,24 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="the account associated with the gateway. Must be used with the domainId parameter.") private String accountName; - - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the domain ID associated with the gateway. " + - "If used with the account parameter returns the gateway associated with the account for the specified domain.") + + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the domain ID associated with the gateway. If used with the account parameter returns the " + + "gateway associated with the account for the specified domain.") private Long domainId; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// public String getEntityTable() { - return "s2s_customer_gateway"; + return "s2s_customer_gateway"; } - + public Long getId() { return id; } - + public String getName() { return name; } @@ -137,8 +132,8 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { return s_name; } - @Override - public long getEntityOwnerId() { + @Override + public long getEntityOwnerId() { Long accountId = finalyzeAccountId(accountName, domainId, null, true); if (accountId == null) { accountId = UserContext.current().getCaller().getId(); @@ -146,16 +141,16 @@ public class UpdateVpnCustomerGatewayCmd extends BaseAsyncCmd { return accountId; } - @Override - public String getEventDescription() { - return "Update site-to-site VPN customer gateway"; - } + @Override + public String getEventDescription() { + return "Update site-to-site VPN customer gateway"; + } + + @Override + public String getEventType() { + return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_UPDATE; + } - @Override - public String getEventType() { - return EventTypes.EVENT_S2S_VPN_CUSTOMER_GATEWAY_UPDATE; - } - @Override public void execute(){ Site2SiteCustomerGateway result = _s2sVpnService.updateCustomerGateway(this); diff --git a/api/src/com/cloud/api/commands/ListZonesByCmd.java b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/commands/ListZonesByCmd.java rename to api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java index 169a44ddfea..5f5f9e7bda0 --- a/api/src/com/cloud/api/commands/ListZonesByCmd.java +++ b/api/src/org/apache/cloudstack/api/command/user/zone/ListZonesByCmd.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.command.user.zone; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import com.cloud.dc.DataCenter; -@Implementation(description="Lists zones", responseObject=ZoneResponse.class) +@APICommand(name = "listZones", description="Lists zones", responseObject=ZoneResponse.class) public class ListZonesByCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListZonesByCmd.class.getName()); @@ -40,24 +39,26 @@ public class ListZonesByCmd extends BaseListCmd { ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, description="the ID of the zone") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=ZoneResponse.class, + description= "the ID of the zone") private Long id; - @Parameter(name=ApiConstants.AVAILABLE, type=CommandType.BOOLEAN, description="true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false.") + @Parameter(name=ApiConstants.AVAILABLE, type=CommandType.BOOLEAN, + description="true if you want to retrieve all available Zones. False if you only want to return the Zones" + + " from which you have at least one VM. Default is false.") private Boolean available; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="the ID of the domain associated with the zone") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType=DomainResponse.class, + description="the ID of the domain associated with the zone") private Long domainId; - + @Parameter(name=ApiConstants.SHOW_CAPACITIES, type=CommandType.BOOLEAN, description="flag to display the capacity of the zones") private Boolean showCapacities; - + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// - + public Long getId() { return id; } @@ -65,19 +66,19 @@ public class ListZonesByCmd extends BaseListCmd { public Boolean isAvailable() { return available; } - + public Long getDomainId(){ - return domainId; + return domainId; } public Boolean getShowCapacities() { - return showCapacities; - } - + return showCapacities; + } + ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// ///////////////////////////////////////////////////// - + @Override public String getCommandName() { return s_name; diff --git a/api/src/com/cloud/api/response/AccountResponse.java b/api/src/org/apache/cloudstack/api/response/AccountResponse.java old mode 100755 new mode 100644 similarity index 93% rename from api/src/com/cloud/api/response/AccountResponse.java rename to api/src/org/apache/cloudstack/api/response/AccountResponse.java index dd69024dfbe..51d3352c647 --- a/api/src/com/cloud/api/response/AccountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AccountResponse.java @@ -14,20 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; +import com.cloud.user.Account; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") +@EntityReference(value = Account.class) public class AccountResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the account") - private IdentityProxy id = new IdentityProxy("account"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the account") private String name; @@ -36,13 +40,13 @@ public class AccountResponse extends BaseResponse { private Short accountType; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="id of the Domain the account belongs too") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="name of the Domain the account belongs too") private String domainName; - + @SerializedName(ApiConstants.DEFAULT_ZONE_ID) @Param(description="the default zone of the account") - private IdentityProxy defaultZoneId = new IdentityProxy("data_center"); + private String defaultZoneId; @SerializedName(ApiConstants.RECEIVED_BYTES) @Param(description="the total number of network traffic bytes received") private Long bytesReceived; @@ -100,7 +104,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("vmrunning") @Param(description="the total number of virtual machines running for this account") private Integer vmRunning; - + @SerializedName("projectlimit") @Param(description="the total number of projects the account can own", since="3.0.1") private String projectLimit; @@ -109,7 +113,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("projectavailable") @Param(description="the total number of projects available for administration by this account", since="3.0.1") private String projectAvailable; - + @SerializedName("networklimit") @Param(description="the total number of networks the account can own", since="3.0.1") private String networkLimit; @@ -118,7 +122,7 @@ public class AccountResponse extends BaseResponse { @SerializedName("networkavailable") @Param(description="the total number of networks available to be created for this account", since="3.0.1") private String networkAvailable; - + @SerializedName("vpclimit") @Param(description="the total number of vpcs the account can own", since="3.0.5") private String vpcLimit; @@ -127,25 +131,31 @@ public class AccountResponse extends BaseResponse { @SerializedName("vpcavailable") @Param(description="the total number of vpcs available to be created for this account", since="3.0.5") private String vpcAvailable; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the account") private String state; @SerializedName(ApiConstants.IS_CLEANUP_REQUIRED) @Param(description="true if the account requires cleanup") private Boolean cleanupRequired; - + @SerializedName("user") @Param(description="the list of users associated with account", responseObject = UserResponse.class) private List users; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; - + @SerializedName(ApiConstants.ACCOUNT_DETAILS) @Param(description="details for the account") private Map details; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -156,8 +166,8 @@ public class AccountResponse extends BaseResponse { this.accountType = accountType; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -247,7 +257,7 @@ public class AccountResponse extends BaseResponse { public void setCleanupRequired(Boolean cleanupRequired) { this.cleanupRequired = cleanupRequired; } - + public void setUsers(List users) { this.users = users; } @@ -255,9 +265,9 @@ public class AccountResponse extends BaseResponse { public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } public void setProjectLimit(String projectLimit) { @@ -283,8 +293,8 @@ public class AccountResponse extends BaseResponse { public void setNetworkAvailable(String networkAvailable) { this.networkAvailable = networkAvailable; } - - public void setDefaultZone(Long defaultZoneId) { - this.defaultZoneId.setValue(defaultZoneId); + + public void setDefaultZone(String defaultZoneId) { + this.defaultZoneId = defaultZoneId; } } diff --git a/api/src/com/cloud/api/response/AlertResponse.java b/api/src/org/apache/cloudstack/api/response/AlertResponse.java similarity index 87% rename from api/src/com/cloud/api/response/AlertResponse.java rename to api/src/org/apache/cloudstack/api/response/AlertResponse.java index c54919e542e..f01a3e9c1f3 100644 --- a/api/src/com/cloud/api/response/AlertResponse.java +++ b/api/src/org/apache/cloudstack/api/response/AlertResponse.java @@ -14,20 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.alert.Alert; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Alert.class) @SuppressWarnings("unused") public class AlertResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the alert") - private IdentityProxy id = new IdentityProxy("alert"); + private String id; @SerializedName(ApiConstants.TYPE) @Param(description="One of the following alert types: " + "MEMORY = 0, CPU = 1, STORAGE = 2, STORAGE_ALLOCATED = 3, PUBLIC_IP = 4, PRIVATE_IP = 5, HOST = 6, USERVM = 7, " + @@ -45,8 +47,8 @@ public class AlertResponse extends BaseResponse { @SerializedName(ApiConstants.SENT) @Param(description="the date and time the alert was sent") private Date lastSent; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setAlertType(Short alertType) { diff --git a/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java b/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java new file mode 100644 index 00000000000..1a47cd2a3d2 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/AsyncJobResponse.java @@ -0,0 +1,110 @@ +// 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 org.apache.cloudstack.api.response; + +import java.util.Date; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.ResponseObject; +import com.cloud.async.AsyncJob; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value=AsyncJob.class) +@SuppressWarnings("unused") +public class AsyncJobResponse extends BaseResponse { + + @SerializedName("accountid") @Param(description="the account that executed the async command") + private String accountId; + + @SerializedName(ApiConstants.USER_ID) @Param(description="the user that executed the async command") + private String userId; + + @SerializedName("cmd") @Param(description="the async command executed") + private String cmd; + + @SerializedName("jobstatus") @Param(description="the current job status-should be 0 for PENDING") + private Integer jobStatus; + + @SerializedName("jobprocstatus") @Param(description="the progress information of the PENDING job") + private Integer jobProcStatus; + + @SerializedName("jobresultcode") @Param(description="the result code for the job") + private Integer jobResultCode; + + @SerializedName("jobresulttype") @Param(description="the result type") + private String jobResultType; + + @SerializedName("jobresult") @Param(description="the result reason") + private ResponseObject jobResult; + + @SerializedName("jobinstancetype") @Param(description="the instance/entity object related to the job") + private String jobInstanceType; + + @SerializedName("jobinstanceid") @Param(description="the unique ID of the instance/entity object related to the job") + private String jobInstanceId; + + @SerializedName(ApiConstants.CREATED) @Param(description=" the created date of the job") + private Date created; + + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public void setUserId(String userId) { + this.userId = userId; + } + + public void setCmd(String cmd) { + this.cmd = cmd; + } + + @Override + public void setJobStatus(Integer jobStatus) { + this.jobStatus = jobStatus; + } + + public void setJobProcStatus(Integer jobProcStatus) { + this.jobProcStatus = jobProcStatus; + } + + public void setJobResultCode(Integer jobResultCode) { + this.jobResultCode = jobResultCode; + } + + public void setJobResultType(String jobResultType) { + this.jobResultType = jobResultType; + } + + public void setJobResult(ResponseObject jobResult) { + this.jobResult = jobResult; + } + + public void setJobInstanceType(String jobInstanceType) { + this.jobInstanceType = jobInstanceType; + } + + public void setJobInstanceId(String jobInstanceId) { + this.jobInstanceId = jobInstanceId; + } + + public void setCreated(Date created) { + this.created = created; + } +} diff --git a/api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java new file mode 100644 index 00000000000..424a4fa446a --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/AutoScalePolicyResponse.java @@ -0,0 +1,118 @@ +// 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 org.apache.cloudstack.api.response; + +import com.cloud.network.as.AutoScalePolicy; +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import java.util.List; + +@EntityReference(value=AutoScalePolicy.class) +public class AutoScalePolicyResponse extends BaseResponse implements ControlledEntityResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "the autoscale policy ID") + private String id; + + @SerializedName(ApiConstants.ACTION) + @Param(description = "the action to be executed if all the conditions evaluate to true for the specified duration.") + private String action; + + @SerializedName(ApiConstants.DURATION) + @Param(description = "the duration for which the conditions have to be true before action is taken") + private Integer duration; + + @SerializedName(ApiConstants.QUIETTIME) + @Param(description = "the cool down period for which the policy should not be evaluated after the action has been taken") + private Integer quietTime; + + @SerializedName("conditions") + @Param(description = "the list of IDs of the conditions that are being evaluated on every interval") + private List conditions; + + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the autoscale policy") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id autoscale policy") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the autoscale policy") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the autoscale policy") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the autoscale policy") + private String domainName; + + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public void setDuration(Integer duration) { + this.duration = duration; + } + + public void setQuietTime(Integer quietTime) { + this.quietTime = quietTime; + } + + public void setAction(String action) { + this.action = action; + } + + public void setConditions(List conditions) { + this.conditions = conditions; + } + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } +} diff --git a/api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java new file mode 100644 index 00000000000..dc0e0155d5f --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/AutoScaleVmGroupResponse.java @@ -0,0 +1,154 @@ +// 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 org.apache.cloudstack.api.response; + +import com.cloud.network.as.AutoScaleVmGroup; +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +import java.util.List; + +@EntityReference(value=AutoScaleVmGroup.class) +public class AutoScaleVmGroupResponse extends BaseResponse implements ControlledEntityResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "the autoscale vm group ID") + private String id; + + @SerializedName(ApiConstants.LBID) + @Param(description = "the load balancer rule ID") + private String loadBalancerId; + + @SerializedName(ApiConstants.VMPROFILE_ID) + @Param(description = "the autoscale profile that contains information about the vms in the vm group.") + private String profileId; + + @SerializedName(ApiConstants.MIN_MEMBERS) + @Param(description = "the minimum number of members in the vmgroup, the number of instances in the vm group will be equal to or more than this number.") + private int minMembers; + + @SerializedName(ApiConstants.MAX_MEMBERS) + @Param(description = "the maximum number of members in the vmgroup, The number of instances in the vm group will be equal to or less than this number.") + private int maxMembers; + + @SerializedName(ApiConstants.INTERVAL) + @Param(description = "the frequency at which the conditions have to be evaluated") + private int interval; + + @SerializedName(ApiConstants.STATE) + @Param(description = "the current state of the AutoScale Vm Group") + private String state; + + @SerializedName(ApiConstants.SCALEUP_POLICIES) + @Param(description = "list of scaleup autoscale policies") + private List scaleUpPolicies; + + @SerializedName(ApiConstants.SCALEDOWN_POLICIES) + @Param(description = "list of scaledown autoscale policies") + private List scaleDownPolicies; + + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the instance group") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id vm profile") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vm profile") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the vm profile") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the vm profile") + private String domainName; + + public AutoScaleVmGroupResponse() { + + } + + + @Override + public String getObjectId() { + return this.id; + } + + + public void setId(String id) { + this.id = id; + } + + public void setLoadBalancerId(String loadBalancerId) { + this.loadBalancerId = loadBalancerId; + } + + public void setProfileId(String profileId) { + this.profileId = profileId; + } + + public void setMinMembers(int minMembers) { + this.minMembers = minMembers; + } + + public void setMaxMembers(int maxMembers) { + this.maxMembers = maxMembers; + } + + public void setState(String state) { + this.state = state; + } + + public void setInterval(int interval) { + this.interval = interval; + } + + public void setScaleUpPolicies(List scaleUpPolicies) { + this.scaleUpPolicies = scaleUpPolicies; + } + + public void setScaleDownPolicies(List scaleDownPolicies) { + this.scaleDownPolicies = scaleDownPolicies; + } + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } +} diff --git a/api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java b/api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java new file mode 100644 index 00000000000..0ae216706d0 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/AutoScaleVmProfileResponse.java @@ -0,0 +1,170 @@ +// 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 org.apache.cloudstack.api.response; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.cloud.network.as.AutoScaleVmProfile; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.Parameter; +import com.cloud.serializer.Param; +import com.cloud.utils.Pair; +import com.google.gson.annotations.SerializedName; + +@EntityReference(value=AutoScaleVmProfile.class) +public class AutoScaleVmProfileResponse extends BaseResponse implements ControlledEntityResponse { + + @SerializedName(ApiConstants.ID) + @Param(description = "the autoscale vm profile ID") + private String id; + + /* Parameters related to deploy virtual machine */ + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "the availability zone to be used while deploying a virtual machine") + private String zoneId; + + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) + @Param(description = "the service offering to be used while deploying a virtual machine") + private String serviceOfferingId; + + @SerializedName(ApiConstants.TEMPLATE_ID) + @Param(description = "the template to be used while deploying a virtual machine") + private String templateId; + + @SerializedName(ApiConstants.OTHER_DEPLOY_PARAMS) + @Param(description = "parameters other than zoneId/serviceOfferringId/templateId to be used while deploying a virtual machine") + private String otherDeployParams; + + /* Parameters related to destroying a virtual machine */ + @SerializedName(ApiConstants.AUTOSCALE_VM_DESTROY_TIME) + @Param(description = "the time allowed for existing connections to get closed before a vm is destroyed") + private Integer destroyVmGraceperiod; + + /* Parameters related to a running virtual machine - monitoring aspects */ + @SerializedName(ApiConstants.COUNTERPARAM_LIST) + @Parameter(name = ApiConstants.COUNTERPARAM_LIST, type = CommandType.MAP, description = "counterparam list. Example: counterparam[0].name=snmpcommunity&counterparam[0].value=public&counterparam[1].name=snmpport&counterparam[1].value=161") + private Map counterParams; + + @SerializedName(ApiConstants.AUTOSCALE_USER_ID) + @Param(description = "the ID of the user used to launch and destroy the VMs") + private String autoscaleUserId; + + @Parameter(name = ApiConstants.CS_URL, type = CommandType.STRING, description = "the API URL including port of the CloudStack Management Server example: http://server.cloud.com:8080/client/api?") + private String csUrl; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the account owning the instance group") + private String accountName; + + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id vm profile") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the vm profile") + private String projectName; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain ID of the vm profile") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain name of the vm profile") + private String domainName; + + public AutoScaleVmProfileResponse() { + + } + + + @Override + public String getObjectId() { + return this.id; + } + + + public void setId(String id) { + this.id = id; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + public void setTemplateId(String templateId) { + this.templateId = templateId; + } + + public void setOtherDeployParams(String otherDeployParams) { + this.otherDeployParams = otherDeployParams; + } + + public void setCounterParams(List> counterParams) { + this.counterParams = new HashMap(); + for (Pair paramKV : counterParams) { + String key = paramKV.first(); + String value = paramKV.second(); + this.counterParams.put(key, value); + } + } + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public void setAutoscaleUserId(String autoscaleUserId) { + this.autoscaleUserId = autoscaleUserId; + } + + public void setDestroyVmGraceperiod(Integer destroyVmGraceperiod) { + this.destroyVmGraceperiod = destroyVmGraceperiod; + } + + public void setCsUrl(String csUrl) { + this.csUrl = csUrl; + } +} diff --git a/api/src/com/cloud/api/response/CapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java similarity index 84% rename from api/src/com/cloud/api/response/CapabilitiesResponse.java rename to api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java index 4d98e173469..20d160dd2d5 100644 --- a/api/src/com/cloud/api/response/CapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilitiesResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class CapabilitiesResponse extends BaseResponse { @@ -27,21 +28,21 @@ public class CapabilitiesResponse extends BaseResponse { @SerializedName("cloudstackversion") @Param(description="version of the cloud stack") private String cloudStackVersion; - + @SerializedName("userpublictemplateenabled") @Param(description="true if user and domain admins can set templates to be shared, false otherwise") private boolean userPublicTemplateEnabled; - + @SerializedName("supportELB") @Param(description="true if region supports elastic load balancer on basic zones") private String supportELB; - + @SerializedName(ApiConstants.PROJECT_INVITE_REQUIRED) @Param(description="If invitation confirmation is required when add account to project") private Boolean projectInviteRequired; - + @SerializedName(ApiConstants.ALLOW_USER_CREATE_PROJECTS) @Param(description="true if regular user is allowed to create projects") private Boolean allowUsersCreateProjects; - + @SerializedName(ApiConstants.CUSTOM_DISK_OFF_MAX_SIZE) @Param(description="maximum size that can be specified when " + - "create disk from disk offering with custom size") + "create disk from disk offering with custom size") private Long diskOffMaxSize; @@ -61,13 +62,13 @@ public class CapabilitiesResponse extends BaseResponse { this.supportELB = supportELB; } - public void setProjectInviteRequired(Boolean projectInviteRequired) { - this.projectInviteRequired = projectInviteRequired; - } + public void setProjectInviteRequired(Boolean projectInviteRequired) { + this.projectInviteRequired = projectInviteRequired; + } - public void setAllowUsersCreateProjects(Boolean allowUsersCreateProjects) { - this.allowUsersCreateProjects = allowUsersCreateProjects; - } + public void setAllowUsersCreateProjects(Boolean allowUsersCreateProjects) { + this.allowUsersCreateProjects = allowUsersCreateProjects; + } public void setDiskOffMaxSize(Long diskOffMaxSize) { this.diskOffMaxSize = diskOffMaxSize; diff --git a/api/src/com/cloud/api/response/CapabilityResponse.java b/api/src/org/apache/cloudstack/api/response/CapabilityResponse.java similarity index 92% rename from api/src/com/cloud/api/response/CapabilityResponse.java rename to api/src/org/apache/cloudstack/api/response/CapabilityResponse.java index 0281c180452..5fe3072fe87 100644 --- a/api/src/com/cloud/api/response/CapabilityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapabilityResponse.java @@ -14,17 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CapabilityResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the capability name") private String name; - + @SerializedName(ApiConstants.VALUE) @Param(description="the capability value") private String value; diff --git a/api/src/com/cloud/api/response/CapacityResponse.java b/api/src/org/apache/cloudstack/api/response/CapacityResponse.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/response/CapacityResponse.java rename to api/src/org/apache/cloudstack/api/response/CapacityResponse.java index d38d9ad0746..000705813fb --- a/api/src/com/cloud/api/response/CapacityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CapacityResponse.java @@ -14,31 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CapacityResponse extends BaseResponse { @SerializedName(ApiConstants.TYPE) @Param(description="the capacity type") private Short capacityType; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name") private String zoneName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name") private String podName; - + @SerializedName(ApiConstants.CLUSTER_ID) @Param(description="the Cluster ID") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the Cluster name") private String clusterName; @@ -60,12 +61,12 @@ public class CapacityResponse extends BaseResponse { this.capacityType = capacityType; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -76,12 +77,12 @@ public class CapacityResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -92,23 +93,23 @@ public class CapacityResponse extends BaseResponse { this.podName = podName; } - public Long getClusterId() { - return clusterId.getValue(); - } + public String getClusterId() { + return clusterId; + } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); - } + public void setClusterId(String clusterId) { + this.clusterId = clusterId; + } - public String getClusterName() { - return clusterName; - } + public String getClusterName() { + return clusterName; + } - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } - public Long getCapacityUsed() { + public Long getCapacityUsed() { return capacityUsed; } diff --git a/api/src/com/cloud/api/response/CloudIdentifierResponse.java b/api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java similarity index 83% rename from api/src/com/cloud/api/response/CloudIdentifierResponse.java rename to api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java index 11d2b0be7d8..d6d2fa70138 100644 --- a/api/src/com/cloud/api/response/CloudIdentifierResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CloudIdentifierResponse.java @@ -14,32 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CloudIdentifierResponse extends BaseResponse { - + @SerializedName(ApiConstants.USER_ID) @Param(description="the user ID for the cloud identifier") - private IdentityProxy userId = new IdentityProxy("user"); - + private String userId; + @SerializedName("cloudidentifier") @Param(description="the cloud identifier") private String cloudIdentifier; - + @SerializedName("signature") @Param(description="the signed response for the cloud identifier") private String signature; - - public Long getUserId() { - return userId.getValue(); + + public String getUserId() { + return userId; } - public void setUserId(Long userId) { - this.userId.setValue(userId); + public void setUserId(String userId) { + this.userId = userId; } - + public String getCloudIdentifier() { return cloudIdentifier; } @@ -47,7 +47,7 @@ public class CloudIdentifierResponse extends BaseResponse { public void setCloudIdentifier(String cloudIdentifier) { this.cloudIdentifier = cloudIdentifier; } - + public String getSignature() { return signature; } diff --git a/api/src/com/cloud/api/response/ClusterResponse.java b/api/src/org/apache/cloudstack/api/response/ClusterResponse.java old mode 100755 new mode 100644 similarity index 72% rename from api/src/com/cloud/api/response/ClusterResponse.java rename to api/src/org/apache/cloudstack/api/response/ClusterResponse.java index 329f1f0e784..e436c9987e9 --- a/api/src/com/cloud/api/response/ClusterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ClusterResponse.java @@ -14,58 +14,60 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.org.Cluster; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = Cluster.class) public class ClusterResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the cluster ID") - private IdentityProxy id = new IdentityProxy("cluster"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the cluster name") private String name; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the cluster") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the cluster") private String podName; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the cluster") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the cluster") private String zoneName; @SerializedName("hypervisortype") @Param(description="the hypervisor type of the cluster") private String hypervisorType; - + @SerializedName("clustertype") @Param(description="the type of the cluster") private String clusterType; - + @SerializedName("allocationstate") @Param(description="the allocation state of the cluster") private String allocationState; - + @SerializedName("managedstate") @Param(description="whether this cluster is managed by cloudstack") private String managedState; - + @SerializedName("capacity") @Param(description="the capacity of the Cluster", responseObject = CapacityResponse.class) private List capacitites; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -76,12 +78,12 @@ public class ClusterResponse extends BaseResponse { this.name = name; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -92,12 +94,12 @@ public class ClusterResponse extends BaseResponse { this.podName = podName; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -107,29 +109,29 @@ public class ClusterResponse extends BaseResponse { public void setZoneName(String zoneName) { this.zoneName = zoneName; } - + public String getClusterType() { - return clusterType; + return clusterType; } - + public void setClusterType(String clusterType) { - this.clusterType = clusterType; + this.clusterType = clusterType; } - + public String getHypervisorType() { - return this.hypervisorType; + return this.hypervisorType; } - + public void setHypervisorType(String hypervisorType) { - this.hypervisorType = hypervisorType; + this.hypervisorType = hypervisorType; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } public String getManagedState() { @@ -140,11 +142,11 @@ public class ClusterResponse extends BaseResponse { this.managedState = managedState; } - public List getCapacitites() { - return capacitites; - } + public List getCapacitites() { + return capacitites; + } - public void setCapacitites(ArrayList arrayList) { - this.capacitites = arrayList; - } + public void setCapacitites(ArrayList arrayList) { + this.capacitites = arrayList; + } } diff --git a/api/src/org/apache/cloudstack/api/response/ConditionResponse.java b/api/src/org/apache/cloudstack/api/response/ConditionResponse.java new file mode 100644 index 00000000000..f398f0aaed5 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/ConditionResponse.java @@ -0,0 +1,126 @@ +// 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 org.apache.cloudstack.api.response; + +import java.util.List; + +import com.cloud.network.as.Condition; +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +@EntityReference(value=Condition.class) +@SuppressWarnings("unused") +public class ConditionResponse extends BaseResponse implements ControlledEntityResponse { + @SerializedName("id") + @Param(description = "the id of the Condition") + private String id; + + @SerializedName(value = ApiConstants.THRESHOLD) + @Param(description = "Threshold Value for the counter.") + private long threshold; + + @SerializedName(value = ApiConstants.RELATIONAL_OPERATOR) + @Param(description = "Relational Operator to be used with threshold.") + private String relationalOperator; + + @SerializedName("counter") + @Param(description = "Details of the Counter.") + private List counterResponse; + + @SerializedName(ApiConstants.DOMAIN_ID) + @Param(description = "the domain id of the Condition owner") + private String domainId; + + @SerializedName(ApiConstants.DOMAIN) + @Param(description = "the domain name of the owner.") + private String domain; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "zone id of counter") + private String zoneId; + + @SerializedName(ApiConstants.PROJECT_ID) + @Param(description = "the project id of the Condition.") + private String projectId; + + @SerializedName(ApiConstants.PROJECT) + @Param(description = "the project name of the Condition") + private String projectName; + + @SerializedName(ApiConstants.ACCOUNT) + @Param(description = "the owner of the Condition.") + private String accountName; + + // ///////////////////////////////////////////////// + // ///////////////// Setters /////////////////////// + // /////////////////////////////////////////////////// + + + public void setId(String id) { + this.id = id; + } + + @Override + public String getObjectId() { + return this.id; + } + + public void setThreshold(long threshold) { + this.threshold = threshold; + } + + public void setRelationalOperator(String relationalOperator) { + this.relationalOperator = relationalOperator; + } + + public void setCounterResponse(List counterResponse) { + this.counterResponse = counterResponse; + } + + @Override + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; + } + + @Override + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + @Override + public void setDomainName(String domainName) { + this.domain = domainName; + } +} diff --git a/api/src/com/cloud/api/response/ConfigurationResponse.java b/api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java similarity index 93% rename from api/src/com/cloud/api/response/ConfigurationResponse.java rename to api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java index bcfac826cb6..ded0fb5fb39 100644 --- a/api/src/com/cloud/api/response/ConfigurationResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ConfigurationResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ConfigurationResponse extends BaseResponse { @SerializedName(ApiConstants.CATEGORY) @Param(description="the category of the configuration") diff --git a/api/src/com/cloud/api/response/ControlledEntityResponse.java b/api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java similarity index 87% rename from api/src/com/cloud/api/response/ControlledEntityResponse.java rename to api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java index ab4a367a21d..598ef082253 100644 --- a/api/src/com/cloud/api/response/ControlledEntityResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ControlledEntityResponse.java @@ -14,17 +14,17 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; public interface ControlledEntityResponse { public void setAccountName(String accountName); - - public void setProjectId(Long projectId); - + + public void setProjectId(String projectId); + public void setProjectName(String projectName); - public void setDomainId(Long domainId); - + public void setDomainId(String domainId); + public void setDomainName(String domainName); } diff --git a/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java b/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java new file mode 100644 index 00000000000..116863256a9 --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/ControlledViewEntityResponse.java @@ -0,0 +1,31 @@ +// 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 org.apache.cloudstack.api.response; + +public interface ControlledViewEntityResponse { + + public void setAccountName(String accountName); + + public void setProjectId(String projectId); + + public void setProjectName(String projectName); + + public void setDomainId(String domainId); + + public void setDomainName(String domainName); +} + diff --git a/api/src/org/apache/cloudstack/api/response/CounterResponse.java b/api/src/org/apache/cloudstack/api/response/CounterResponse.java new file mode 100644 index 00000000000..4dc44e767bf --- /dev/null +++ b/api/src/org/apache/cloudstack/api/response/CounterResponse.java @@ -0,0 +1,72 @@ +// 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 org.apache.cloudstack.api.response; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.network.as.Counter; +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; + +@SuppressWarnings("unused") +@EntityReference(value=Counter.class) +public class CounterResponse extends BaseResponse { + @SerializedName("id") + @Param(description = "the id of the Counter") + private String id; + + @SerializedName(value = ApiConstants.NAME) + @Param(description = "Name of the counter.") + private String name; + + @SerializedName(value = ApiConstants.SOURCE) + @Param(description = "Source of the counter.") + private String source; + + @SerializedName(value = ApiConstants.VALUE) + @Param(description = "Value in case of snmp or other specific counters.") + private String value; + + @SerializedName(ApiConstants.ZONE_ID) + @Param(description = "zone id of counter") + private String zoneId; + + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { + this.name = name; + } + + public void setSource(String source) { + this.source = source; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/api/src/com/cloud/api/response/CreateCmdResponse.java b/api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java similarity index 87% rename from api/src/com/cloud/api/response/CreateCmdResponse.java rename to api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java index 5fa3b38ab31..3c26324e10b 100644 --- a/api/src/com/cloud/api/response/CreateCmdResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CreateCmdResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CreateCmdResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @@ -31,8 +32,8 @@ public class CreateCmdResponse extends BaseResponse { public void setId(Long id) { this.id.setValue(id); } - + public void setIdEntityTable(String entityTable) { - this.id.setTableName(entityTable); + this.id.setTableName(entityTable); } } diff --git a/api/src/com/cloud/api/response/CustomCertificateResponse.java b/api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java similarity index 81% rename from api/src/com/cloud/api/response/CustomCertificateResponse.java rename to api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java index 0738c33e271..f45b0c8e49b 100644 --- a/api/src/com/cloud/api/response/CustomCertificateResponse.java +++ b/api/src/org/apache/cloudstack/api/response/CustomCertificateResponse.java @@ -14,21 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class CustomCertificateResponse extends BaseResponse { @SerializedName("message") @Param(description="message of the certificate upload operation") private String message; - public String getResultMessage() { - return message; - } + public String getResultMessage() { + return message; + } - public void setResultMessage(String msg) { - this.message = msg; - } + public void setResultMessage(String msg) { + this.message = msg; + } } diff --git a/api/src/com/cloud/api/response/DiskOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java similarity index 86% rename from api/src/com/cloud/api/response/DiskOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java index 9b37431df94..de3daf587ad 100644 --- a/api/src/com/cloud/api/response/DiskOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DiskOfferingResponse.java @@ -14,21 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.DiskOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=DiskOffering.class) public class DiskOfferingResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="unique ID of the disk offering") - private IdentityProxy id = new IdentityProxy("disk_offering"); + private String id; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID this disk offering belongs to. Ignore this information as it is not currently applicable.") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name this disk offering belongs to. Ignore this information as it is not currently applicable.") private String domain; @@ -47,27 +50,27 @@ public class DiskOfferingResponse extends BaseResponse { @SerializedName("iscustomized") @Param(description="true if disk offering uses custom size, false otherwise") private Boolean customized; - + @SerializedName(ApiConstants.TAGS) @Param(description="the tags for the disk offering") private String tags; @SerializedName("storagetype") @Param(description="the storage type for this disk offering") private String storageType; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomain() { diff --git a/api/src/com/cloud/api/response/DomainResponse.java b/api/src/org/apache/cloudstack/api/response/DomainResponse.java similarity index 78% rename from api/src/com/cloud/api/response/DomainResponse.java rename to api/src/org/apache/cloudstack/api/response/DomainResponse.java index 52ba884ff55..c74e7c98d2f 100644 --- a/api/src/com/cloud/api/response/DomainResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DomainResponse.java @@ -14,16 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.domain.Domain; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +@EntityReference(value = Domain.class) public class DomainResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the domain") - private IdentityProxy id = new IdentityProxy("domain"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the domain") private String domainName; @@ -32,26 +35,26 @@ public class DomainResponse extends BaseResponse { private Integer level; @SerializedName("parentdomainid") @Param(description="the domain ID of the parent domain") - private IdentityProxy parentDomainId = new IdentityProxy("domain"); + private String parentDomainId; @SerializedName("parentdomainname") @Param(description="the domain name of the parent domain") private String parentDomainName; @SerializedName("haschild") @Param(description="whether the domain has one or more sub-domains") private boolean hasChild; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; @SerializedName(ApiConstants.PATH) @Param(description="the path of the domain") private String path; - - public Long getId() { - return id.getValue(); + + public String getId() { + return this.id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getDomainName() { @@ -70,12 +73,12 @@ public class DomainResponse extends BaseResponse { this.level = level; } - public Long getParentDomainId() { - return parentDomainId.getValue(); + public String getParentDomainId() { + return parentDomainId; } - public void setParentDomainId(Long parentDomainId) { - this.parentDomainId.setValue(parentDomainId); + public void setParentDomainId(String parentDomainId) { + this.parentDomainId = parentDomainId; } public String getParentDomainName() { @@ -98,12 +101,12 @@ public class DomainResponse extends BaseResponse { this.networkDomain = networkDomain; } - public String getPath() { - return path; - } + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } - public void setPath(String path) { - this.path = path; - } - } diff --git a/api/src/com/cloud/api/response/DomainRouterResponse.java b/api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java similarity index 78% rename from api/src/com/cloud/api/response/DomainRouterResponse.java rename to api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java index d710aadb2e7..cf2f3f41f56 100644 --- a/api/src/com/cloud/api/response/DomainRouterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/DomainRouterResponse.java @@ -14,27 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; + +import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.cloud.vm.VirtualMachine.State; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachine.class) @SuppressWarnings("unused") -public class DomainRouterResponse extends BaseResponse implements ControlledEntityResponse{ +public class DomainRouterResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the router") - private IdentityProxy id = new IdentityProxy("vm_instance"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID for the router") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name for the router") - private String zoneName; + private String zoneName; @SerializedName(ApiConstants.DNS1) @Param(description="the first DNS for the router") private String dns1; @@ -52,10 +57,10 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti private String name; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID for the router") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName(ApiConstants.HOST_ID) @Param(description="the host ID for the router") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the hostname for the router") private String hostName; @@ -68,9 +73,9 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.LINK_LOCAL_MAC_NETMASK) @Param(description="the link local netmask for the router") private String linkLocalNetmask; - + @SerializedName(ApiConstants.LINK_LOCAL_NETWORK_ID) @Param(description="the ID of the corresponding link local network") - private IdentityProxy linkLocalNetworkId = new IdentityProxy("networks"); + private String linkLocalNetworkId; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address for the router") private String publicIp; @@ -80,9 +85,9 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName("publicnetmask") @Param(description="the public netmask for the router") private String publicNetmask; - + @SerializedName("publicnetworkid") @Param(description="the ID of the corresponding public network") - private IdentityProxy publicNetworkId = new IdentityProxy("networks"); + private String publicNetworkId; @SerializedName("guestipaddress") @Param(description="the guest IP address for the router") private String guestIpAddress; @@ -92,12 +97,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName("guestnetmask") @Param(description="the guest netmask for the router") private String guestNetmask; - + @SerializedName("guestnetworkid") @Param(description="the ID of the corresponding guest network") - private IdentityProxy guestNetworkId = new IdentityProxy("networks"); + private String guestNetworkId; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="the template ID for the router") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName(ApiConstants.CREATED) @Param(description="the date and time the router was created") private Date created; @@ -107,59 +112,67 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the router") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID associated with the router") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain associated with the router") private String domainName; - + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; - + @SerializedName("isredundantrouter") @Param(description="if this router is an redundant virtual router") private boolean isRedundantRouter; - + @SerializedName("redundantstate") @Param(description="the state of redundant virtual router") private String redundantState; - + @SerializedName("templateversion") @Param(description="the version of template") private String templateVersion; - + @SerializedName("scriptsversion") @Param(description="the version of scripts") private String scriptsVersion; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the network belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - - @SerializedName("nic") @Param(description="the list of nics associated with the router", + private String vpcId; + + @SerializedName("nic") @Param(description="the list of nics associated with the router", responseObject = NicResponse.class, since="4.0") - private List nics; - + private Set nics; + + public DomainRouterResponse(){ + nics = new HashSet(); + } + + + @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { @@ -186,12 +199,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.name = name; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { @@ -222,8 +235,8 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.guestNetmask = guestNetmask; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setCreated(Date created) { @@ -240,8 +253,8 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -249,18 +262,18 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.domainName = domainName; } - public void setPublicNetworkId(Long publicNetworkId) { - this.publicNetworkId.setValue(publicNetworkId); + public void setPublicNetworkId(String publicNetworkId) { + this.publicNetworkId = publicNetworkId; } - public void setGuestNetworkId(Long guestNetworkId) { - this.guestNetworkId.setValue(guestNetworkId); + public void setGuestNetworkId(String guestNetworkId) { + this.guestNetworkId = guestNetworkId; } public void setLinkLocalIp(String linkLocalIp) { this.linkLocalIp = linkLocalIp; } - + public void setLinkLocalMacAddress(String linkLocalMacAddress) { this.linkLocalMacAddress = linkLocalMacAddress; } @@ -269,12 +282,12 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti this.linkLocalNetmask = linkLocalNetmask; } - public void setLinkLocalNetworkId(Long linkLocalNetworkId) { - this.linkLocalNetworkId.setValue(linkLocalNetworkId); + public void setLinkLocalNetworkId(String linkLocalNetworkId) { + this.linkLocalNetworkId = linkLocalNetworkId; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -292,33 +305,37 @@ public class DomainRouterResponse extends BaseResponse implements ControlledEnti public String getTemplateVersion() { return this.templateVersion; } - + public void setTemplateVersion(String templateVersion) { this.templateVersion = templateVersion; } - + public String getScriptsVersion() { return this.scriptsVersion; } - + public void setScriptsVersion(String scriptsVersion) { this.scriptsVersion = scriptsVersion; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - - public void setNics(List nics) { + + public void setNics(Set nics) { this.nics = nics; } + + public void addNic(NicResponse nic) { + this.nics.add(nic); + } } diff --git a/api/src/com/cloud/api/response/EventResponse.java b/api/src/org/apache/cloudstack/api/response/EventResponse.java similarity index 83% rename from api/src/com/cloud/api/response/EventResponse.java rename to api/src/org/apache/cloudstack/api/response/EventResponse.java index 61292214fee..b2148db5da1 100644 --- a/api/src/com/cloud/api/response/EventResponse.java +++ b/api/src/org/apache/cloudstack/api/response/EventResponse.java @@ -14,20 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.event.Event; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Event.class) @SuppressWarnings("unused") -public class EventResponse extends BaseResponse implements ControlledEntityResponse{ +public class EventResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of the event") - private IdentityProxy id = new IdentityProxy("event"); + private String id; @SerializedName(ApiConstants.USERNAME) @Param(description="the name of the user who performed the action (can be different from the account if an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)") private String username; @@ -43,15 +45,15 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name for the account that owns the object being acted on in the event (e.g. the owner of the virtual machine, ip address, or security group)") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the id of the account's domain") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the account's domain") private String domainName; @@ -63,10 +65,10 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo private Event.State state; @SerializedName("parentid") @Param(description="whether the event is parented") - private IdentityProxy parentId = new IdentityProxy("event"); + private String parentId; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setUsername(String username) { @@ -91,8 +93,8 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -108,13 +110,13 @@ public class EventResponse extends BaseResponse implements ControlledEntityRespo this.state = state; } - public void setParentId(Long parentId) { - this.parentId.setValue(parentId); + public void setParentId(String parentId) { + this.parentId = parentId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/EventTypeResponse.java b/api/src/org/apache/cloudstack/api/response/EventTypeResponse.java similarity index 89% rename from api/src/com/cloud/api/response/EventTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/EventTypeResponse.java index 9f6f84f4840..4dcc44179a6 100644 --- a/api/src/com/cloud/api/response/EventTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/EventTypeResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class EventTypeResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="Event Type") diff --git a/api/src/com/cloud/api/response/ExceptionResponse.java b/api/src/org/apache/cloudstack/api/response/ExceptionResponse.java similarity index 84% rename from api/src/com/cloud/api/response/ExceptionResponse.java rename to api/src/org/apache/cloudstack/api/response/ExceptionResponse.java index 9ff2cf12437..5f8e642140a 100644 --- a/api/src/com/cloud/api/response/ExceptionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExceptionResponse.java @@ -14,25 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.ArrayList; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ExceptionResponse extends BaseResponse { @SerializedName("uuidList") @Param(description="List of uuids associated with this error") - private ArrayList idList = new ArrayList(); + private ArrayList idList; @SerializedName("errorcode") @Param(description="numeric code associated with this error") private Integer errorCode; @SerializedName("cserrorcode") @Param(description="cloudstack exception error code associated with this error") - private Integer csErrorCode; - + private Integer csErrorCode; + @SerializedName("errortext") @Param(description="the text associated with this error") private String errorText = "Command failed due to Internal Server Error"; @@ -52,12 +52,12 @@ public class ExceptionResponse extends BaseResponse { this.errorText = errorText; } - public void addProxyObject(String tableName, Long id, String idFieldName) { - idList.add(new IdentityProxy(tableName, id, idFieldName)); + public void addProxyObject(String id) { + idList.add(id); return; } - public ArrayList getIdProxyList() { + public ArrayList getIdProxyList() { return idList; } diff --git a/server/src/com/cloud/server/api/response/ExternalFirewallResponse.java b/api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java similarity index 85% rename from server/src/com/cloud/server/api/response/ExternalFirewallResponse.java rename to api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java index 728db4b8c01..30fe86f88da 100644 --- a/server/src/com/cloud/server/api/response/ExternalFirewallResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExternalFirewallResponse.java @@ -14,133 +14,132 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class ExternalFirewallResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external firewall") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; - + @SerializedName(ApiConstants.USERNAME) @Param(description="the username that's used to log in to the external firewall") private String username; - + @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the external firewall") private String publicInterface; - + @SerializedName(ApiConstants.USAGE_INTERFACE) @Param(description="the usage interface of the external firewall") private String usageInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the external firewall") private String privateInterface; - + @SerializedName(ApiConstants.PUBLIC_ZONE) @Param(description="the public security zone of the external firewall") private String publicZone; - + @SerializedName(ApiConstants.PRIVATE_ZONE) @Param(description="the private security zone of the external firewall") private String privateZone; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external firewall") private String numRetries; - + @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getUsername() { return username; } - + public void setUsername(String username) { this.username = username; } - + public String getPublicInterface() { return publicInterface; } - + public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } - + public String getUsageInterface() { return usageInterface; } - + public void setUsageInterface(String usageInterface) { this.usageInterface = usageInterface; } - + public String getPrivateInterface() { return privateInterface; } - + public void setPrivateInterface(String privateInterface) { this.privateInterface = privateInterface; } - + public String getPublicZone() { return publicZone; } - + public void setPublicZone(String publicZone) { this.publicZone = publicZone; } - + public String getPrivateZone() { return privateZone; } - + public void setPrivateZone(String privateZone) { this.privateZone = privateZone; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } - + public String getTimeout() { return timeout; } - + public void setTimeout(String timeout) { this.timeout = timeout; } diff --git a/server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java b/api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java similarity index 81% rename from server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java rename to api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java index 5eb7a96a134..6f80c1084f8 100644 --- a/server/src/com/cloud/server/api/response/ExternalLoadBalancerResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExternalLoadBalancerResponse.java @@ -14,89 +14,88 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class ExternalLoadBalancerResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external load balancer") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external load balancer") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external load balancer") private String ipAddress; - + @SerializedName(ApiConstants.USERNAME) @Param(description="the username that's used to log in to the external load balancer") private String username; - + @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the external load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the external load balancer") private String privateInterface; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external load balancer") private String numRetries; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getUsername() { return username; } - + public void setUsername(String username) { this.username = username; } - + public String getPublicInterface() { return publicInterface; } - + public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } - + public String getPrivateInterface() { return privateInterface; } - + public void setPrivateInterface(String privateInterface) { this.privateInterface = privateInterface; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } diff --git a/api/src/com/cloud/api/response/ExtractResponse.java b/api/src/org/apache/cloudstack/api/response/ExtractResponse.java old mode 100755 new mode 100644 similarity index 75% rename from api/src/com/cloud/api/response/ExtractResponse.java rename to api/src/org/apache/cloudstack/api/response/ExtractResponse.java index b285b454cc1..5d415e94349 --- a/api/src/com/cloud/api/response/ExtractResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ExtractResponse.java @@ -14,85 +14,82 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ExtractResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of extracted object") - private IdentityProxy id = new IdentityProxy("vm_template"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the extracted object") private String name; - + @SerializedName("extractId") @Param(description="the upload id of extracted object") - private IdentityProxy uploadId = new IdentityProxy("async_job"); - + private String uploadId; + @SerializedName("uploadpercentage") @Param(description="the percentage of the entity uploaded to the specified location") private Integer uploadPercent; - + @SerializedName("status") @Param(description="the status of the extraction") private String status; - + @SerializedName("accountid") @Param(description="the account id to which the extracted object belongs") - private IdentityProxy accountId = new IdentityProxy("account"); - + private String accountId; + @SerializedName("resultstring") @Param(includeInApiDoc=false) - private String resultString; + private String resultString; @SerializedName(ApiConstants.CREATED) @Param(description="the time and date the object was created") private Date createdDate; @SerializedName(ApiConstants.STATE) @Param(description="the state of the extracted object") private String state; - + @SerializedName("storagetype") @Param(description="type of the storage") private String storageType; @SerializedName("storage") private String storage; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone ID the object was extracted from") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="zone name the object was extracted from") private String zoneName; @SerializedName("extractMode") @Param(description="the mode of extraction - upload or download") private String mode; - + @SerializedName(ApiConstants.URL) @Param(description="if mode = upload then url of the uploaded entity. if mode = download the url from which the entity can be downloaded") - private String url; - - public ExtractResponse(){ + private String url; + + public ExtractResponse(){ } - - public ExtractResponse(Long typeId, String typeName, long accountId, - String state, Long uploadId) { - this.id.setValue(typeId); + + public ExtractResponse(String typeId, String typeName, String accountId, + String state, String uploadId) { + this.id = typeId; this.name = typeName; - this.accountId.setValue(accountId); + this.accountId = accountId; this.state = state; - this.uploadId.setValue(uploadId); + this.uploadId = uploadId; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(long id) { - this.id.setValue(id); - } - - public void setIdentityTableName(String tableName) { - this.id.setTableName(tableName); + public void setId(String id) { + this.id = id; } + public String getName() { return name; } @@ -101,12 +98,12 @@ public class ExtractResponse extends BaseResponse { this.name = name; } - public Long getUploadId() { - return uploadId.getValue(); + public String getUploadId() { + return uploadId; } - public void setUploadId(Long uploadId) { - this.uploadId.setValue(uploadId); + public void setUploadId(String uploadId) { + this.uploadId = uploadId; } public Integer getUploadPercent() { @@ -125,12 +122,12 @@ public class ExtractResponse extends BaseResponse { this.status = status; } - public Long getAccountId() { - return accountId.getValue(); + public String getAccountId() { + return accountId; } - public void setAccountId(long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } public String getResultString() { @@ -173,12 +170,12 @@ public class ExtractResponse extends BaseResponse { this.storage = storage; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { diff --git a/api/src/com/cloud/api/response/FirewallResponse.java b/api/src/org/apache/cloudstack/api/response/FirewallResponse.java similarity index 93% rename from api/src/com/cloud/api/response/FirewallResponse.java rename to api/src/org/apache/cloudstack/api/response/FirewallResponse.java index bcb78e2f8f6..27992569e78 100644 --- a/api/src/com/cloud/api/response/FirewallResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FirewallResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the firewall rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the firewall rule") private String protocol; @@ -36,19 +36,19 @@ public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.END_PORT) @Param(description = "the ending port of firewall rule's port range") private String endPort; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the firewall rule") private Long publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the firewall rule") private String publicIpAddress; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.ICMP_TYPE) @Param(description= "type of the icmp message being sent") private Integer icmpType; @@ -58,8 +58,8 @@ public class FirewallResponse extends BaseResponse { @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setProtocol(String protocol) { diff --git a/api/src/com/cloud/api/response/FirewallRuleResponse.java b/api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java similarity index 75% rename from api/src/com/cloud/api/response/FirewallRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java index 252ad0dafe6..0009658c2a7 100644 --- a/api/src/com/cloud/api/response/FirewallRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/FirewallRuleResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.rules.FirewallRule; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=FirewallRule.class) @SuppressWarnings("unused") -public class FirewallRuleResponse extends BaseResponse{ +public class FirewallRuleResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the port forwarding rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PRIVATE_START_PORT) @Param(description = "the starting port of port forwarding rule's private port range") private String privateStartPort; @@ -44,35 +47,41 @@ public class FirewallRuleResponse extends BaseResponse{ private String publicEndPort; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="the VM ID for the port forwarding rule") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("virtualmachinename") @Param(description="the VM name for the port forwarding rule") private String virtualMachineName; @SerializedName("virtualmachinedisplayname") @Param(description="the VM display name for the port forwarding rule") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the port forwarding rule") - private IdentityProxy publicIpAddressId = new IdentityProxy("user_ip_address"); + private String publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the port forwarding rule") private String publicIpAddress; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) private List tags; - - public Long getId() { - return id.getValue(); + + + @Override + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getPrivateStartPort() { @@ -89,8 +98,8 @@ public class FirewallRuleResponse extends BaseResponse{ public void setPrivateEndPort(String privatePort) { this.privateEndPort = privatePort; - } - + } + public String getProtocol() { return protocol; } @@ -106,7 +115,7 @@ public class FirewallRuleResponse extends BaseResponse{ public String getPublicEndPort() { return publicEndPort; } - + public void setPublicStartPort(String publicPort) { this.publicStartPort = publicPort; } @@ -115,12 +124,12 @@ public class FirewallRuleResponse extends BaseResponse{ this.publicEndPort = publicPort; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { @@ -131,21 +140,21 @@ public class FirewallRuleResponse extends BaseResponse{ this.virtualMachineName = virtualMachineName; } - public String getVirtualMachineDisplayName() { - return virtualMachineDisplayName; - } + public String getVirtualMachineDisplayName() { + return virtualMachineDisplayName; + } - public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { - this.virtualMachineDisplayName = virtualMachineDisplayName; - } + public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { + this.virtualMachineDisplayName = virtualMachineDisplayName; + } - public String getPublicIpAddress() { - return publicIpAddress; - } + public String getPublicIpAddress() { + return publicIpAddress; + } - public void setPublicIpAddress(String publicIpAddress) { - this.publicIpAddress = publicIpAddress; - } + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } public String getState() { return state; @@ -155,14 +164,14 @@ public class FirewallRuleResponse extends BaseResponse{ this.state = state; } - public Long getPublicIpAddressId() { - return publicIpAddressId.getValue(); + public String getPublicIpAddressId() { + return publicIpAddressId; } - public void setPublicIpAddressId(Long publicIpAddressId) { - this.publicIpAddressId.setValue(publicIpAddressId); + public void setPublicIpAddressId(String publicIpAddressId) { + this.publicIpAddressId = publicIpAddressId; } - + public String getCidrList() { return cidrList; } @@ -170,7 +179,7 @@ public class FirewallRuleResponse extends BaseResponse{ public void setCidrList(String cidrs) { this.cidrList = cidrs; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/GetVMPasswordResponse.java b/api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java similarity index 58% rename from api/src/com/cloud/api/response/GetVMPasswordResponse.java rename to api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java index 41f1b6d3d53..8147df3fae1 100644 --- a/api/src/com/cloud/api/response/GetVMPasswordResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GetVMPasswordResponse.java @@ -14,30 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class GetVMPasswordResponse extends BaseResponse { - - @SerializedName("encryptedpassword") @Param(description="The encrypted password of the VM") - private String encryptedPassword; - - public GetVMPasswordResponse() {} - - public GetVMPasswordResponse(String responseName, String encryptedPassword) { - setResponseName(responseName); - setObjectName("password"); - setEncryptedPassword(encryptedPassword); - } - public String getEncryptedPassword() { - return encryptedPassword; - } + @SerializedName("encryptedpassword") @Param(description="The encrypted password of the VM") + private String encryptedPassword; + + public GetVMPasswordResponse() {} + + public GetVMPasswordResponse(String responseName, String encryptedPassword) { + setResponseName(responseName); + setObjectName("password"); + setEncryptedPassword(encryptedPassword); + } + + public String getEncryptedPassword() { + return encryptedPassword; + } + + public void setEncryptedPassword(String encryptedPassword) { + this.encryptedPassword = encryptedPassword; + } - public void setEncryptedPassword(String encryptedPassword) { - this.encryptedPassword = encryptedPassword; - } - } diff --git a/api/src/com/cloud/api/response/GuestOSCategoryResponse.java b/api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java similarity index 74% rename from api/src/com/cloud/api/response/GuestOSCategoryResponse.java rename to api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java index 9e98f3e2e3e..a14ce59f968 100644 --- a/api/src/com/cloud/api/response/GuestOSCategoryResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GuestOSCategoryResponse.java @@ -14,26 +14,29 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.GuestOsCategory; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=GuestOsCategory.class) public class GuestOSCategoryResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the OS category") - private IdentityProxy id = new IdentityProxy("guest_os_category"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the OS category") - private String name; + private String name; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { diff --git a/api/src/com/cloud/api/response/GuestOSResponse.java b/api/src/org/apache/cloudstack/api/response/GuestOSResponse.java similarity index 71% rename from api/src/com/cloud/api/response/GuestOSResponse.java rename to api/src/org/apache/cloudstack/api/response/GuestOSResponse.java index 8efa8d8f4eb..0bc5dd2956e 100644 --- a/api/src/com/cloud/api/response/GuestOSResponse.java +++ b/api/src/org/apache/cloudstack/api/response/GuestOSResponse.java @@ -14,37 +14,40 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.GuestOS; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=GuestOS.class) public class GuestOSResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the OS type") - private IdentityProxy id = new IdentityProxy("guest_os"); + private String id; @SerializedName(ApiConstants.OS_CATEGORY_ID) @Param(description="the ID of the OS category") - private IdentityProxy osCategoryId = new IdentityProxy("guest_os_category"); + private String osCategoryId; @SerializedName(ApiConstants.DESCRIPTION) @Param(description="the name/description of the OS type") private String description; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getOsCategoryId() { - return osCategoryId.getValue(); + public String getOsCategoryId() { + return osCategoryId; } - public void setOsCategoryId(Long osCategoryId) { - this.osCategoryId.setValue(osCategoryId); + public void setOsCategoryId(String osCategoryId) { + this.osCategoryId = osCategoryId; } public String getDescription() { diff --git a/api/src/com/cloud/api/response/HostResponse.java b/api/src/org/apache/cloudstack/api/response/HostResponse.java old mode 100755 new mode 100644 similarity index 89% rename from api/src/com/cloud/api/response/HostResponse.java rename to api/src/org/apache/cloudstack/api/response/HostResponse.java index 52c96fb0482..35b07dda83d --- a/api/src/com/cloud/api/response/HostResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HostResponse.java @@ -14,21 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host; import com.cloud.host.Status; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Host.class) public class HostResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the host") - private IdentityProxy id = new IdentityProxy("host"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the host") private String name; @@ -43,7 +45,7 @@ public class HostResponse extends BaseResponse { private Host.Type hostType; @SerializedName("oscategoryid") @Param(description="the OS category ID of the host") - private IdentityProxy osCategoryId = new IdentityProxy("guest_os_category"); + private String osCategoryId; @SerializedName("oscategoryname") @Param(description="the OS category name of the host") private String osCategoryName; @@ -52,13 +54,13 @@ public class HostResponse extends BaseResponse { private String ipAddress; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the host") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the host") private String zoneName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID of the host") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the host") private String podName; @@ -118,7 +120,7 @@ public class HostResponse extends BaseResponse { private Long managementServerId; @SerializedName("clusterid") @Param(description="the cluster ID of the host") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the cluster name of the host") private String clusterName; @@ -158,16 +160,16 @@ public class HostResponse extends BaseResponse { @Override - public Long getObjectId() { - return getId(); - } - - public Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -186,8 +188,8 @@ public class HostResponse extends BaseResponse { this.hostType = hostType; } - public void setOsCategoryId(Long osCategoryId) { - this.osCategoryId.setValue(osCategoryId); + public void setOsCategoryId(String osCategoryId) { + this.osCategoryId = osCategoryId; } public void setOsCategoryName(String osCategoryName) { @@ -198,16 +200,16 @@ public class HostResponse extends BaseResponse { this.ipAddress = ipAddress; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public void setPodName(String podName) { @@ -217,7 +219,7 @@ public class HostResponse extends BaseResponse { public void setVersion(String version) { this.version = version; } - + public void setHypervisor(HypervisorType hypervisor) { this.hypervisor = hypervisor; } @@ -225,7 +227,7 @@ public class HostResponse extends BaseResponse { public void setCpuNumber(Integer cpuNumber) { this.cpuNumber = cpuNumber; } - + public void setCpuSpeed(Long cpuSpeed) { this.cpuSpeed = cpuSpeed; } @@ -286,8 +288,8 @@ public class HostResponse extends BaseResponse { this.managementServerId = managementServerId; } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); + public void setClusterId(String clusterId) { + this.clusterId = clusterId; } public void setClusterName(String clusterName) { @@ -314,6 +316,11 @@ public class HostResponse extends BaseResponse { this.events = events; } + + public String getHostTags() { + return hostTags; + } + public void setHostTags(String hostTags) { this.hostTags = hostTags; } @@ -321,11 +328,11 @@ public class HostResponse extends BaseResponse { public void setHasEnoughCapacity(Boolean hasEnoughCapacity) { this.hasEnoughCapacity = hasEnoughCapacity; } - + public void setSuitableForMigration(Boolean suitableForMigration) { this.suitableForMigration = suitableForMigration; - } + } public String getResourceState() { return resourceState; @@ -347,22 +354,6 @@ public class HostResponse extends BaseResponse { this.hypervisorVersion = hypervisorVersion; } - public void setOsCategoryId(IdentityProxy osCategoryId) { - this.osCategoryId = osCategoryId; - } - - public void setZoneId(IdentityProxy zoneId) { - this.zoneId = zoneId; - } - - public void setPodId(IdentityProxy podId) { - this.podId = podId; - } - - public void setClusterId(IdentityProxy clusterId) { - this.clusterId = clusterId; - } - public void setHaHost(Boolean haHost) { this.haHost = haHost; } diff --git a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java b/api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java similarity index 85% rename from api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java rename to api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java index 4c3ea44c6c2..44e0513e32c 100644 --- a/api/src/com/cloud/api/response/HypervisorCapabilitiesResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HypervisorCapabilitiesResponse.java @@ -14,17 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.hypervisor.HypervisorCapabilities; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=HypervisorCapabilities.class) public class HypervisorCapabilitiesResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the hypervisor capabilities row") - private IdentityProxy id = new IdentityProxy("hypervisor_capabilities"); + private String id; @SerializedName(ApiConstants.HYPERVISOR_VERSION) @Param(description="the hypervisor version") private String hypervisorVersion; @@ -38,17 +41,13 @@ public class HypervisorCapabilitiesResponse extends BaseResponse { @SerializedName(ApiConstants.SECURITY_GROUP_EANBLED) @Param(description="true if security group is supported") private boolean isSecurityGroupEnabled; - @Override - public Long getObjectId() { - return getId(); + + public String getId() { + return id; } - public Long getId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } diff --git a/api/src/com/cloud/api/response/HypervisorResponse.java b/api/src/org/apache/cloudstack/api/response/HypervisorResponse.java similarity index 89% rename from api/src/com/cloud/api/response/HypervisorResponse.java rename to api/src/org/apache/cloudstack/api/response/HypervisorResponse.java index c3ce693f647..3828539746b 100644 --- a/api/src/com/cloud/api/response/HypervisorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/HypervisorResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class HypervisorResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="Hypervisor name") diff --git a/api/src/com/cloud/api/response/IPAddressResponse.java b/api/src/org/apache/cloudstack/api/response/IPAddressResponse.java similarity index 75% rename from api/src/com/cloud/api/response/IPAddressResponse.java rename to api/src/org/apache/cloudstack/api/response/IPAddressResponse.java index a9c1769406f..4d18aef5569 100644 --- a/api/src/com/cloud/api/response/IPAddressResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IPAddressResponse.java @@ -14,21 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.IpAddress; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=IpAddress.class) @SuppressWarnings("unused") public class IPAddressResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="public IP address id") - private IdentityProxy id = new IdentityProxy("user_ip_address"); - + private String id; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="public IP address") private String ipAddress; @@ -36,7 +39,7 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR private Date allocated; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the zone the public IP address belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the public IP address belongs to") private String zoneName; @@ -46,15 +49,15 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account the public IP address is associated with") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID the public IP address is associated with") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain the public IP address is associated with") private String domainName; @@ -62,66 +65,72 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR @SerializedName(ApiConstants.FOR_VIRTUAL_NETWORK) @Param(description="the virtual network for the IP address") private Boolean forVirtualNetwork; - @SerializedName(ApiConstants.VLAN_ID) @Param(description="the ID of the VLAN associated with the IP address") - private IdentityProxy vlanId = new IdentityProxy("vlan"); + @SerializedName(ApiConstants.VLAN_ID) @Param(description="the ID of the VLAN associated with the IP address." + + " This parameter is visible to ROOT admins only") + private String vlanId; @SerializedName("vlanname") @Param(description="the VLAN associated with the IP address") private String vlanName; @SerializedName("isstaticnat") @Param(description="true if this ip is for static nat, false otherwise") private Boolean staticNat; - + @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="true if this ip is system ip (was allocated as a part of deployVm or createLbRule)") private Boolean isSystem; - + @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="virutal machine id the ip address is assigned to (not null only for static nat Ip)") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); - + private String virtualMachineId; + @SerializedName("virtualmachinename") @Param(description="virutal machine name the ip address is assigned to (not null only for static nat Ip)") private String virtualMachineName; - + @SerializedName("virtualmachinedisplayname") @Param(description="virutal machine display name the ip address is assigned to (not null only for static nat Ip)") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_ID) @Param(description="the ID of the Network associated with the IP address") - private IdentityProxy associatedNetworkId = new IdentityProxy("networks"); - + private String associatedNetworkId; + @SerializedName(ApiConstants.ASSOCIATED_NETWORK_NAME) @Param(description="the name of the Network associated with the IP address") private String associatedNetworkName; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the ID of the Network where ip belongs to") - private IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName(ApiConstants.STATE) @Param(description="State of the ip address. Can be: Allocatin, Allocated and Releasing") private String state; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.PURPOSE) @Param(description="purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value") private String purpose; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the ip belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with ip address", responseObject = ResourceTagResponse.class) private List tags; -/* +/* @SerializedName(ApiConstants.JOB_ID) @Param(description="shows the current pending asynchronous job ID. This tag is not returned if no current pending jobs are acting on the volume") private IdentityProxy jobId = new IdentityProxy("async_job"); -*/ +*/ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } + @Override + public String getObjectId() { + return this.getId(); + } + public void setAllocated(Date allocated) { this.allocated = allocated; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { @@ -138,10 +147,10 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; @@ -151,28 +160,28 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR this.forVirtualNetwork = forVirtualNetwork; } - public void setVlanId(Long vlanId) { - this.vlanId.setValue(vlanId); + public void setVlanId(String vlanId) { + this.vlanId = vlanId; } public void setVlanName(String vlanName) { this.vlanName = vlanName; } - public void setStaticNat(Boolean staticNat) { - this.staticNat = staticNat; - } - - public void setAssociatedNetworkId(Long networkId) { - this.associatedNetworkId.setValue(networkId); + public void setStaticNat(Boolean staticNat) { + this.staticNat = staticNat; } - public void setNetworkId(Long networkId) { - this.networkId.setValue(networkId); + public void setAssociatedNetworkId(String networkId) { + this.associatedNetworkId = networkId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setNetworkId(String networkId) { + this.networkId = networkId; + } + + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVirtualMachineName(String virtualMachineName) { @@ -183,49 +192,45 @@ public class IPAddressResponse extends BaseResponse implements ControlledEntityR this.virtualMachineDisplayName = virtualMachineDisplayName; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setState(String state) { this.state = state; } - @Override - public Long getObjectId() { - return getId(); - } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public void setIsSystem(Boolean isSystem) { - this.isSystem = isSystem; - } + public void setIsSystem(Boolean isSystem) { + this.isSystem = isSystem; + } public void setPurpose(String purpose) { this.purpose = purpose; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/InstanceGroupResponse.java b/api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java similarity index 80% rename from api/src/com/cloud/api/response/InstanceGroupResponse.java rename to api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java index 3b1e3585934..24706ab09fc 100644 --- a/api/src/com/cloud/api/response/InstanceGroupResponse.java +++ b/api/src/org/apache/cloudstack/api/response/InstanceGroupResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.vm.InstanceGroup; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") -public class InstanceGroupResponse extends BaseResponse implements ControlledEntityResponse{ +@EntityReference(value = InstanceGroup.class) +public class InstanceGroupResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the instance group") - private IdentityProxy id = new IdentityProxy("instance_group"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the instance group") private String name; @@ -36,21 +39,21 @@ public class InstanceGroupResponse extends BaseResponse implements ControlledEnt @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the instance group") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the group") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the group") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the instance group") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the instance group") private String domainName; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -67,18 +70,18 @@ public class InstanceGroupResponse extends BaseResponse implements ControlledEnt } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/IpForwardingRuleResponse.java b/api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java similarity index 76% rename from api/src/com/cloud/api/response/IpForwardingRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java index 2017a3feac8..93c86c31332 100644 --- a/api/src/com/cloud/api/response/IpForwardingRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IpForwardingRuleResponse.java @@ -14,50 +14,50 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class IpForwardingRuleResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the port forwarding rule") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the port forwarding rule") private String protocol; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="the VM ID for the port forwarding rule") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("virtualmachinename") @Param(description="the VM name for the port forwarding rule") private String virtualMachineName; @SerializedName("virtualmachinedisplayname") @Param(description="the VM display name for the port forwarding rule") private String virtualMachineDisplayName; - + @SerializedName(ApiConstants.IP_ADDRESS_ID) @Param(description="the public ip address id for the port forwarding rule") private Long publicIpAddressId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the public ip address for the port forwarding rule") private String publicIpAddress; - + @SerializedName(ApiConstants.START_PORT) @Param(description="the start port of the rule") private Integer startPort; - + @SerializedName(ApiConstants.END_PORT) @Param(description="the end port of the rule") private Integer endPort; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the ip forwarding rule") private String state; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getProtocol() { @@ -68,12 +68,12 @@ public class IpForwardingRuleResponse extends BaseResponse { this.protocol = protocol; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { @@ -84,21 +84,21 @@ public class IpForwardingRuleResponse extends BaseResponse { this.virtualMachineName = virtualMachineName; } - public String getVirtualMachineDisplayName() { - return virtualMachineDisplayName; - } + public String getVirtualMachineDisplayName() { + return virtualMachineDisplayName; + } - public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { - this.virtualMachineDisplayName = virtualMachineDisplayName; - } + public void setVirtualMachineDisplayName(String virtualMachineDisplayName) { + this.virtualMachineDisplayName = virtualMachineDisplayName; + } - public String getPublicIpAddress() { - return publicIpAddress; - } + public String getPublicIpAddress() { + return publicIpAddress; + } - public void setPublicIpAddress(String publicIpAddress) { - this.publicIpAddress = publicIpAddress; - } + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } public String getState() { return state; diff --git a/api/src/com/cloud/api/response/IsoVmResponse.java b/api/src/org/apache/cloudstack/api/response/IsoVmResponse.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/response/IsoVmResponse.java rename to api/src/org/apache/cloudstack/api/response/IsoVmResponse.java index 29a898a2789..a667e50c5f9 --- a/api/src/com/cloud/api/response/IsoVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/IsoVmResponse.java @@ -14,15 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class IsoVmResponse extends BaseResponse { @SerializedName("id") @Param(description="the ISO ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName("name") @Param(description="the ISO name") private String name; @@ -37,13 +37,13 @@ public class IsoVmResponse extends BaseResponse { private Boolean featured; @SerializedName("ostypeid") @Param(description="the ID of the OS type for this template.") - private IdentityProxy osTypeId = new IdentityProxy("guest_os"); + private String osTypeId; @SerializedName("ostypename") @Param(description="the name of the OS type for this template.") private String osTypeName; @SerializedName("virtualmachineid") @Param(description="id of the virtual machine") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("vmname") @Param(description="name of the virtual machine") private String virtualMachineName; @@ -54,13 +54,18 @@ public class IsoVmResponse extends BaseResponse { @SerializedName("vmstate") @Param(description="state of the virtual machine") private String virtualMachineState; - - public Long getOsTypeId() { - return osTypeId.getValue(); + + @Override + public String getObjectId() { + return this.getId(); } - public void setOsTypeId(Long osTypeId) { - this.osTypeId.setValue(osTypeId); + public String getOsTypeId() { + return osTypeId; + } + + public void setOsTypeId(String osTypeId) { + this.osTypeId = osTypeId; } public String getOsTypeName() { @@ -71,12 +76,12 @@ public class IsoVmResponse extends BaseResponse { this.osTypeName = osTypeName; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -111,12 +116,12 @@ public class IsoVmResponse extends BaseResponse { this.featured = featured; } - public Long getVirtualMachineId() { - return virtualMachineId.getValue(); + public String getVirtualMachineId() { + return virtualMachineId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public String getVirtualMachineName() { diff --git a/api/src/com/cloud/api/response/LBStickinessPolicyResponse.java b/api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java similarity index 90% rename from api/src/com/cloud/api/response/LBStickinessPolicyResponse.java rename to api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java index 0d1212d705f..0eb4d58d50b 100644 --- a/api/src/com/cloud/api/response/LBStickinessPolicyResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LBStickinessPolicyResponse.java @@ -14,13 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.network.rules.StickinessPolicy; import com.cloud.serializer.Param; import com.cloud.utils.Pair; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; import java.util.List; import java.util.Map; @@ -29,8 +29,8 @@ import java.util.HashMap; public class LBStickinessPolicyResponse extends BaseResponse { @SerializedName("id") @Param(description = "the LB Stickiness policy ID") - private IdentityProxy id = new IdentityProxy("load_balancer_stickiness_policies"); - + private String id; + @SerializedName("name") @Param(description = "the name of the Stickiness policy") private String name; @@ -54,13 +54,13 @@ public class LBStickinessPolicyResponse extends BaseResponse { @SerializedName("params") @Param(description = "the params of the policy") private Map params; - + public Map getParams() { return params; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -82,7 +82,7 @@ public class LBStickinessPolicyResponse extends BaseResponse { public String getMethodName() { return methodName; } - + public String getState() { return state; } @@ -99,12 +99,12 @@ public class LBStickinessPolicyResponse extends BaseResponse { if (stickinesspolicy.isRevoke()) { this.setState("Revoked"); } - if (stickinesspolicy.getId() != 0) - setId(stickinesspolicy.getId()); + if (stickinesspolicy.getUuid() != null ) + setId(stickinesspolicy.getUuid()); - /* Get the param and values from the database and fill the response object - * The following loop is to - * 1) convert from List of Pair to Map + /* Get the param and values from the database and fill the response object + * The following loop is to + * 1) convert from List of Pair to Map * 2) combine all params with name with ":" , currently we have one param called "domain" that can appear multiple times. * */ @@ -118,7 +118,7 @@ public class LBStickinessPolicyResponse extends BaseResponse { { sb.append(":").append(tempParamList.get(key)); } - + tempParamList.put(key,sb.toString()); } diff --git a/api/src/com/cloud/api/response/LBStickinessResponse.java b/api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java similarity index 83% rename from api/src/com/cloud/api/response/LBStickinessResponse.java rename to api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java index 278fdf3bc03..7887e7c430a 100644 --- a/api/src/com/cloud/api/response/LBStickinessResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LBStickinessResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.rules.StickinessPolicy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; import java.util.List; +@EntityReference(value=StickinessPolicy.class) public class LBStickinessResponse extends BaseResponse { @SerializedName("lbruleid") @Param(description = "the LB rule ID") - private IdentityProxy lbRuleId = new IdentityProxy("firewall_rules"); + private String lbRuleId; @SerializedName("name") @Param(description = "the name of the Stickiness policy") @@ -39,10 +42,10 @@ public class LBStickinessResponse extends BaseResponse { @SerializedName("account") @Param(description = "the account of the Stickiness policy") private String accountName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the Stickiness policy") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description = "the domain of the Stickiness policy") @@ -51,17 +54,17 @@ public class LBStickinessResponse extends BaseResponse { @SerializedName("state") @Param(description = "the state of the policy") private String state; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description = "the id of the zone the Stickiness policy belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName("stickinesspolicy") @Param(description = "the list of stickinesspolicies", responseObject = LBStickinessPolicyResponse.class) private List stickinessPolicies; - public void setlbRuleId(Long lbRuleId) { - this.lbRuleId.setValue(lbRuleId); + public void setlbRuleId(String lbRuleId) { + this.lbRuleId = lbRuleId; } public void setRules(List policies) { @@ -79,11 +82,11 @@ public class LBStickinessResponse extends BaseResponse { public List getStickinessPolicies() { return stickinessPolicies; } - + public String getDescription() { return description; } - + public void setDescription(String description) { this.description = description; } @@ -96,14 +99,14 @@ public class LBStickinessResponse extends BaseResponse { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getDomainName() { return domainName; } diff --git a/api/src/com/cloud/api/response/LDAPConfigResponse.java b/api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java similarity index 95% rename from api/src/com/cloud/api/response/LDAPConfigResponse.java rename to api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java index 3e56c9566a3..e851e38e2bd 100644 --- a/api/src/com/cloud/api/response/LDAPConfigResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LDAPConfigResponse.java @@ -14,11 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class LDAPConfigResponse extends BaseResponse { @@ -98,6 +99,6 @@ public class LDAPConfigResponse extends BaseResponse { public void setBindPassword(String bindPassword) { this.bindPassword = bindPassword; } - + } diff --git a/api/src/com/cloud/api/response/LDAPRemoveResponse.java b/api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java similarity index 81% rename from api/src/com/cloud/api/response/LDAPRemoveResponse.java rename to api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java index b3cdd9c4da0..0feec5bc5b5 100644 --- a/api/src/com/cloud/api/response/LDAPRemoveResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LDAPRemoveResponse.java @@ -14,15 +14,13 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class LDAPRemoveResponse extends BaseResponse { - public LDAPRemoveResponse(){ - super(); - } + public LDAPRemoveResponse(){ + super(); + } } diff --git a/api/src/com/cloud/api/response/ListResponse.java b/api/src/org/apache/cloudstack/api/response/ListResponse.java similarity index 75% rename from api/src/com/cloud/api/response/ListResponse.java rename to api/src/org/apache/cloudstack/api/response/ListResponse.java index 47f76a52afa..3f28887f95e 100644 --- a/api/src/com/cloud/api/response/ListResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ListResponse.java @@ -14,14 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ResponseObject; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.ResponseObject; public class ListResponse extends BaseResponse { List responses; + private transient Integer count; public List getResponses() { return responses; @@ -31,11 +33,21 @@ public class ListResponse extends BaseResponse { this.responses = responses; } + public void setResponses(List responses, Integer count) { + this.responses = responses; + this.count = count; + } + + public Integer getCount() { + if (count != null) { + return count; + } + if (responses != null) { return responses.size(); - } else { - return null; } + + return null; } } diff --git a/api/src/com/cloud/api/response/LoadBalancerResponse.java b/api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java similarity index 82% rename from api/src/com/cloud/api/response/LoadBalancerResponse.java rename to api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java index 016bccc7188..bd5efdba1e4 100644 --- a/api/src/com/cloud/api/response/LoadBalancerResponse.java +++ b/api/src/org/apache/cloudstack/api/response/LoadBalancerResponse.java @@ -14,20 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class LoadBalancerResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "the load balancer rule ID") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description = "the name of the load balancer") @@ -39,7 +39,7 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description = "the public ip address id") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); + private String publicIpId; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description = "the public ip address") @@ -56,23 +56,23 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ALGORITHM) @Param(description = "the load balancer algorithm (source, roundrobin, leastconn)") private String algorithm; - + @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account of the load balancer rule") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the load balancer") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the load balancer") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the load balancer rule") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain of the load balancer rule") @@ -84,13 +84,13 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti @SerializedName(ApiConstants.ZONE_ID) @Param(description = "the id of the zone the rule belongs to") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with load balancer", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -125,8 +125,9 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -137,26 +138,26 @@ public class LoadBalancerResponse extends BaseResponse implements ControlledEnti this.state = state; } - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } - + } diff --git a/api/src/com/cloud/api/response/NetworkACLResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java similarity index 92% rename from api/src/com/cloud/api/response/NetworkACLResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java index 10f312b7631..e16a1a5a434 100644 --- a/api/src/com/cloud/api/response/NetworkACLResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkACLResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class NetworkACLResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the ACL") - private IdentityProxy id = new IdentityProxy("firewall_rules"); + private String id; @SerializedName(ApiConstants.PROTOCOL) @Param(description="the protocol of the ACL") private String protocol; @@ -39,25 +39,25 @@ public class NetworkACLResponse extends BaseResponse { @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type for the ACL") private String trafficType; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; @SerializedName(ApiConstants.CIDR_LIST) @Param(description="the cidr list to forward traffic from") private String cidrList; - + @SerializedName(ApiConstants.ICMP_TYPE) @Param(description= "type of the icmp message being sent") private Integer icmpType; @SerializedName(ApiConstants.ICMP_CODE) @Param(description = "error code for this icmp message") private Integer icmpCode; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the network ACLs", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setProtocol(String protocol) { @@ -91,7 +91,7 @@ public class NetworkACLResponse extends BaseResponse { public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/server/src/com/cloud/server/api/response/NetworkDeviceResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java similarity index 70% rename from server/src/com/cloud/server/api/response/NetworkDeviceResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java index 3cf76de1ab7..dc67b53e1ed 100644 --- a/server/src/com/cloud/server/api/response/NetworkDeviceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkDeviceResponse.java @@ -14,24 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class NetworkDeviceResponse extends BaseResponse { - @SerializedName(ApiConstants.ID) - @Param(description = "the ID of the network device") - private IdentityProxy id = new IdentityProxy("host"); + @SerializedName(ApiConstants.ID) + @Param(description = "the ID of the network device") + private String id; - public Long getId() { - return id.getValue(); - } + public String getId() { + return id; + } - public void setId(Long id) { - this.id.setValue(id); - } + public void setId(String id) { + this.id = id; + } } diff --git a/api/src/com/cloud/api/response/NetworkOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java similarity index 85% rename from api/src/com/cloud/api/response/NetworkOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java index 4b8abf921fa..5c1479105f8 100644 --- a/api/src/com/cloud/api/response/NetworkOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkOfferingResponse.java @@ -14,72 +14,75 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.NetworkOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=NetworkOffering.class) @SuppressWarnings("unused") -public class NetworkOfferingResponse extends BaseResponse{ +public class NetworkOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the network offering") - private final IdentityProxy id = new IdentityProxy("network_offerings"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the network offering") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the network offering.") private String displayText; - + @SerializedName(ApiConstants.TAGS) @Param(description="the tags for the network offering") private String tags; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date this network offering was created") private Date created; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage.") private String trafficType; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if network offering is default, false otherwise") private Boolean isDefault; - + @SerializedName(ApiConstants.SPECIFY_VLAN) @Param(description="true if network offering supports vlans, false otherwise") private Boolean specifyVlan; - + @SerializedName(ApiConstants.CONSERVE_MODE) @Param(description="true if network offering is ip conserve mode enabled") private Boolean conserveMode; @SerializedName(ApiConstants.SPECIFY_IP_RANGES) @Param(description="true if network offering supports specifying ip ranges, false otherwise") private Boolean specifyIpRanges; - + @SerializedName(ApiConstants.AVAILABILITY) @Param(description="availability of the network offering") private String availability; - + @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; @SerializedName(ApiConstants.STATE) @Param(description="state of the network offering. Can be Disabled/Enabled/Inactive") private String state; - + @SerializedName(ApiConstants.GUEST_IP_TYPE) @Param(description="guest type of the network offering, can be Shared or Isolated") private String guestIpType; - + @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering used by virtual router provider") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); - + private String serviceOfferingId; + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.FOR_VPC) @Param(description="true if network offering can be used by VPC networks only") private Boolean forVpc; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -89,7 +92,7 @@ public class NetworkOfferingResponse extends BaseResponse{ public void setDisplayText(String displayText) { this.displayText = displayText; } - + public void setTags(String tags) { this.tags = tags; } @@ -134,17 +137,14 @@ public class NetworkOfferingResponse extends BaseResponse{ this.guestIpType = type; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } - public void setServiceOfferingId(IdentityProxy serviceOfferingId) { - this.serviceOfferingId = serviceOfferingId; - } - - public void setSpecifyIpRanges(Boolean specifyIpRanges) { - this.specifyIpRanges = specifyIpRanges; - } + public void setSpecifyIpRanges(Boolean specifyIpRanges) { + this.specifyIpRanges = specifyIpRanges; + } public void setForVpc(Boolean forVpc) { this.forVpc = forVpc; diff --git a/api/src/com/cloud/api/response/NetworkResponse.java b/api/src/org/apache/cloudstack/api/response/NetworkResponse.java similarity index 78% rename from api/src/com/cloud/api/response/NetworkResponse.java rename to api/src/org/apache/cloudstack/api/response/NetworkResponse.java index a4158f16323..64cc9531901 100644 --- a/api/src/com/cloud/api/response/NetworkResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NetworkResponse.java @@ -14,134 +14,138 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Network; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.projects.ProjectAccount; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value = {Network.class, ProjectAccount.class}) public class NetworkResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.ID) @Param(description="the id of the network") - private IdentityProxy id = new IdentityProxy("networks"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the network") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the displaytext of the network") private String displaytext; - + @SerializedName("broadcastdomaintype") @Param(description="Broadcast domain type of the network") private String broadcastDomainType; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type of the network") private String trafficType; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the network's gateway") private String gateway; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the network's netmask") private String netmask; - + @SerializedName(ApiConstants.CIDR) @Param(description="the cidr the network") private String cidr; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the network") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the network belongs to") private String zoneName; - + @SerializedName("networkofferingid") @Param(description="network offering id the network is created from") - private IdentityProxy networkOfferingId = new IdentityProxy("network_offerings"); - + private String networkOfferingId; + @SerializedName("networkofferingname") @Param(description="name of the network offering the network is created from") private String networkOfferingName; - + @SerializedName("networkofferingdisplaytext") @Param(description="display text of the network offering the network is created from") private String networkOfferingDisplayText; - + @SerializedName("networkofferingavailability") @Param(description="availability of the network offering the network is created from") private String networkOfferingAvailability; - + @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="true if network is system, false otherwise") private Boolean isSystem; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the network") private String state; @SerializedName("related") @Param(description="related to what other network configuration") - private IdentityProxy related = new IdentityProxy("networks"); - - @SerializedName("broadcasturi") @Param(description="broadcast uri of the network") + private String related; + + @SerializedName("broadcasturi") @Param(description="broadcast uri of the network. This parameter is visible to ROOT admins only") private String broadcastUri; - + @SerializedName(ApiConstants.DNS1) @Param(description="the first DNS for the network") private String dns1; - + @SerializedName(ApiConstants.DNS2) @Param(description="the second DNS for the network") private String dns2; - + @SerializedName(ApiConstants.TYPE) @Param(description="the type of the network") private String type; - - @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the network") + + @SerializedName(ApiConstants.VLAN) @Param(description="The vlan of the network. This parameter is visible to ROOT admins only") private String vlan; - + @SerializedName(ApiConstants.ACL_TYPE) @Param(description="acl type - access type to the network") private String aclType; - + @SerializedName(ApiConstants.SUBDOMAIN_ACCESS) @Param(description="true if users from subdomains can access the domain level network") private Boolean subdomainAccess; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the network") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the network owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the network owner") private String domain; - + @SerializedName("isdefault") @Param(description="true if network is default, false otherwise") private Boolean isDefault; - + @SerializedName("service") @Param(description="the list of services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain") private String networkDomain; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network id") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.RESTART_REQUIRED) @Param(description="true network requires restart") private Boolean restartRequired; - + @SerializedName(ApiConstants.SPECIFY_IP_RANGES) @Param(description="true if network supports specifying ip ranges, false otherwise") private Boolean specifyIpRanges; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the network belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.CAN_USE_FOR_DEPLOY) @Param(description="list networks available for vm deployment") private Boolean canUseForDeploy; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with network", responseObject = ResourceTagResponse.class) private List tags; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -163,21 +167,21 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setNetmask(String netmask) { this.netmask = netmask; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - public void setNetworkOfferingId(Long networkOfferingId) { - this.networkOfferingId.setValue(networkOfferingId); + public void setNetworkOfferingId(String networkOfferingId) { + this.networkOfferingId = networkOfferingId; } public void setState(String state) { this.state = state; } - public void setRelated(Long related) { - this.related.setValue(related); + public void setRelated(String related) { + this.related = related; } public void setBroadcastUri(String broadcastUri) { @@ -200,8 +204,9 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setNetworkOfferingName(String networkOfferingName) { @@ -224,14 +229,14 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.isSystem = isSystem; } - public void setDomainName(String domain) { - this.domain = domain; - } + public void setDomainName(String domain) { + this.domain = domain; + } public void setNetworkOfferingAvailability(String networkOfferingAvailability) { this.networkOfferingAvailability = networkOfferingAvailability; } - + public void setServices(List services) { this.services = services; } @@ -243,10 +248,10 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -254,42 +259,42 @@ public class NetworkResponse extends BaseResponse implements ControlledEntityRes this.projectName = projectName; } - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public void setAclType(String aclType) { - this.aclType = aclType; - } - - public void setSubdomainAccess(Boolean subdomainAccess) { - this.subdomainAccess = subdomainAccess; - } - - public void setZoneName(String zoneName) { - this.zoneName = zoneName; - } - - public void setCidr(String cidr) { - this.cidr = cidr; - } - - public void setRestartRequired(Boolean restartRequired) { - this.restartRequired = restartRequired; - } - - public void setSpecifyIpRanges(Boolean specifyIpRanges) { - this.specifyIpRanges = specifyIpRanges; - } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + public void setAclType(String aclType) { + this.aclType = aclType; } - + + public void setSubdomainAccess(Boolean subdomainAccess) { + this.subdomainAccess = subdomainAccess; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public void setCidr(String cidr) { + this.cidr = cidr; + } + + public void setRestartRequired(Boolean restartRequired) { + this.restartRequired = restartRequired; + } + + public void setSpecifyIpRanges(Boolean specifyIpRanges) { + this.specifyIpRanges = specifyIpRanges; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + public void setCanUseForDeploy(Boolean canUseForDeploy) { this.canUseForDeploy = canUseForDeploy; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/NicResponse.java b/api/src/org/apache/cloudstack/api/response/NicResponse.java old mode 100755 new mode 100644 similarity index 82% rename from api/src/com/cloud/api/response/NicResponse.java rename to api/src/org/apache/cloudstack/api/response/NicResponse.java index 69d5c31f66c..a6ca5b8232d --- a/api/src/com/cloud/api/response/NicResponse.java +++ b/api/src/org/apache/cloudstack/api/response/NicResponse.java @@ -14,62 +14,63 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class NicResponse extends BaseResponse { - + @SerializedName("id") @Param(description="the ID of the nic") - private final IdentityProxy id = new IdentityProxy("nics"); + private String id; @SerializedName("networkid") @Param(description="the ID of the corresponding network") - private final IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName("networkname") @Param(description="the name of the corresponding network") private String networkName ; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the nic") private String netmask; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the nic") private String gateway; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the ip address of the nic") private String ipaddress; - + @SerializedName("isolationuri") @Param(description="the isolation uri of the nic") private String isolationUri; - + @SerializedName("broadcasturi") @Param(description="the broadcast uri of the nic") private String broadcastUri; - + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the traffic type of the nic") private String trafficType; - + @SerializedName(ApiConstants.TYPE) @Param(description="the type of the nic") private String type; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if nic is default, false otherwise") private Boolean isDefault; @SerializedName("macaddress") @Param(description="true if nic is default, false otherwise") private String macAddress; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public void setNetworkid(Long networkid) { - this.networkId.setValue(networkid); + + public void setNetworkid(String networkid) { + this.networkId = networkid; } public void setNetworkName(String networkname) { @@ -108,15 +109,16 @@ public class NicResponse extends BaseResponse { this.isDefault = isDefault; } - public void setMacAddress(String macAddress) { - this.macAddress = macAddress; - } + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } @Override public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((id == null) ? 0 : id.hashCode()); + String oid = this.getId(); + result = prime * result + ((oid== null) ? 0 : oid.hashCode()); return result; } @@ -129,12 +131,13 @@ public class NicResponse extends BaseResponse { if (getClass() != obj.getClass()) return false; NicResponse other = (NicResponse) obj; - if (id == null) { - if (other.id != null) + String oid = this.getId(); + if (oid == null) { + if (other.getId() != null) return false; - } else if (!id.equals(other.id)) + } else if (!oid.equals(other.getId())) return false; return true; } - + } diff --git a/api/src/com/cloud/api/response/PhysicalNetworkResponse.java b/api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java similarity index 82% rename from api/src/com/cloud/api/response/PhysicalNetworkResponse.java rename to api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java index 72f10755371..78257b1bd0f 100644 --- a/api/src/com/cloud/api/response/PhysicalNetworkResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PhysicalNetworkResponse.java @@ -14,39 +14,42 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetwork; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetwork.class) @SuppressWarnings("unused") -public class PhysicalNetworkResponse extends BaseResponse{ - +public class PhysicalNetworkResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) @Param(description="the uuid of the physical network") private String id; - + @SerializedName(ApiConstants.NAME) @Param(description="name of the physical network") private String name; - + @SerializedName(ApiConstants.BROADCAST_DOMAIN_RANGE) @Param(description="Broadcast domain range of the physical network") private String broadcastDomainRange; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the physical network") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.STATE) @Param(description="state of the physical network") private String state; @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the physical network") private String vlan; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the physical network owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.TAGS) @Param(description="comma separated tag") private String tags; @@ -56,41 +59,48 @@ public class PhysicalNetworkResponse extends BaseResponse{ @SerializedName(ApiConstants.NETWORK_SPEED) @Param(description="the speed of the physical network") private String networkSpeed; + + @Override + public String getObjectId() { + return this.id; + + } + public void setId(String uuid) { this.id = uuid; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setState(String state) { this.state = state; } - - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + + public void setDomainId(String domainId) { + this.domainId = domainId; } - + public void setVlan(String vlan) { this.vlan = vlan; } - + public void setTags(List tags) { if (tags == null || tags.size() == 0) { return; } - + StringBuilder buf = new StringBuilder(); for (String tag : tags) { buf.append(tag).append(","); } - + this.tags = buf.delete(buf.length()-1, buf.length()).toString(); } - + public void setBroadcastDomainRange(String broadcastDomainRange) { this.broadcastDomainRange = broadcastDomainRange; } @@ -103,16 +113,16 @@ public class PhysicalNetworkResponse extends BaseResponse{ if (isolationMethods == null || isolationMethods.size() == 0) { return; } - + StringBuilder buf = new StringBuilder(); for (String isolationMethod : isolationMethods) { buf.append(isolationMethod).append(","); } - + this.isolationMethods = buf.delete(buf.length()-1, buf.length()).toString(); } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/api/src/com/cloud/api/response/PodResponse.java b/api/src/org/apache/cloudstack/api/response/PodResponse.java old mode 100755 new mode 100644 similarity index 77% rename from api/src/com/cloud/api/response/PodResponse.java rename to api/src/org/apache/cloudstack/api/response/PodResponse.java index df4a70f0970..71192796b25 --- a/api/src/com/cloud/api/response/PodResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PodResponse.java @@ -14,24 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; + +import com.cloud.dc.Pod; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = Pod.class) public class PodResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the Pod") - private IdentityProxy id = new IdentityProxy("host_pod_ref"); + private String id; @SerializedName("name") @Param(description="the name of the Pod") private String name; @SerializedName("zoneid") @Param(description="the Zone ID of the Pod") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the Pod") private String zoneName; @@ -47,19 +51,19 @@ public class PodResponse extends BaseResponse { @SerializedName("endip") @Param(description="the ending IP for the Pod") private String endIp; - + @SerializedName("allocationstate") @Param(description="the allocation state of the Pod") - private String allocationState; + private String allocationState; @SerializedName("capacity") @Param(description="the capacity of the Pod", responseObject = CapacityResponse.class) private List capacitites; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -70,12 +74,12 @@ public class PodResponse extends BaseResponse { this.name = name; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -117,20 +121,20 @@ public class PodResponse extends BaseResponse { public void setEndIp(String endIp) { this.endIp = endIp; } - + public String getAllocationState() { - return allocationState; + return allocationState; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - public List getCapacitites() { - return capacitites; - } + public List getCapacitites() { + return capacitites; + } - public void setCapacitites(List capacitites) { - this.capacitites = capacitites; - } + public void setCapacitites(List capacitites) { + this.capacitites = capacitites; + } } diff --git a/api/src/com/cloud/api/response/PrivateGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java similarity index 76% rename from api/src/com/cloud/api/response/PrivateGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java index e901a70933f..37c96ff6a17 100644 --- a/api/src/com/cloud/api/response/PrivateGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/PrivateGatewayResponse.java @@ -14,66 +14,74 @@ // 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.api.ApiConstants; +package org.apache.cloudstack.api.response; +import com.cloud.network.vpc.VpcGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VpcGateway.class) @SuppressWarnings("unused") public class PrivateGatewayResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.ID) @Param(description="the id of the private gateway") - private IdentityProxy id = new IdentityProxy("vpc_gateways"); - + private String id; + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway") private String gateway; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the private gateway's netmask") private String netmask; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the private gateway's ip address") private String address; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the private gateway") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the private gateway belongs to") private String zoneName; - + @SerializedName(ApiConstants.VLAN) @Param(description="the vlan of the private gateway") private String vlan; - + @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the private gateaway belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - + private String vpcId; + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network id") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the private gateway") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the private gateway") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the private gateway") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the private gateway") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the private gateway") private String domainName; - + @SerializedName(ApiConstants.STATE) @Param(description="State of the gateway, can be Creating, Ready, Deleting") private String state; - - - public void setId(Long id) { - this.id.setValue(id); + + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setGateway(String gateway) { @@ -83,9 +91,9 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn public void setNetmask(String netmask) { this.netmask = netmask; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setVlan(String vlan) { @@ -95,37 +103,37 @@ public class PrivateGatewayResponse extends BaseResponse implements ControlledEn public void setZoneName(String zoneName) { this.zoneName = zoneName; } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } public void setAddress(String address) { this.address = address; } - public void setPhysicalNetworkId(Long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override diff --git a/api/src/com/cloud/api/response/ProjectAccountResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java similarity index 81% rename from api/src/com/cloud/api/response/ProjectAccountResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java index e613466634a..134841caf31 100644 --- a/api/src/com/cloud/api/response/ProjectAccountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectAccountResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.projects.ProjectAccount; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=ProjectAccount.class) @SuppressWarnings("unused") -public class ProjectAccountResponse extends BaseResponse implements ControlledEntityResponse { +public class ProjectAccountResponse extends BaseResponse implements ControlledViewEntityResponse { @SerializedName(ApiConstants.PROJECT_ID) @Param(description = "project id") - private IdentityProxy projectId = new IdentityProxy("projects"); + private String projectId; @SerializedName(ApiConstants.PROJECT) @Param(description = "project name") @@ -35,7 +38,7 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description = "the id of the account") - private IdentityProxy id = new IdentityProxy("account"); + private String accountId; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the name of the account") @@ -51,7 +54,7 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "id of the Domain the account belongs too") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "name of the Domain the account belongs too") @@ -61,16 +64,16 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn @Param(description = "the list of users associated with account", responseObject = UserResponse.class) private List users; - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } public void setProjectName(String projectName) { this.projectName = projectName; } - public void setId(Long id) { - this.id.setValue(id); + public void setAccountId(String id) { + this.accountId = id; } public void setAccountName(String accountName) { @@ -81,8 +84,8 @@ public class ProjectAccountResponse extends BaseResponse implements ControlledEn this.accountType = accountType; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { diff --git a/api/src/com/cloud/api/response/ProjectInvitationResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java similarity index 79% rename from api/src/com/cloud/api/response/ProjectInvitationResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java index abb47a7a664..0c9ce685bcc 100644 --- a/api/src/com/cloud/api/response/ProjectInvitationResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectInvitationResponse.java @@ -14,53 +14,56 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.projects.ProjectInvitation; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=ProjectInvitation.class) @SuppressWarnings("unused") -public class ProjectInvitationResponse extends BaseResponse implements ControlledEntityResponse{ +public class ProjectInvitationResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the id of the invitation") - private IdentityProxy id = new IdentityProxy("project_invitations"); - + private String id; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the id of the project") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the name of the project") private String projectName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id the project belongs to") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name where the project belongs to") private String domainName; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name of the project's owner") private String accountName; - + @SerializedName(ApiConstants.EMAIL) @Param(description="the email the invitation was sent to") private String email; - + @SerializedName(ApiConstants.STATE) @Param(description="the invitation state") private String invitationState; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } public void setProjectName(String projectName) { this.projectName = projectName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domain) { diff --git a/api/src/com/cloud/api/response/ProjectResponse.java b/api/src/org/apache/cloudstack/api/response/ProjectResponse.java similarity index 77% rename from api/src/com/cloud/api/response/ProjectResponse.java rename to api/src/org/apache/cloudstack/api/response/ProjectResponse.java index 2735980a6e4..7ecda234814 100644 --- a/api/src/com/cloud/api/response/ProjectResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProjectResponse.java @@ -14,45 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; +import java.util.ArrayList; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.projects.Project; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Project.class) @SuppressWarnings("unused") -public class ProjectResponse extends BaseResponse{ - +public class ProjectResponse extends BaseResponse { + @SerializedName(ApiConstants.ID) @Param(description="the id of the project") - private IdentityProxy id = new IdentityProxy("projects"); - + private String id; + @SerializedName(ApiConstants.NAME) @Param(description="the name of the project") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the displaytext of the project") private String displaytext; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id the project belongs to") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name where the project belongs to") private String domain; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name of the project's owner") private String ownerName; - + @SerializedName(ApiConstants.STATE) @Param(description="the state of the project") private String state; - - @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) - private List tags; - - public void setId(Long id) { - this.id.setValue(id); + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) + private List tags = new ArrayList(); + + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -63,8 +67,8 @@ public class ProjectResponse extends BaseResponse{ this.displaytext = displaytext; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomain(String domain) { @@ -78,8 +82,12 @@ public class ProjectResponse extends BaseResponse{ public void setState(String state) { this.state = state; } - + public void setTags(List tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/ProviderResponse.java b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java similarity index 76% rename from api/src/com/cloud/api/response/ProviderResponse.java rename to api/src/org/apache/cloudstack/api/response/ProviderResponse.java index d8a5eb6bd62..b83c2348390 100644 --- a/api/src/com/cloud/api/response/ProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ProviderResponse.java @@ -14,39 +14,42 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetworkServiceProvider; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetworkServiceProvider.class) @SuppressWarnings("unused") public class ProviderResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the provider name") private String name; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.DEST_PHYSICAL_NETWORK_ID) @Param(description="the destination physical network") - private IdentityProxy destinationPhysicalNetworkId = new IdentityProxy("physical_network"); - + private String destinationPhysicalNetworkId; + @SerializedName(ApiConstants.STATE) @Param(description="state of the network provider") private String state; @SerializedName(ApiConstants.ID) @Param(description="uuid of the network provider") private String id; - + @SerializedName(ApiConstants.SERVICE_LIST) @Param(description="services for this provider") private List services; - + @SerializedName(ApiConstants.CAN_ENABLE_INDIVIDUAL_SERVICE) @Param(description="true if individual services can be enabled/disabled") private Boolean canEnableIndividualServices; - + public void setName(String name) { this.name = name; } @@ -54,27 +57,27 @@ public class ProviderResponse extends BaseResponse { public String getName() { return name; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); - } - - public void setDestinationPhysicalNetworkId(long destPhysicalNetworkId) { - this.destinationPhysicalNetworkId.setValue(destPhysicalNetworkId); + public String getphysicalNetworkId() { + return physicalNetworkId; } - public long getDestinationPhysicalNetworkId() { - return destinationPhysicalNetworkId.getValue(); + public void setDestinationPhysicalNetworkId(String destPhysicalNetworkId) { + this.destinationPhysicalNetworkId = destPhysicalNetworkId; + } + + public String getDestinationPhysicalNetworkId() { + return destinationPhysicalNetworkId; } public void setState(String state) { this.state = state; } - + public String getState() { return this.state; } @@ -82,24 +85,24 @@ public class ProviderResponse extends BaseResponse { public void setId(String uuid) { this.id = uuid; } - + public String getId() { return this.id; } - + public void setServices(List services) { this.services = services; } - + public List getServices() { return services; } - + public Boolean getCanEnableIndividualServices() { return canEnableIndividualServices; } public void setCanEnableIndividualServices(Boolean canEnableIndividualServices) { this.canEnableIndividualServices = canEnableIndividualServices; - } + } } diff --git a/api/src/com/cloud/api/response/RegisterResponse.java b/api/src/org/apache/cloudstack/api/response/RegisterResponse.java similarity index 94% rename from api/src/com/cloud/api/response/RegisterResponse.java rename to api/src/org/apache/cloudstack/api/response/RegisterResponse.java index 6f9f3404b31..eee924940fb 100644 --- a/api/src/com/cloud/api/response/RegisterResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RegisterResponse.java @@ -14,10 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class RegisterResponse extends BaseResponse { @SerializedName("apikey") @Param(description="the api key of the registered user") diff --git a/api/src/com/cloud/api/response/RemoteAccessVpnResponse.java b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java similarity index 68% rename from api/src/com/cloud/api/response/RemoteAccessVpnResponse.java rename to api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java index c6fe4d43fb6..3fd7d7a668b 100644 --- a/api/src/com/cloud/api/response/RemoteAccessVpnResponse.java +++ b/api/src/org/apache/cloudstack/api/response/RemoteAccessVpnResponse.java @@ -14,22 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.RemoteAccessVpn; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=RemoteAccessVpn.class) @SuppressWarnings("unused") public class RemoteAccessVpnResponse extends BaseResponse implements ControlledEntityResponse{ - + @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description="the public ip address of the vpn server") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); - + private String publicIpId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public ip address of the vpn server") private String publicIp; - + @SerializedName("iprange") @Param(description="the range of ips to allocate to the clients") private String ipRange; @@ -38,62 +41,63 @@ public class RemoteAccessVpnResponse extends BaseResponse implements ControlledE @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account of the remote access vpn") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the account of the remote access vpn") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the account of the remote access vpn") - private String domainName; - + private String domainName; + @SerializedName(ApiConstants.STATE) @Param(description="the state of the rule") private String state; - public void setPublicIp(String publicIp) { - this.publicIp = publicIp; - } + public void setPublicIp(String publicIp) { + this.publicIp = publicIp; + } - public void setIpRange(String ipRange) { - this.ipRange = ipRange; - } + public void setIpRange(String ipRange) { + this.ipRange = ipRange; + } - public void setPresharedKey(String presharedKey) { - this.presharedKey = presharedKey; - } + public void setPresharedKey(String presharedKey) { + this.presharedKey = presharedKey; + } - public void setAccountName(String accountName) { - this.accountName = accountName; - } + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } - public void setDomainName(String name) { - this.domainName = name; - } + public void setDomainName(String name) { + this.domainName = name; + } public void setState(String state) { this.state = state; } - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + } diff --git a/api/src/com/cloud/api/response/ResourceCountResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java similarity index 86% rename from api/src/com/cloud/api/response/ResourceCountResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java index 73fe44fe92d..9e62f4ff7f5 100644 --- a/api/src/com/cloud/api/response/ResourceCountResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceCountResponse.java @@ -14,27 +14,28 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class ResourceCountResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account for which resource count's are updated") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id for which resource count's are updated") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name for which resource count's are updated") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID for which resource count's are updated") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name for which resource count's are updated") private String domainName; @@ -51,8 +52,8 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -67,15 +68,15 @@ public class ResourceCountResponse extends BaseResponse implements ControlledEnt public void setResourceCount(Long resourceCount) { this.resourceCount = resourceCount; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + } diff --git a/api/src/com/cloud/api/response/ResourceLimitResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java similarity index 83% rename from api/src/com/cloud/api/response/ResourceLimitResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java index f41feca554a..c01e12f2e23 100644 --- a/api/src/com/cloud/api/response/ResourceLimitResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceLimitResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.configuration.ResourceLimit; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = ResourceLimit.class) @SuppressWarnings("unused") public class ResourceLimitResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account of the resource limit") private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the resource limit") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the resource limit") private String domainName; @@ -37,33 +40,33 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt @SerializedName("max") @Param(description="the maximum number of the resource. A -1 means the resource currently has no limit.") private Long max; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the resource limit") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the resource limit") private String projectName; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - + @Override public void setProjectName(String projectName) { this.projectName = projectName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + public void setResourceType(String resourceType) { this.resourceType = resourceType; } @@ -73,7 +76,7 @@ public class ResourceLimitResponse extends BaseResponse implements ControlledEnt } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } } diff --git a/api/src/com/cloud/api/response/ResourceTagResponse.java b/api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java similarity index 82% rename from api/src/com/cloud/api/response/ResourceTagResponse.java rename to api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java index 13566a73732..30bcbfd38a2 100644 --- a/api/src/com/cloud/api/response/ResourceTagResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ResourceTagResponse.java @@ -14,45 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") -public class ResourceTagResponse extends BaseResponse implements ControlledEntityResponse{ +public class ResourceTagResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.KEY) @Param(description="tag key name") private String key; - + @SerializedName(ApiConstants.VALUE) @Param(description="tag value") private String value; - + @SerializedName(ApiConstants.RESOURCE_TYPE) @Param(description="resource type") private String resourceType; - + @SerializedName(ApiConstants.RESOURCE_ID) @Param(description="id of the resource") - private String id; - + private String resourceId; + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the tag") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id the tag belongs to") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name where tag belongs to") private String projectName; - + @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the tag") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the tag") private String domainName; - + @SerializedName(ApiConstants.CUSTOMER) @Param(description="customer associated with the tag") private String customer; @@ -68,32 +68,35 @@ public class ResourceTagResponse extends BaseResponse implements ControlledEntit this.resourceType = resourceType; } - public void setId(String id) { - this.id = id; + public void setResourceId(String id) { + this.resourceId = id; } - + + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } - + + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } - + @Override public void setProjectName(String projectName) { this.projectName = projectName; - } - + } + public void setCustomer(String customer) { this.customer = customer; } diff --git a/api/src/org/apache/cloudstack/api/response/S3Response.java b/api/src/org/apache/cloudstack/api/response/S3Response.java new file mode 100644 index 00000000000..5dd0ef0e041 --- /dev/null +++ b/api/src/org/apache/cloudstack/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 org.apache.cloudstack.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/api/response/SSHKeyPairResponse.java b/api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java similarity index 66% rename from api/src/com/cloud/api/response/SSHKeyPairResponse.java rename to api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java index 16a29974338..606636382a1 100644 --- a/api/src/com/cloud/api/response/SSHKeyPairResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SSHKeyPairResponse.java @@ -14,57 +14,58 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SSHKeyPairResponse extends BaseResponse { - + @SerializedName(ApiConstants.NAME) @Param(description="Name of the keypair") private String name; @SerializedName("fingerprint") @Param(description="Fingerprint of the public key") private String fingerprint; - + @SerializedName("privatekey") @Param(description="Private key") private String privateKey; public SSHKeyPairResponse() {} - + public SSHKeyPairResponse(String name, String fingerprint) { - this(name, fingerprint, null); + this(name, fingerprint, null); } - + public SSHKeyPairResponse(String name, String fingerprint, String privateKey) { - this.name = name; - this.fingerprint = fingerprint; - this.privateKey = privateKey; + this.name = name; + this.fingerprint = fingerprint; + this.privateKey = privateKey; } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } + public String getName() { + return name; + } - public String getFingerprint() { - return fingerprint; - } + public void setName(String name) { + this.name = name; + } - public void setFingerprint(String fingerprint) { - this.fingerprint = fingerprint; - } + public String getFingerprint() { + return fingerprint; + } - public String getPrivateKey() { - return privateKey; - } + public void setFingerprint(String fingerprint) { + this.fingerprint = fingerprint; + } + + public String getPrivateKey() { + return privateKey; + } + + public void setPrivateKey(String privateKey) { + this.privateKey = privateKey; + } - public void setPrivateKey(String privateKey) { - this.privateKey = privateKey; - } - } diff --git a/api/src/com/cloud/api/response/SecurityGroupResponse.java b/api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java similarity index 68% rename from api/src/com/cloud/api/response/SecurityGroupResponse.java rename to api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java index 5c6deedfb34..f3b9beb8d3e 100644 --- a/api/src/com/cloud/api/response/SecurityGroupResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SecurityGroupResponse.java @@ -14,19 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.security.SecurityGroup; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") -public class SecurityGroupResponse extends BaseResponse implements ControlledEntityResponse{ +@EntityReference(value = SecurityGroup.class) +public class SecurityGroupResponse extends BaseResponse implements ControlledViewEntityResponse{ + @SerializedName(ApiConstants.ID) @Param(description="the ID of the security group") - private IdentityProxy id = new IdentityProxy("security_group"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the security group") private String name; @@ -36,36 +41,52 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account owning the security group") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the group") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the group") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the security group") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the security group") private String domainName; @SerializedName("ingressrule") @Param(description="the list of ingress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class) - private List ingressRules; + private Set ingressRules; @SerializedName("egressrule") @Param(description="the list of egress rules associated with the security group", responseObject = SecurityGroupRuleResponse.class) - private List egressRules; - + private Set egressRules; + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the rule", responseObject = ResourceTagResponse.class) - private List tags; - - public void setId(Long id) { - this.id.setValue(id); + private Set tags; + + public SecurityGroupResponse(){ + this.ingressRules = new HashSet(); + this.egressRules = new HashSet(); + this.tags = new HashSet(); } - - public Long getId() { - return id.getValue(); + + + + @Override + public String getObjectId() { + return this.getId(); } + + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public void setName(String name) { this.name = name; } @@ -78,25 +99,29 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { this.domainName = domainName; } - public void setSecurityGroupIngressRules(List securityGroupRules) { + public void setSecurityGroupIngressRules(Set securityGroupRules) { this.ingressRules = securityGroupRules; } - public void setSecurityGroupEgressRules(List securityGroupRules) { + public void addSecurityGroupIngressRule(SecurityGroupRuleResponse rule){ + this.ingressRules.add(rule); + } + + public void setSecurityGroupEgressRules(Set securityGroupRules) { this.egressRules = securityGroupRules; } - - @Override - public Long getObjectId() { - return getId(); + + public void addSecurityGroupEgressRule(SecurityGroupRuleResponse rule){ + this.egressRules.add(rule); } @Override @@ -123,18 +148,22 @@ public class SecurityGroupResponse extends BaseResponse implements ControlledEnt return false; return true; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setTags(List tags) { + + public void setTags(Set tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/SecurityGroupRuleResponse.java b/api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java similarity index 73% rename from api/src/com/cloud/api/response/SecurityGroupRuleResponse.java rename to api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java index f55b810ac33..19aaa4594b9 100644 --- a/api/src/com/cloud/api/response/SecurityGroupRuleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SecurityGroupRuleResponse.java @@ -14,16 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.security.SecurityGroupRules; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +@EntityReference(value = SecurityGroupRules.class) public class SecurityGroupRuleResponse extends BaseResponse { @SerializedName("ruleid") @Param(description="the id of the security group rule") - private IdentityProxy ruleId = new IdentityProxy("security_group_rule"); + private String ruleId; @SerializedName("protocol") @Param(description="the protocol of the security group rule") private String protocol; @@ -49,12 +52,12 @@ public class SecurityGroupRuleResponse extends BaseResponse { @SerializedName(ApiConstants.CIDR) @Param(description="the CIDR notation for the base IP address of the security group rule") private String cidr; - public Long getRuleId() { - return ruleId.getValue(); + public String getRuleId() { + return ruleId; } - public void setRuleId(Long ruleId) { - this.ruleId.setValue(ruleId); + public void setRuleId(String ruleId) { + this.ruleId = ruleId; } public String getProtocol() { @@ -120,4 +123,31 @@ public class SecurityGroupRuleResponse extends BaseResponse { public void setCidr(String cidr) { this.cidr = cidr; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + String oid = this.getRuleId(); + result = prime * result + ((oid== null) ? 0 : oid.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; + SecurityGroupRuleResponse other = (SecurityGroupRuleResponse) obj; + String oid = this.getRuleId(); + if (oid == null) { + if (other.getRuleId() != null) + return false; + } else if (!oid.equals(other.getRuleId())) + return false; + return true; + } } diff --git a/api/src/com/cloud/api/response/ServiceOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java similarity index 82% rename from api/src/com/cloud/api/response/ServiceOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java index fe0efc07df9..7a10f7f7673 100644 --- a/api/src/com/cloud/api/response/ServiceOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceOfferingResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.offering.ServiceOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = ServiceOffering.class) public class ServiceOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the service offering") - private IdentityProxy id = new IdentityProxy("disk_offering"); + private String id; @SerializedName("name") @Param(description="the name of the service offering") private String name; @@ -50,21 +53,21 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName("offerha") @Param(description="the ha support in the service offering") private Boolean offerHa; - + @SerializedName("limitcpuuse") @Param(description="restrict the CPU usage to committed service offering") private Boolean limitCpuUse; - + @SerializedName("tags") @Param(description="the tags for the service offering") private String tags; - @SerializedName("domainid") @Param(description="the domain id of the service offering") - private IdentityProxy domainId = new IdentityProxy("domain"); - + @SerializedName("domainid") @Param(description="the domain id of the service offering") + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="Domain name for the offering") private String domain; - + @SerializedName(ApiConstants.HOST_TAGS) @Param(description="the host tag for the service offering") - private String hostTag; + private String hostTag; @SerializedName(ApiConstants.IS_SYSTEM_OFFERING) @Param(description="is this a system vm offering") private Boolean isSystem; @@ -74,17 +77,17 @@ public class ServiceOfferingResponse extends BaseResponse { @SerializedName(ApiConstants.SYSTEM_VM_TYPE) @Param(description="is this a the systemvm type for system vm offering") private String vm_type; - + @SerializedName(ApiConstants.NETWORKRATE) @Param(description="data transfer rate in megabits per second allowed.") private Integer networkRate; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getName() { @@ -94,11 +97,11 @@ public class ServiceOfferingResponse extends BaseResponse { public void setName(String name) { this.name = name; } - + public Boolean getIsSystem() { return isSystem; } - + public void setIsSystemOffering(Boolean isSystem) { this.isSystem = isSystem; } @@ -107,16 +110,16 @@ public class ServiceOfferingResponse extends BaseResponse { public Boolean getDefaultUse() { return defaultUse; } - + public void setDefaultUse(Boolean defaultUse) { this.defaultUse = defaultUse; } - + public String getSystemVmType() { return vm_type; } - + public void setSystemVmType(String vmtype) { this.vm_type = vmtype; } @@ -179,13 +182,13 @@ public class ServiceOfferingResponse extends BaseResponse { } public Boolean getLimitCpuUse() { - return limitCpuUse; + return limitCpuUse; } - + public void setLimitCpuUse(Boolean limitCpuUse) { - this.limitCpuUse = limitCpuUse; + this.limitCpuUse = limitCpuUse; } - + public String getTags() { return tags; } @@ -194,29 +197,29 @@ public class ServiceOfferingResponse extends BaseResponse { this.tags = tags; } - public Long getDomainId() { - return domainId.getValue(); - } + public String getDomainId() { + return domainId; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + public void setDomainId(String domainId) { + this.domainId = domainId; + } - public String getDomain() { - return domain; - } + public String getDomain() { + return domain; + } - public void setDomain(String domain) { - this.domain = domain; - } - - public String getHostTag() { - return hostTag; - } + public void setDomain(String domain) { + this.domain = domain; + } - public void setHostTag(String hostTag) { - this.hostTag = hostTag; - } + public String getHostTag() { + return hostTag; + } + + public void setHostTag(String hostTag) { + this.hostTag = hostTag; + } public void setNetworkRate(Integer networkRate) { this.networkRate = networkRate; diff --git a/api/src/com/cloud/api/response/ServiceResponse.java b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java similarity index 92% rename from api/src/com/cloud/api/response/ServiceResponse.java rename to api/src/org/apache/cloudstack/api/response/ServiceResponse.java index 3c73e927053..11f7d710383 100644 --- a/api/src/com/cloud/api/response/ServiceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ServiceResponse.java @@ -14,23 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; @SuppressWarnings("unused") public class ServiceResponse extends BaseResponse { @SerializedName(ApiConstants.NAME) @Param(description="the service name") private String name; - + @SerializedName(ApiConstants.PROVIDER) @Param(description="the service provider name") private List providers; - + @SerializedName("capability") @Param(description="the list of capabilities", responseObject = CapabilityResponse.class) private List capabilities; @@ -45,4 +46,4 @@ public class ServiceResponse extends BaseResponse { public void setProviders(List providers) { this.providers = providers; } -} \ No newline at end of file +} diff --git a/api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java similarity index 86% rename from api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java index 7c706f3452a..d164580bdea 100644 --- a/api/src/com/cloud/api/response/Site2SiteCustomerGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteCustomerGatewayResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteCustomerGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteCustomerGateway.class) @SuppressWarnings("unused") public class Site2SiteCustomerGatewayResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_customer_gateway"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="name of the customer gateway") private String name; @@ -45,41 +48,41 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co @SerializedName(ApiConstants.IKE_POLICY) @Param(description="IKE policy of customer gateway") private String ikePolicy; - + @SerializedName(ApiConstants.ESP_POLICY) @Param(description="IPsec policy of customer gateway") private String espPolicy; - + @SerializedName(ApiConstants.IKE_LIFETIME) @Param(description="Lifetime of IKE SA of customer gateway") private Long ikeLifetime; - + @SerializedName(ApiConstants.ESP_LIFETIME) @Param(description="Lifetime of ESP SA of customer gateway") private Long espLifetime; - + @SerializedName(ApiConstants.DPD) @Param(description="if DPD is enabled for customer gateway") private Boolean dpd; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - + public void setId(String id) { + this.id = id; + } + public void setName(String name) { this.name = name; } @@ -98,40 +101,40 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co public void setIpsecPsk(String ipsecPsk) { this.ipsecPsk = ipsecPsk; - } - + } + public void setIkePolicy(String ikePolicy) { this.ikePolicy = ikePolicy; - } - + } + public void setEspPolicy(String espPolicy) { this.espPolicy = espPolicy; - } - + } + public void setIkeLifetime(Long ikeLifetime) { this.ikeLifetime = ikeLifetime; - } - + } + public void setEspLifetime(Long espLifetime) { this.espLifetime = espLifetime; - } - + } + public void setDpd(Boolean dpd) { this.dpd= dpd; - } - + } + public void setRemoved(Date removed) { this.removed = removed; - } - + } + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -140,8 +143,8 @@ public class Site2SiteCustomerGatewayResponse extends BaseResponse implements Co } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java similarity index 79% rename from api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java index 1af50178172..c398116a9f8 100644 --- a/api/src/com/cloud/api/response/Site2SiteVpnConnectionResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnConnectionResponse.java @@ -14,29 +14,32 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteVpnConnection; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteVpnConnection.class) @SuppressWarnings("unused") public class Site2SiteVpnConnectionResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_vpn_connection"); + private String id; @SerializedName(ApiConstants.S2S_VPN_GATEWAY_ID) @Param(description="the vpn gateway ID") - private IdentityProxy vpnGatewayId= new IdentityProxy("s2s_vpn_gateway"); - + private String vpnGatewayId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address") //from VpnGateway private String ip; @SerializedName(ApiConstants.S2S_CUSTOMER_GATEWAY_ID) @Param(description="the customer gateway ID") - private IdentityProxy customerGatewayId = new IdentityProxy("s2s_customer_gateway"); - + private String customerGatewayId; + @SerializedName(ApiConstants.GATEWAY) @Param(description="public ip address id of the customer gateway") //from CustomerGateway private String gatewayIp; @@ -54,85 +57,85 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont @SerializedName(ApiConstants.IKE_LIFETIME) @Param(description="Lifetime of IKE SA of customer gateway") //from CustomerGateway private Long ikeLifetime; - + @SerializedName(ApiConstants.ESP_LIFETIME) @Param(description="Lifetime of ESP SA of customer gateway") //from CustomerGateway private Long espLifetime; - + @SerializedName(ApiConstants.DPD) @Param(description="if DPD is enabled for customer gateway") //from CustomerGateway private Boolean dpd; - + @SerializedName(ApiConstants.STATE) @Param(description="State of vpn connection") private String state; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date and time the host was created") private Date created; @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - - public void setVpnGatewayId(Long vpnGatewayId) { - this.vpnGatewayId.setValue(vpnGatewayId); + public void setId(String id) { + this.id = id; + } + + public void setVpnGatewayId(String vpnGatewayId) { + this.vpnGatewayId = vpnGatewayId; } public void setIp(String ip) { - this.ip = ip; - } - - public void setCustomerGatewayId(Long customerGatewayId) { - this.customerGatewayId.setValue(customerGatewayId); + this.ip = ip; } - + + public void setCustomerGatewayId(String customerGatewayId) { + this.customerGatewayId = customerGatewayId; + } + public void setGatewayIp(String gatewayIp) { - this.gatewayIp = gatewayIp; + this.gatewayIp = gatewayIp; } - + public void setGuestCidrList(String guestCidrList) { - this.guestCidrList = guestCidrList; + this.guestCidrList = guestCidrList; } - + public void setIpsecPsk(String ipsecPsk) { - this.ipsecPsk = ipsecPsk; + this.ipsecPsk = ipsecPsk; } - + public void setIkePolicy(String ikePolicy) { - this.ikePolicy = ikePolicy; + this.ikePolicy = ikePolicy; } - + public void setEspPolicy(String espPolicy) { - this.espPolicy = espPolicy; + this.espPolicy = espPolicy; } - + public void setIkeLifetime(Long ikeLifetime) { this.ikeLifetime = ikeLifetime; - } - + } + public void setEspLifetime(Long espLifetime) { this.espLifetime = espLifetime; - } - + } + public void setDpd(Boolean dpd) { this.dpd= dpd; - } - + } + public void setState(String state) { this.state = state; } @@ -143,7 +146,7 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont public void setRemoved(Date removed) { this.removed = removed; - } + } @Override public void setAccountName(String accountName) { @@ -151,8 +154,8 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -161,8 +164,8 @@ public class Site2SiteVpnConnectionResponse extends BaseResponse implements Cont } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java similarity index 75% rename from api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java rename to api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java index b1eaffdced6..8cb06fc8a56 100644 --- a/api/src/com/cloud/api/response/Site2SiteVpnGatewayResponse.java +++ b/api/src/org/apache/cloudstack/api/response/Site2SiteVpnGatewayResponse.java @@ -14,68 +14,71 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.Site2SiteVpnGateway; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Site2SiteVpnGateway.class) @SuppressWarnings("unused") public class Site2SiteVpnGatewayResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the vpn gateway ID") - private IdentityProxy id = new IdentityProxy("s2s_vpn_gateway"); + private String id; @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="the public IP address") private String ip; @SerializedName(ApiConstants.VPC_ID) @Param(description="the vpc id of this gateway") - private IdentityProxy vpcId = new IdentityProxy("vpc"); + private String vpcId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.REMOVED) @Param(description="the date and time the host was removed") private Date removed; - public void setId(Long id) { - this.id.setValue(id); - } - - public void setIp(String ip) { - this.ip = ip; - } - - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); - } - + public void setId(String id) { + this.id = id; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public void setVpcId(String vpcId) { + this.vpcId = vpcId; + } + public void setRemoved(Date removed) { this.removed = removed; - } - + } + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -84,8 +87,8 @@ public class Site2SiteVpnGatewayResponse extends BaseResponse implements Control } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override diff --git a/api/src/com/cloud/api/response/SnapshotPolicyResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java similarity index 81% rename from api/src/com/cloud/api/response/SnapshotPolicyResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java index ac1b6cbe3ae..6bf77a04298 100644 --- a/api/src/com/cloud/api/response/SnapshotPolicyResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotPolicyResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; +import com.cloud.storage.snapshot.SnapshotPolicy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=SnapshotPolicy.class) public class SnapshotPolicyResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the snapshot policy") - private IdentityProxy id = new IdentityProxy("snapshot_policy"); + private String id; @SerializedName("volumeid") @Param(description="the ID of the disk volume") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName("schedule") @Param(description="time the snapshot is scheduled to be taken.") private String schedule; @@ -39,20 +42,20 @@ public class SnapshotPolicyResponse extends BaseResponse { @SerializedName("timezone") @Param(description="the time zone of the snapshot policy") private String timezone; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getVolumeId() { - return volumeId.getValue(); + public String getVolumeId() { + return volumeId; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } public String getSchedule() { diff --git a/api/src/com/cloud/api/response/SnapshotResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java similarity index 81% rename from api/src/com/cloud/api/response/SnapshotResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotResponse.java index 71b1b14b8b5..8ea0d7fb87f 100644 --- a/api/src/com/cloud/api/response/SnapshotResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotResponse.java @@ -14,22 +14,24 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.Snapshot; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Snapshot.class) @SuppressWarnings("unused") public class SnapshotResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description = "ID of the snapshot") - private IdentityProxy id = new IdentityProxy("snapshots"); + private String id; @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the snapshot") @@ -37,15 +39,15 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the domain ID of the snapshot's account") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain name of the snapshot's account") private String domainName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the snapshot") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the snapshot") private String projectName; @@ -55,7 +57,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.VOLUME_ID) @Param(description = "ID of the disk volume") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName(ApiConstants.VOLUME_NAME) @Param(description = "name of the disk volume") @@ -66,7 +68,7 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe private String volumeType; @SerializedName(ApiConstants.CREATED) - @Param(description = " the date the snapshot was created") + @Param(description = " the date the snapshot was created") private Date created; @SerializedName(ApiConstants.NAME) @@ -80,21 +82,22 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe @SerializedName(ApiConstants.STATE) @Param(description = "the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage") private Snapshot.Status state; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with snapshot", responseObject = ResourceTagResponse.class) private List tags; + @Override - public Long getObjectId() { - return getId(); - } - - private Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + private String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getAccountName() { @@ -105,12 +108,13 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe this.accountName = accountName; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -121,8 +125,8 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe this.snapshotType = snapshotType; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } public void setVolumeName(String volumeName) { @@ -150,15 +154,15 @@ public class SnapshotResponse extends BaseResponse implements ControlledEntityRe } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/SnapshotScheduleResponse.java b/api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java similarity index 67% rename from api/src/com/cloud/api/response/SnapshotScheduleResponse.java rename to api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java index 37f82b83290..19bb189467b 100644 --- a/api/src/com/cloud/api/response/SnapshotScheduleResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SnapshotScheduleResponse.java @@ -14,49 +14,49 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SnapshotScheduleResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the snapshot schedule") - private IdentityProxy id = new IdentityProxy("snapshot_schedule"); + private String id; @SerializedName("volumeid") @Param(description="the volume ID the snapshot schedule applied for") - private IdentityProxy volumeId = new IdentityProxy("volumes"); + private String volumeId; @SerializedName("snapshotpolicyid") @Param(description="the snapshot policy ID used by the snapshot schedule") - private IdentityProxy snapshotPolicyId = new IdentityProxy("snapshot_policy"); + private String snapshotPolicyId; @SerializedName("scheduled") @Param(description="time the snapshot is scheduled to be taken") private Date scheduled; - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getVolumeId() { - return volumeId.getValue(); + public String getVolumeId() { + return volumeId; } - public void setVolumeId(Long volumeId) { - this.volumeId.setValue(volumeId); + public void setVolumeId(String volumeId) { + this.volumeId = volumeId; } - public Long getSnapshotPolicyId() { - return snapshotPolicyId.getValue(); + public String getSnapshotPolicyId() { + return snapshotPolicyId; } - public void setSnapshotPolicyId(Long snapshotPolicyId) { - this.snapshotPolicyId.setValue(snapshotPolicyId); + public void setSnapshotPolicyId(String snapshotPolicyId) { + this.snapshotPolicyId = snapshotPolicyId; } public Date getScheduled() { diff --git a/api/src/com/cloud/api/response/StaticRouteResponse.java b/api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java similarity index 77% rename from api/src/com/cloud/api/response/StaticRouteResponse.java rename to api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java index 0b950ecffe0..e7383e3787d 100644 --- a/api/src/com/cloud/api/response/StaticRouteResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StaticRouteResponse.java @@ -14,99 +14,108 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.StaticRoute; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StaticRoute.class) @SuppressWarnings("unused") public class StaticRouteResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of static route") - private IdentityProxy id = new IdentityProxy("static_routes"); - + private String id; + @SerializedName(ApiConstants.STATE) @Param(description="the state of the static route") private String state; @SerializedName(ApiConstants.VPC_ID) @Param(description="VPC the static route belongs to") - private IdentityProxy vpcId = new IdentityProxy("vpc"); - + private String vpcId; + @SerializedName(ApiConstants.GATEWAY_ID) @Param(description="VPC gateway the route is created for") - private IdentityProxy gatewayId = new IdentityProxy("vpc_gateways"); - + private String gatewayId; + @SerializedName(ApiConstants.CIDR) @Param(description="static route CIDR") private String cidr; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the static route") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the static route") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the static route") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the static route") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the static route") private String domainName; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with static route", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + + @Override + public String getObjectId() { + return this.id; + } + + public void setId(String id) { + this.id = id; } public void setState(String state) { this.state = state; } - public void setVpcId(Long vpcId) { - this.vpcId.setValue(vpcId); + public void setVpcId(String vpcId) { + this.vpcId = vpcId; } - public void setGatewayId(Long gatewayId) { - this.gatewayId.setValue(gatewayId); + public void setGatewayId(String gatewayId) { + this.gatewayId = gatewayId; } public void setCidr(String cidr) { this.cidr = cidr; } - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/StatusResponse.java b/api/src/org/apache/cloudstack/api/response/StatusResponse.java similarity index 92% rename from api/src/com/cloud/api/response/StatusResponse.java rename to api/src/org/apache/cloudstack/api/response/StatusResponse.java index 336cad7b76a..ffe7c7c0c1e 100644 --- a/api/src/com/cloud/api/response/StatusResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StatusResponse.java @@ -14,14 +14,15 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class StatusResponse extends BaseResponse { @SerializedName("status") private Boolean status; - + public Boolean getStatus() { return status; } diff --git a/api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java b/api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java old mode 100755 new mode 100644 similarity index 86% rename from api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java rename to api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java index 68a939778cf..328180f5260 --- a/api/src/com/cloud/api/response/StorageNetworkIpRangeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StorageNetworkIpRangeResponse.java @@ -14,20 +14,23 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.dc.StorageNetworkIpRange; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StorageNetworkIpRange.class) public class StorageNetworkIpRangeResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the uuid of storage network IP range.") private String uuid; - + @SerializedName(ApiConstants.VLAN) @Param(description="the ID or VID of the VLAN.") private Integer vlan; - + @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod uuid for the storage network IP range") private String podUuid; @@ -36,35 +39,35 @@ public class StorageNetworkIpRangeResponse extends BaseResponse { @SerializedName(ApiConstants.END_IP) @Param(description="the end ip of the storage network IP range") private String endIp; - + @SerializedName(ApiConstants.GATEWAY) @Param(description="the gateway of the storage network IP range") private String gateway; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the network uuid of storage network IP range") private String networkUuid; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone uuid of the storage network IP range") private String zoneUuid; - + @SerializedName(ApiConstants.NETMASK) @Param(description="the netmask of the storage network IP range") private String netmask; - - public void setUuid(String uuid) { - this.uuid = uuid; - } - + + public void setUuid(String uuid) { + this.uuid = uuid; + } + public void setZoneUuid(String zoneUuid) { this.zoneUuid = zoneUuid; } - + public void setVlan(Integer vlan) { this.vlan = vlan; } - + public void setPodUuid(String podUuid) { this.podUuid = podUuid; } - + public void setStartIp(String startIp) { this.startIp = startIp; } @@ -76,12 +79,12 @@ public class StorageNetworkIpRangeResponse extends BaseResponse { public void setNetworkUuid(String networkUuid) { this.networkUuid = networkUuid; } - + public void setNetmask(String netmask) { - this.netmask = netmask; + this.netmask = netmask; } - + public void setGateway(String gateway) { - this.gateway = gateway; + this.gateway = gateway; } } diff --git a/api/src/com/cloud/api/response/StoragePoolResponse.java b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java old mode 100755 new mode 100644 similarity index 80% rename from api/src/com/cloud/api/response/StoragePoolResponse.java rename to api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java index 3b6a5792127..7afce716fda --- a/api/src/com/cloud/api/response/StoragePoolResponse.java +++ b/api/src/org/apache/cloudstack/api/response/StoragePoolResponse.java @@ -14,28 +14,31 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.storage.StoragePool; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.StoragePoolStatus; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=StoragePool.class) public class StoragePoolResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the storage pool") - private IdentityProxy id = new IdentityProxy("storage_pool"); + private String id; @SerializedName("zoneid") @Param(description="the Zone ID of the storage pool") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name of the storage pool") private String zoneName; @SerializedName("podid") @Param(description="the Pod ID of the storage pool") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name of the storage pool") private String podName; @@ -56,7 +59,7 @@ public class StoragePoolResponse extends BaseResponse { private String type; @SerializedName("clusterid") @Param(description="the ID of the cluster for the storage pool") - private IdentityProxy clusterId = new IdentityProxy("cluster"); + private String clusterId; @SerializedName("clustername") @Param(description="the name of the cluster for the storage pool") private String clusterName; @@ -66,7 +69,7 @@ public class StoragePoolResponse extends BaseResponse { @SerializedName("disksizeallocated") @Param(description="the host's currently allocated disk size") private Long diskSizeAllocated; - + @SerializedName("disksizeused") @Param(description="the host's currently used disk size") private Long diskSizeUsed; @@ -76,25 +79,27 @@ public class StoragePoolResponse extends BaseResponse { @SerializedName(ApiConstants.STATE) @Param(description="the state of the storage pool") private StoragePoolStatus state; + + @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -105,12 +110,12 @@ public class StoragePoolResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public String getPodName() { @@ -161,12 +166,12 @@ public class StoragePoolResponse extends BaseResponse { this.type = type; } - public Long getClusterId() { - return clusterId.getValue(); + public String getClusterId() { + return clusterId; } - public void setClusterId(Long clusterId) { - this.clusterId.setValue(clusterId); + public void setClusterId(String clusterId) { + this.clusterId = clusterId; } public String getClusterName() { @@ -194,14 +199,14 @@ public class StoragePoolResponse extends BaseResponse { } public Long getDiskSizeUsed() { - return diskSizeUsed; - } + return diskSizeUsed; + } - public void setDiskSizeUsed(Long diskSizeUsed) { - this.diskSizeUsed = diskSizeUsed; - } + public void setDiskSizeUsed(Long diskSizeUsed) { + this.diskSizeUsed = diskSizeUsed; + } - public String getTags() { + public String getTags() { return tags; } @@ -216,5 +221,5 @@ public class StoragePoolResponse extends BaseResponse { public void setState(StoragePoolStatus state) { this.state = state; } - + } diff --git a/api/src/com/cloud/api/response/SuccessResponse.java b/api/src/org/apache/cloudstack/api/response/SuccessResponse.java similarity index 71% rename from api/src/com/cloud/api/response/SuccessResponse.java rename to api/src/org/apache/cloudstack/api/response/SuccessResponse.java index b390e0bd79d..47c65b6a068 100644 --- a/api/src/com/cloud/api/response/SuccessResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SuccessResponse.java @@ -14,37 +14,38 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SuccessResponse extends BaseResponse { - @SerializedName("success") @Param(description="true if operation is executed successfully") - private Boolean success = true; - + @SerializedName("success") @Param(description="true if operation is executed successfully") + private Boolean success = true; + @SerializedName("displaytext") @Param(description="any text associated with the success or failure") private String displayText; - - public Boolean getSuccess() { - return success; - } - public void setSuccess(Boolean success) { - this.success = success; - } + public Boolean getSuccess() { + return success; + } - public String getDisplayText() { - return displayText; - } + public void setSuccess(Boolean success) { + this.success = success; + } + + public String getDisplayText() { + return displayText; + } public void setDisplayText(String displayText) { this.displayText = displayText; } - + public SuccessResponse() {} - + public SuccessResponse(String responseName) { - super.setResponseName(responseName); + super.setResponseName(responseName); } } diff --git a/api/src/com/cloud/api/response/SwiftResponse.java b/api/src/org/apache/cloudstack/api/response/SwiftResponse.java old mode 100755 new mode 100644 similarity index 87% rename from api/src/com/cloud/api/response/SwiftResponse.java rename to api/src/org/apache/cloudstack/api/response/SwiftResponse.java index 81171defdf0..83fceb348f7 --- a/api/src/com/cloud/api/response/SwiftResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SwiftResponse.java @@ -14,19 +14,19 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class SwiftResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description = "the ID of swift") - private IdentityProxy id = new IdentityProxy("swift"); + private String id; @SerializedName(ApiConstants.URL) @Param(description = "url for swift") @@ -45,13 +45,9 @@ public class SwiftResponse extends BaseResponse { private String username; - @Override - public Long getObjectId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public String getUrl() { diff --git a/api/src/com/cloud/api/response/SystemVmInstanceResponse.java b/api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java similarity index 80% rename from api/src/com/cloud/api/response/SystemVmInstanceResponse.java rename to api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java index cae526efe57..48df8549ab3 100644 --- a/api/src/com/cloud/api/response/SystemVmInstanceResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SystemVmInstanceResponse.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.utils.IdentityProxy; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; /* * This is the generic response for all types of System VMs (SSVM, consoleproxy, domain routers(router, LB, DHCP)) */ public class SystemVmInstanceResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the system VM") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName("systemvmtype") @Param(description="the system VM type") private String systemVmType; @@ -34,25 +34,22 @@ public class SystemVmInstanceResponse extends BaseResponse { private String name; @SerializedName("hostid") @Param(description="the host ID for the system VM") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("state") @Param(description="the state of the system VM") private String state; - + @SerializedName("role") @Param(description="the role of the system VM") private String role; - - - public Long getObjectId() { - return getId(); + + + + public String getId() { + return id; } - public Long getId() { - return id.getValue(); - } - - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getSystemVmType() { @@ -71,12 +68,12 @@ public class SystemVmInstanceResponse extends BaseResponse { this.name = name; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getState() { @@ -86,13 +83,13 @@ public class SystemVmInstanceResponse extends BaseResponse { public void setState(String state) { this.state = state; } - + public String getRole() { return role; } public void setRole(String role) { this.role = role; - } + } } diff --git a/api/src/com/cloud/api/response/SystemVmResponse.java b/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java similarity index 84% rename from api/src/com/cloud/api/response/SystemVmResponse.java rename to api/src/org/apache/cloudstack/api/response/SystemVmResponse.java index ea0025852cf..8b0f80b255a 100644 --- a/api/src/com/cloud/api/response/SystemVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/SystemVmResponse.java @@ -14,30 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.vm.VirtualMachine; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachine.class) public class SystemVmResponse extends BaseResponse { @SerializedName("id") @Param(description="the ID of the system VM") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName("systemvmtype") @Param(description="the system VM type") private String systemVmType; @SerializedName("jobid") @Param(description="the job ID associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.") - private IdentityProxy jobId = new IdentityProxy("async_job"); + private String jobId; @SerializedName("jobstatus") @Param(description="the job status associated with the system VM. This is only displayed if the router listed is part of a currently running asynchronous job.") private Integer jobStatus; @SerializedName("zoneid") @Param(description="the Zone ID for the system VM") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the Zone name for the system VM") private String zoneName; @@ -58,10 +61,10 @@ public class SystemVmResponse extends BaseResponse { private String name; @SerializedName("podid") @Param(description="the Pod ID for the system VM") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("hostid") @Param(description="the host ID for the system VM") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the hostname for the system VM") private String hostName; @@ -74,7 +77,7 @@ public class SystemVmResponse extends BaseResponse { @SerializedName(ApiConstants.PRIVATE_NETMASK) @Param(description="the private netmask for the system VM") private String privateNetmask; - + @SerializedName(ApiConstants.LINK_LOCAL_IP) @Param(description="the link local IP address for the system vm") private String linkLocalIp; @@ -94,33 +97,33 @@ public class SystemVmResponse extends BaseResponse { private String publicNetmask; @SerializedName("templateid") @Param(description="the template ID for the system VM") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("created") @Param(description="the date and time the system VM was created") private Date created; @SerializedName("state") @Param(description="the state of the system VM") private String state; - + @SerializedName("activeviewersessions") @Param(description="the number of active console sessions for the console proxy system vm") private Integer activeViewerSessions; - - private Long objectId; - - public Long getObjectId() { - return objectId; - } - - public void setObjectId(Long objectId) { - this.objectId = objectId; + + // private Long objectId; + + + + @Override + public String getObjectId() { + return this.getId(); } - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public String getSystemVmType() { @@ -131,12 +134,12 @@ public class SystemVmResponse extends BaseResponse { this.systemVmType = systemVmType; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getZoneName() { @@ -187,20 +190,20 @@ public class SystemVmResponse extends BaseResponse { this.name = name; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getHostName() { @@ -259,12 +262,12 @@ public class SystemVmResponse extends BaseResponse { this.publicNetmask = publicNetmask; } - public Long getTemplateId() { - return templateId.getValue(); + public String getTemplateId() { + return templateId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public Date getCreated() { diff --git a/api/src/com/cloud/api/response/TemplatePermissionsResponse.java b/api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java similarity index 80% rename from api/src/com/cloud/api/response/TemplatePermissionsResponse.java rename to api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java index 1f801462e2d..f1e08e3dcc6 100644 --- a/api/src/com/cloud/api/response/TemplatePermissionsResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TemplatePermissionsResponse.java @@ -14,43 +14,46 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachineTemplate.class) @SuppressWarnings("unused") public class TemplatePermissionsResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName(ApiConstants.IS_PUBLIC) @Param(description="true if this template is a public template, false otherwise") private Boolean publicTemplate; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain to which the template belongs") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the list of accounts the template is available for") private List accountNames; - + @SerializedName(ApiConstants.PROJECT_IDS) @Param(description="the list of projects the template is available for") private List projectIds; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setPublicTemplate(Boolean publicTemplate) { this.publicTemplate = publicTemplate; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setAccountNames(List accountNames) { diff --git a/api/src/com/cloud/api/response/TemplateResponse.java b/api/src/org/apache/cloudstack/api/response/TemplateResponse.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/response/TemplateResponse.java rename to api/src/org/apache/cloudstack/api/response/TemplateResponse.java index 5c3d3399799..f6f74dac5b7 --- a/api/src/com/cloud/api/response/TemplateResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TemplateResponse.java @@ -14,22 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; import java.util.Map; -import com.cloud.api.ApiConstants; +import com.cloud.template.VirtualMachineTemplate; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.cloud.storage.Storage.ImageFormat; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualMachineTemplate.class) @SuppressWarnings("unused") public class TemplateResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the template name") private String name; @@ -67,19 +70,19 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private boolean crossZones; @SerializedName(ApiConstants.OS_TYPE_ID) @Param(description="the ID of the OS type for this template.") - private IdentityProxy osTypeId = new IdentityProxy("guest_os"); + private String osTypeId; @SerializedName("ostypename") @Param(description="the name of the OS type for this template.") private String osTypeName; @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the account id to which the template belongs") - private IdentityProxy accountId = new IdentityProxy("account"); + private String accountId; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account name to which the template belongs") private String account; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the zone for this template") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone for this template") private String zoneName; @@ -97,10 +100,10 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private String hypervisor; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the domain to which the template belongs") - private String domainName; + private String domainName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain to which the template belongs") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.IS_EXTRACTABLE) @Param(description="true if the template is extractable, false otherwise") private Boolean extractable; @@ -109,65 +112,67 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe private String checksum; @SerializedName("sourcetemplateid") @Param(description="the template ID of the parent template if present") - private IdentityProxy sourcetemplateId = new IdentityProxy("vm_template"); + private String sourcetemplateId; @SerializedName(ApiConstants.HOST_ID) @Param(description="the ID of the secondary storage host for the template") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the secondary storage host for the template") private String hostName; @SerializedName(ApiConstants.TEMPLATE_TAG) @Param(description="the tag of this template") private String templateTag; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the template") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the template") private String projectName; - + @SerializedName(ApiConstants.DETAILS) @Param(description="additional key/value details tied with template") private Map details; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with tempate", responseObject = ResourceTagResponse.class) private List tags; - + + + @Override - public Long getObjectId() { - return getId(); - } - - public Long getId() { - return id.getValue(); + public String getObjectId() { + return this.getId(); } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public String getId() { + return id; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; } public void setAccountName(String account) { this.account = account; } - public void setOsTypeId(Long osTypeId) { - this.osTypeId.setValue(osTypeId); + public void setOsTypeId(String osTypeId) { + this.osTypeId = osTypeId; } public void setOsTypeName(String osTypeName) { this.osTypeName = osTypeName; } - public void setId(long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -229,15 +234,15 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe public void setHypervisor(String hypervisor) { this.hypervisor = hypervisor; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setExtractable(Boolean extractable) { @@ -248,12 +253,12 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe this.checksum = checksum; } - public void setSourceTemplateId(Long sourcetemplateId) { - this.sourcetemplateId.setValue(sourcetemplateId); - } + public void setSourceTemplateId(String sourcetemplateId) { + this.sourcetemplateId = sourcetemplateId; + } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { @@ -263,25 +268,25 @@ public class TemplateResponse extends BaseResponse implements ControlledEntityRe public void setTemplateTag(String templateTag) { this.templateTag = templateTag; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + public Map getDetails() { - return this.details; + return this.details; } - + public void setDetails(Map details) { - this.details = details; + this.details = details; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/server/src/com/cloud/server/api/response/TrafficMonitorResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java similarity index 77% rename from server/src/com/cloud/server/api/response/TrafficMonitorResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java index 9271c04bb5d..366e5d631b0 100644 --- a/server/src/com/cloud/server/api/response/TrafficMonitorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficMonitorResponse.java @@ -14,67 +14,66 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class TrafficMonitorResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the external firewall") - private IdentityProxy id = new IdentityProxy("host"); - + private String id; + @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; - + @SerializedName(ApiConstants.NUM_RETRIES) @Param(description="the number of times to retry requests to the external firewall") private String numRetries; - + @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - - public Long getId() { - return id.getValue(); + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } - - public Long getZoneId() { - return zoneId.getValue(); + + public String getZoneId() { + return zoneId; } - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public String getIpAddress() { return ipAddress; } - + public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } - + public String getNumRetries() { return numRetries; } - + public void setNumRetries(String numRetries) { this.numRetries = numRetries; } - + public String getTimeout() { return timeout; } - + public void setTimeout(String timeout) { this.timeout = timeout; } diff --git a/api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java old mode 100755 new mode 100644 similarity index 61% rename from api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java index 3a5d4f71aa3..30adc3d87ca --- a/api/src/com/cloud/api/response/TrafficTypeImplementorResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficTypeImplementorResponse.java @@ -14,24 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class TrafficTypeImplementorResponse extends BaseResponse { - @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="network traffic type") - private String trafficType; - - @SerializedName(ApiConstants.TRAFFIC_TYPE_IMPLEMENTOR) @Param(description="implementor of network traffic type") - private String implementor; - - public void setTrafficType(String type) { - this.trafficType = type; - } - - public void setImplementor(String impl) { - this.implementor = impl; - } + @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="network traffic type") + private String trafficType; + + @SerializedName(ApiConstants.TRAFFIC_TYPE_IMPLEMENTOR) @Param(description="implementor of network traffic type") + private String implementor; + + public void setTrafficType(String type) { + this.trafficType = type; + } + + public void setImplementor(String impl) { + this.implementor = impl; + } } diff --git a/api/src/com/cloud/api/response/TrafficTypeResponse.java b/api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java similarity index 81% rename from api/src/com/cloud/api/response/TrafficTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java index f64fbb1dd24..43760f2e1b4 100644 --- a/api/src/com/cloud/api/response/TrafficTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/TrafficTypeResponse.java @@ -14,13 +14,16 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.PhysicalNetworkTrafficType; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=PhysicalNetworkTrafficType.class) public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="id of the network provider") @@ -28,10 +31,10 @@ public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.TRAFFIC_TYPE) @Param(description="the trafficType to be added to the physical network") private String trafficType; - + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.XEN_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a XenServer host") private String xenNetworkLabel; @@ -41,30 +44,36 @@ public class TrafficTypeResponse extends BaseResponse { @SerializedName(ApiConstants.VMWARE_NETWORK_LABEL) @Param(description="The network name label of the physical device dedicated to this traffic on a VMware host") private String vmwareNetworkLabel; - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + @Override + public String getObjectId() { + return this.id; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - + + public String getphysicalNetworkId() { + return physicalNetworkId; + } + public void setId(String uuid) { this.id = uuid; } - + public String getId() { return this.id; } - + public String getTrafficType() { return trafficType; } - + public void setTrafficType(String trafficType) { this.trafficType = trafficType; } - + public String getXenLabel() { return xenNetworkLabel; } @@ -72,7 +81,7 @@ public class TrafficTypeResponse extends BaseResponse { public String getKvmLabel() { return kvmNetworkLabel; } - + public void setXenLabel(String xenLabel) { this.xenNetworkLabel = xenLabel; } @@ -83,8 +92,8 @@ public class TrafficTypeResponse extends BaseResponse { public void setVmwareLabel(String vmwareNetworkLabel) { this.vmwareNetworkLabel = vmwareNetworkLabel; - } - + } + public String getVmwareLabel() { return vmwareNetworkLabel; } diff --git a/api/src/com/cloud/api/response/UpgradeVmResponse.java b/api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java similarity index 83% rename from api/src/com/cloud/api/response/UpgradeVmResponse.java rename to api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java index e48ec08fe7c..767f783da44 100644 --- a/api/src/com/cloud/api/response/UpgradeVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UpgradeVmResponse.java @@ -14,18 +14,18 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class UpgradeVmResponse extends BaseResponse { - @SerializedName("id") - private IdentityProxy id = new IdentityProxy("vm_instance"); + @SerializedName("id") + private String id; public String getName() { return name; @@ -67,12 +67,12 @@ public class UpgradeVmResponse extends BaseResponse { this.account = account; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomain() { @@ -91,12 +91,12 @@ public class UpgradeVmResponse extends BaseResponse { this.haEnable = haEnable; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public String getDisplayName() { @@ -115,12 +115,12 @@ public class UpgradeVmResponse extends BaseResponse { this.zoneName = zoneName; } - public Long getHostId() { - return hostId.getValue(); + public String getHostId() { + return hostId; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public String getHostName() { @@ -131,12 +131,12 @@ public class UpgradeVmResponse extends BaseResponse { this.hostName = hostName; } - public Long getTemplateId() { - return templateId.getValue(); + public String getTemplateId() { + return templateId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public String getTemplateName() { @@ -163,12 +163,12 @@ public class UpgradeVmResponse extends BaseResponse { this.passwordEnabled = passwordEnabled; } - public Long getServiceOfferingId() { - return serviceOfferingId.getValue(); + public String getServiceOfferingId() { + return serviceOfferingId; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public String getServiceOfferingName() { @@ -219,8 +219,8 @@ public class UpgradeVmResponse extends BaseResponse { this.networkKbsWrite = networkKbsWrite; } - public Long isId() { - return id.getValue(); + public String isId() { + return id; } @SerializedName("name") @Param(description="the ID of the virtual machine") @@ -239,7 +239,7 @@ public class UpgradeVmResponse extends BaseResponse { private String account; @SerializedName("domainid") @Param(description="the ID of the domain in which the virtual machine exists") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description="the name of the domain in which the virtual machine exists") private String domain; @@ -248,7 +248,7 @@ public class UpgradeVmResponse extends BaseResponse { private boolean haEnable; @SerializedName("zoneid") @Param(description="the ID of the availablility zone for the virtual machine") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName("displayname") @Param(description="user generated name. The name of the virtual machine is returned if no displayname exists.") private String displayName; @@ -257,25 +257,25 @@ public class UpgradeVmResponse extends BaseResponse { private String zoneName; @SerializedName("hostid") @Param(description="the ID of the host for the virtual machine") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the host for the virtual machine") private String hostName; @SerializedName("templateid") @Param(description="the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file.") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("templatename") @Param(description="the name of the template for the virtual machine") private String templateName; - @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") + @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") private String templateDisplayText; @SerializedName("passwordenabled") @Param(description="true if the password rest feature is enabled, false otherwise") private boolean passwordEnabled; @SerializedName("serviceofferingid") @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; diff --git a/server/src/com/cloud/server/api/response/UsageRecordResponse.java b/api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java similarity index 80% rename from server/src/com/cloud/server/api/response/UsageRecordResponse.java rename to api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java index e80e262b716..9679575c046 100644 --- a/server/src/com/cloud/server/api/response/UsageRecordResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UsageRecordResponse.java @@ -14,12 +14,11 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; -import com.cloud.api.response.ControlledEntityResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.response.ControlledEntityResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @@ -27,24 +26,24 @@ import com.google.gson.annotations.SerializedName; public class UsageRecordResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ACCOUNT) @Param(description="the user account name") private String accountName; - + @SerializedName(ApiConstants.ACCOUNT_ID) @Param(description="the user account Id") - private IdentityProxy accountId = new IdentityProxy("account"); - + private String accountId; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the resource") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the resource") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain the resource is associated with") private String domainName; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.DESCRIPTION) @Param(description="description of the usage record") private String description; @@ -59,7 +58,7 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit private String rawUsage; @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description="virtual machine ID") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName(ApiConstants.NAME) @Param(description="virtual machine name") private String vmName; @@ -68,11 +67,11 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit private String offeringId; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="template ID") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("usageid") @Param(description="id of the resource") private String usageId; - + @SerializedName(ApiConstants.TYPE) @Param(description="resource type") private String type; @@ -90,29 +89,29 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.IS_SYSTEM) @Param(description="True if the IPAddress is system IP - allocated during vm deploy or lb rule create") private Boolean isSystem; - + @SerializedName("networkid") @Param(description="id of the network") private String networkId; - + @SerializedName("isdefault") @Param(description="True if the resource is default") private Boolean isDefault; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); - } - - @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setAccountId(String accountId) { + this.accountId = accountId; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setDescription(String description) { @@ -131,8 +130,8 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit this.rawUsage = rawUsage; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVmName(String vmName) { @@ -143,8 +142,8 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit this.offeringId = offeringId; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setUsageId(String usageId) { @@ -174,17 +173,17 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit public void setSystem(Boolean isSystem) { this.isSystem = isSystem; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - + @Override public void setDomainName(String domainName) { this.domainName = domainName; @@ -193,7 +192,7 @@ public class UsageRecordResponse extends BaseResponse implements ControlledEntit public void setNetworkId(String networkId) { this.networkId = networkId; } - + public void setDefault(Boolean isDefault) { this.isDefault = isDefault; } diff --git a/server/src/com/cloud/server/api/response/UsageTypeResponse.java b/api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java similarity index 92% rename from server/src/com/cloud/server/api/response/UsageTypeResponse.java rename to api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java index cb927e1c106..b21d26f3774 100644 --- a/server/src/com/cloud/server/api/response/UsageTypeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UsageTypeResponse.java @@ -14,10 +14,10 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.server.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/api/src/com/cloud/api/response/UserResponse.java b/api/src/org/apache/cloudstack/api/response/UserResponse.java similarity index 78% rename from api/src/com/cloud/api/response/UserResponse.java rename to api/src/org/apache/cloudstack/api/response/UserResponse.java index 920eb598f5a..9ab6248ed2e 100644 --- a/api/src/com/cloud/api/response/UserResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UserResponse.java @@ -14,18 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import com.cloud.serializer.Param; +import com.cloud.user.User; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; + +@EntityReference(value = User.class) public class UserResponse extends BaseResponse { @SerializedName("id") @Param(description="the user ID") - private IdentityProxy id = new IdentityProxy("user"); + private String id; @SerializedName("username") @Param(description="the user name") private String username; @@ -52,7 +55,7 @@ public class UserResponse extends BaseResponse { private Short accountType; @SerializedName("domainid") @Param(description="the domain ID of the user") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName("domain") @Param(description="the domain name of the user") private String domainName; @@ -67,15 +70,22 @@ public class UserResponse extends BaseResponse { private String secretKey; @SerializedName("accountid") @Param(description="the account ID of the user") - private IdentityProxy accountId = new IdentityProxy("account"); + private String accountId; - - public Long getId() { - return id.getValue(); + @SerializedName("iscallerchilddomain") @Param(description="the boolean value representing if the updating target is in caller's child domain") + private boolean isCallerChildDomain; + + @Override + public String getObjectId() { + return this.getId(); } - public void setId(Long id) { - this.id.setValue(id); + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; } public String getUsername() { @@ -142,12 +152,12 @@ public class UserResponse extends BaseResponse { this.accountType = accountType; } - public Long getDomainId() { - return domainId.getValue(); + public String getDomainId() { + return domainId; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public String getDomainName() { @@ -181,11 +191,19 @@ public class UserResponse extends BaseResponse { public void setSecretKey(String secretKey) { this.secretKey = secretKey; } - public Long getAccountId() { - return accountId.getValue(); + public String getAccountId() { + return accountId; } - public void setAccountId(Long accountId) { - this.accountId.setValue(accountId); + public void setAccountId(String accountId) { + this.accountId = accountId; + } + + public boolean getIsCallerSubdomain() { + return this.isCallerChildDomain; + } + + public void setIsCallerChildDomain(boolean isCallerChildDomain) { + this.isCallerChildDomain = isCallerChildDomain; } } diff --git a/api/src/com/cloud/api/response/UserVmResponse.java b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java old mode 100755 new mode 100644 similarity index 78% rename from api/src/com/cloud/api/response/UserVmResponse.java rename to api/src/org/apache/cloudstack/api/response/UserVmResponse.java index f74c07254c7..5450bfb6452 --- a/api/src/com/cloud/api/response/UserVmResponse.java +++ b/api/src/org/apache/cloudstack/api/response/UserVmResponse.java @@ -14,20 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import com.cloud.network.router.VirtualRouter; +import com.cloud.uservm.UserVm; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.vm.VirtualMachine; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value={VirtualMachine.class, UserVm.class, VirtualRouter.class}) public class UserVmResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the virtual machine") - private IdentityProxy id = new IdentityProxy("vm_instance"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the virtual machine") private String name; @@ -37,15 +43,15 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the virtual machine") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vm") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vm") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the domain in which the virtual machine exists") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the name of the domain in which the virtual machine exists") private String domainName; @@ -60,37 +66,37 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private Boolean haEnable; @SerializedName(ApiConstants.GROUP_ID) @Param(description="the group ID of the virtual machine") - private IdentityProxy groupId = new IdentityProxy("instance_group"); + private String groupId; @SerializedName(ApiConstants.GROUP) @Param(description="the group name of the virtual machine") private String group; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the ID of the availablility zone for the virtual machine") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the availability zone for the virtual machine") private String zoneName; @SerializedName(ApiConstants.HOST_ID) @Param(description="the ID of the host for the virtual machine") - private IdentityProxy hostId = new IdentityProxy("host"); + private String hostId; @SerializedName("hostname") @Param(description="the name of the host for the virtual machine") private String hostName; @SerializedName(ApiConstants.TEMPLATE_ID) @Param(description="the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file.") - private IdentityProxy templateId = new IdentityProxy("vm_template"); + private String templateId; @SerializedName("templatename") @Param(description="the name of the template for the virtual machine") private String templateName; - @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") + @SerializedName("templatedisplaytext") @Param(description=" an alternate display text of the template for the virtual machine") private String templateDisplayText; @SerializedName(ApiConstants.PASSWORD_ENABLED) @Param(description="true if the password rest feature is enabled, false otherwise") private Boolean passwordEnabled; @SerializedName("isoid") @Param(description="the ID of the ISO attached to the virtual machine") - private IdentityProxy isoId = new IdentityProxy("vm_template"); + private String isoId; @SerializedName("isoname") @Param(description="the name of the ISO attached to the virtual machine") private String isoName; @@ -99,11 +105,11 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private String isoDisplayText; @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description="the ID of the service offering of the virtual machine") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description="the name of the service offering of the virtual machine") private String serviceOfferingName; - + @SerializedName("forvirtualnetwork") @Param(description="the virtual network for the service offering") private Boolean forVirtualNetwork; @@ -118,7 +124,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp @SerializedName("cpuused") @Param(description="the amount of the vm's CPU currently used") private String cpuUsed; - + @SerializedName("networkkbsread") @Param(description="the incoming network traffic on the vm") private Long networkKbsRead; @@ -126,7 +132,7 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private Long networkKbsWrite; @SerializedName("guestosid") @Param(description="Os type ID of the virtual machine") - private IdentityProxy guestOsId = new IdentityProxy("guest_os"); + private String guestOsId; @SerializedName("rootdeviceid") @Param(description="device ID of the root volume") private Long rootDeviceId; @@ -135,42 +141,55 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp private String rootDeviceType; @SerializedName("securitygroup") @Param(description="list of security groups associated with the virtual machine", responseObject = SecurityGroupResponse.class) - private List securityGroupList; + private Set securityGroupList; @SerializedName(ApiConstants.PASSWORD) @Param(description="the password (if exists) of the virtual machine") private String password; @SerializedName("nic") @Param(description="the list of nics associated with vm", responseObject = NicResponse.class) - private List nics; - + private Set nics; + @SerializedName("hypervisor") @Param(description="the hypervisor on which the template runs") private String hypervisor; - + @SerializedName(ApiConstants.PUBLIC_IP_ID) @Param(description="public IP address id associated with vm via Static nat rule") - private IdentityProxy publicIpId = new IdentityProxy("user_ip_address"); - + private String publicIpId; + @SerializedName(ApiConstants.PUBLIC_IP) @Param(description="public IP address id associated with vm via Static nat rule") private String publicIp; - + @SerializedName(ApiConstants.INSTANCE_NAME) @Param(description="instance name of the user vm; this parameter is returned to the ROOT admin only", since="3.0.1") private String instanceName; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with vm", responseObject = ResourceTagResponse.class) - private List tags; + private Set tags; @SerializedName(ApiConstants.SSH_KEYPAIR) @Param(description="ssh key-pair") private String keyPairName; - public void setHypervisor(String hypervisor) { - this.hypervisor = hypervisor; - } - - public void setId(Long id) { - this.id.setValue(id); + public UserVmResponse(){ + securityGroupList = new HashSet(); + nics = new HashSet(); + tags = new HashSet(); } - public Long getId() { - return this.id.getValue(); + public void setHypervisor(String hypervisor) { + this.hypervisor = hypervisor; + } + + public void setId(String id) { + this.id = id; + } + + public String getId() { + return this.id; + } + + + + @Override + public String getObjectId() { + return this.getId(); } public void setName(String name) { @@ -185,8 +204,9 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { @@ -205,32 +225,32 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.haEnable = haEnable; } - public void setGroupId(Long groupId) { - this.groupId.setValue(groupId); + public void setGroupId(String groupId) { + this.groupId = groupId; } public void setGroup(String group) { this.group = group; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setZoneName(String zoneName) { this.zoneName = zoneName; } - public void setHostId(Long hostId) { - this.hostId.setValue(hostId); + public void setHostId(String hostId) { + this.hostId = hostId; } public void setHostName(String hostName) { this.hostName = hostName; } - public void setTemplateId(Long templateId) { - this.templateId.setValue(templateId); + public void setTemplateId(String templateId) { + this.templateId = templateId; } public void setTemplateName(String templateName) { @@ -245,8 +265,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.passwordEnabled = passwordEnabled; } - public void setIsoId(Long isoId) { - this.isoId.setValue(isoId); + public void setIsoId(String isoId) { + this.isoId = isoId; } public void setIsoName(String isoName) { @@ -257,8 +277,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.isoDisplayText = isoDisplayText; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -289,8 +309,8 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.networkKbsWrite = networkKbsWrite; } - public void setGuestOsId(Long guestOsId) { - this.guestOsId.setValue(guestOsId); + public void setGuestOsId(String guestOsId) { + this.guestOsId = guestOsId; } public void setRootDeviceId(Long rootDeviceId) { @@ -305,39 +325,38 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.password = password; } -/* - public void setJobId(Long jobId) { - super.setJobId(jobId); - } - - public void setJobStatus(Integer jobStatus) { - this.jobStatus = jobStatus; - } -*/ public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - public void setNics(List nics) { + public void setNics(Set nics) { this.nics = nics; } - public void setSecurityGroupList(List securityGroups) { + public void addNic(NicResponse nic) { + this.nics.add(nic); + } + + public void setSecurityGroupList(Set securityGroups) { this.securityGroupList = securityGroups; } - - @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + + public void addSecurityGroup(SecurityGroupResponse securityGroup){ + this.securityGroupList.add(securityGroup); } - + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; + } + @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPublicIpId(Long publicIpId) { - this.publicIpId.setValue(publicIpId); + + public void setPublicIpId(String publicIpId) { + this.publicIpId = publicIpId; } public void setPublicIp(String publicIp) { @@ -348,11 +367,16 @@ public class UserVmResponse extends BaseResponse implements ControlledEntityResp this.instanceName = instanceName; } - public void setTags(List tags) { + public void setTags(Set tags) { this.tags = tags; } + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } + public void setKeyPairName(String keyPairName) { this.keyPairName = keyPairName; } + } diff --git a/api/src/com/cloud/api/response/VirtualRouterProviderResponse.java b/api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java similarity index 79% rename from api/src/com/cloud/api/response/VirtualRouterProviderResponse.java rename to api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java index 3e3e33dee16..dcb2322e5b9 100644 --- a/api/src/com/cloud/api/response/VirtualRouterProviderResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VirtualRouterProviderResponse.java @@ -14,49 +14,52 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.VirtualRouterProvider; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VirtualRouterProvider.class) public class VirtualRouterProviderResponse extends BaseResponse implements ControlledEntityResponse { @SerializedName(ApiConstants.ID) @Param(description="the id of the router") - private IdentityProxy id = new IdentityProxy("virtual_router_providers"); - + private String id; + @SerializedName(ApiConstants.NSP_ID) @Param(description="the physical network service provider id of the provider") - private IdentityProxy nspId = new IdentityProxy("physical_network_service_providers"); - + private String nspId; + @SerializedName(ApiConstants.ENABLED) @Param(description="Enabled/Disabled the service provider") private Boolean enabled; @SerializedName(ApiConstants.ACCOUNT) @Param(description="the account associated with the provider") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the ipaddress") - private Long projectId; - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the address") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID associated with the provider") - private Long domainId; + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain associated with the provider") private String domainName; - + @Override public void setAccountName(String accountName) { this.accountName = accountName; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } @Override - public void setDomainId(Long domainId) { + public void setDomainId(String domainId) { this.domainId = domainId; } @@ -66,7 +69,7 @@ public class VirtualRouterProviderResponse extends BaseResponse implements Contr } @Override - public void setProjectId(Long projectId) { + public void setProjectId(String projectId) { this.projectId = projectId; } @@ -75,8 +78,8 @@ public class VirtualRouterProviderResponse extends BaseResponse implements Contr this.projectName = projectName; } - public void setNspId(Long nspId) { - this.nspId.setValue(nspId); + public void setNspId(String nspId) { + this.nspId = nspId; } public void setEnabled(Boolean enabled) { diff --git a/api/src/com/cloud/api/response/VlanIpRangeResponse.java b/api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java similarity index 75% rename from api/src/com/cloud/api/response/VlanIpRangeResponse.java rename to api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java index 63358161eaf..bfde73963c1 100644 --- a/api/src/com/cloud/api/response/VlanIpRangeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VlanIpRangeResponse.java @@ -14,23 +14,26 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.dc.Vlan; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Vlan.class) @SuppressWarnings("unused") public class VlanIpRangeResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the ID of the VLAN IP range") - private IdentityProxy id = new IdentityProxy("vlan"); + private String id; @SerializedName("forvirtualnetwork") @Param(description="the virtual network for the VLAN IP range") private Boolean forVirtualNetwork; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the Zone ID of the VLAN IP range") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.VLAN) @Param(description="the ID or VID of the VLAN.") private String vlan; @@ -39,13 +42,13 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain ID of the VLAN IP range") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the VLAN IP range") private String domainName; @SerializedName(ApiConstants.POD_ID) @Param(description="the Pod ID for the VLAN IP range") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); + private String podId; @SerializedName("podname") @Param(description="the Pod name for the VLAN IP range") private String podName; @@ -64,49 +67,49 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit @SerializedName(ApiConstants.END_IP) @Param(description="the end ip of the VLAN IP range") private String endIp; - + @SerializedName(ApiConstants.NETWORK_ID) @Param(description="the network id of vlan range") - private IdentityProxy networkId = new IdentityProxy("networks"); - + private String networkId; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vlan range") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vlan range") private String projectName; - - @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - public void setId(Long id) { - this.id.setValue(id); + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network this belongs to") + private String physicalNetworkId; + + public void setId(String id) { + this.id = id; } public void setForVirtualNetwork(Boolean forVirtualNetwork) { this.forVirtualNetwork = forVirtualNetwork; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public void setVlan(String vlan) { this.vlan = vlan; } - + public void setAccountName(String accountName) { this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } public void setDomainName(String domainName) { this.domainName = domainName; } - public void setPodId(Long podId) { - this.podId.setValue(podId); + public void setPodId(String podId) { + this.podId = podId; } public void setPodName(String podName) { @@ -133,25 +136,25 @@ public class VlanIpRangeResponse extends BaseResponse implements ControlledEntit this.endIp = endIp; } - public void setNetworkId(Long networkId) { - this.networkId.setValue(networkId); + public void setNetworkId(String networkId) { + this.networkId = networkId; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } - public long getphysicalNetworkId() { - return physicalNetworkId.getValue(); - } + public String getphysicalNetworkId() { + return physicalNetworkId; + } } diff --git a/api/src/com/cloud/api/response/VolumeResponse.java b/api/src/org/apache/cloudstack/api/response/VolumeResponse.java old mode 100755 new mode 100644 similarity index 81% rename from api/src/com/cloud/api/response/VolumeResponse.java rename to api/src/org/apache/cloudstack/api/response/VolumeResponse.java index b5633908a81..d92153d0dbe --- a/api/src/com/cloud/api/response/VolumeResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VolumeResponse.java @@ -14,21 +14,25 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; -import java.util.List; +import java.util.HashSet; +import java.util.Set; -import com.cloud.api.ApiConstants; +import com.cloud.storage.Volume; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Volume.class) @SuppressWarnings("unused") -public class VolumeResponse extends BaseResponse implements ControlledEntityResponse{ +public class VolumeResponse extends BaseResponse implements ControlledViewEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description = "ID of the disk volume") - private IdentityProxy id = new IdentityProxy("volumes"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description = "name of the disk volume") @@ -36,7 +40,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ZONE_ID) @Param(description = "ID of the availability zone") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.ZONE_NAME) @Param(description = "name of the availability zone") @@ -52,7 +56,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.VIRTUAL_MACHINE_ID) @Param(description = "id of the virtual machine") - private IdentityProxy virtualMachineId = new IdentityProxy("vm_instance"); + private String virtualMachineId; @SerializedName("vmname") @Param(description = "name of the virtual machine") @@ -81,16 +85,16 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.ACCOUNT) @Param(description = "the account associated with the disk volume") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description = "the ID of the domain associated with the disk volume") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description = "the domain associated with the disk volume") @@ -106,7 +110,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.DISK_OFFERING_ID) @Param(description = "ID of the disk offering") - private IdentityProxy diskOfferingId = new IdentityProxy("disk_offering"); + private String diskOfferingId; @SerializedName("diskofferingname") @Param(description = "name of the disk offering") @@ -122,7 +126,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.SNAPSHOT_ID) @Param(description = "ID of the snapshot from which this volume was created") - private IdentityProxy snapshotId = new IdentityProxy("snapshots"); + private String snapshotId; @SerializedName("attached") @Param(description = "the date the volume was attached to a VM instance") @@ -134,7 +138,7 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName(ApiConstants.SERVICE_OFFERING_ID) @Param(description = "ID of the service offering for root disk") - private IdentityProxy serviceOfferingId = new IdentityProxy("disk_offering"); + private String serviceOfferingId; @SerializedName("serviceofferingname") @Param(description = "name of the service offering for root disk") @@ -147,17 +151,21 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp @SerializedName("isextractable") @Param(description = "true if the volume is extractable, false otherwise") private Boolean extractable; - + @SerializedName(ApiConstants.STATUS) @Param(description="the status of the volume") private String status; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with volume", responseObject = ResourceTagResponse.class) - private List tags; + private Set tags; + + public VolumeResponse(){ + tags = new HashSet(); + } @Override - public Long getObjectId() { - return getId(); + public String getObjectId() { + return this.getId(); } public Boolean getDestroyed() { @@ -168,22 +176,22 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.destroyed = destroyed; } - public Long getId() { - return id.getValue(); + public String getId() { + return id; } - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { this.name = name; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - + public void setZoneName(String zoneName) { this.zoneName = zoneName; } @@ -196,8 +204,8 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.deviceId = deviceId; } - public void setVirtualMachineId(Long virtualMachineId) { - this.virtualMachineId.setValue(virtualMachineId); + public void setVirtualMachineId(String virtualMachineId) { + this.virtualMachineId = virtualMachineId; } public void setVirtualMachineName(String virtualMachineName) { @@ -224,10 +232,11 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.accountName = accountName; } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + @Override + public void setDomainId(String domainId) { + this.domainId = domainId; } - + public void setDomainName(String domainName) { this.domainName = domainName; } @@ -240,8 +249,8 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.hypervisor = hypervisor; } - public void setDiskOfferingId(Long diskOfferingId) { - this.diskOfferingId.setValue(diskOfferingId); + public void setDiskOfferingId(String diskOfferingId) { + this.diskOfferingId = diskOfferingId; } public void setDiskOfferingName(String diskOfferingName) { @@ -256,16 +265,16 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp this.storagePoolName = storagePoolName; } - public void setSnapshotId(Long snapshotId) { - this.snapshotId.setValue(snapshotId); + public void setSnapshotId(String snapshotId) { + this.snapshotId = snapshotId; } public void setAttached(Date attached) { this.attached = attached; } - public void setServiceOfferingId(Long serviceOfferingId) { - this.serviceOfferingId.setValue(serviceOfferingId); + public void setServiceOfferingId(String serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; } public void setServiceOfferingName(String serviceOfferingName) { @@ -273,10 +282,10 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp } public void setStatus(String status) { - this.status = status; - } + this.status = status; + } - public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { + public void setServiceOfferingDisplayText(String serviceOfferingDisplayText) { this.serviceOfferingDisplayText = serviceOfferingDisplayText; } @@ -287,18 +296,22 @@ public class VolumeResponse extends BaseResponse implements ControlledEntityResp public void setState(String state) { this.state = state; } - + @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; } - - public void setTags(List tags) { + + public void setTags(Set tags) { this.tags = tags; } + + public void addTag(ResourceTagResponse tag){ + this.tags.add(tag); + } } diff --git a/api/src/com/cloud/api/response/VpcOfferingResponse.java b/api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java similarity index 85% rename from api/src/com/cloud/api/response/VpcOfferingResponse.java rename to api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java index 51c5fc2c9ba..3e196febe24 100644 --- a/api/src/com/cloud/api/response/VpcOfferingResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpcOfferingResponse.java @@ -14,42 +14,45 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.VpcOffering; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=VpcOffering.class) @SuppressWarnings("unused") -public class VpcOfferingResponse extends BaseResponse{ +public class VpcOfferingResponse extends BaseResponse { @SerializedName("id") @Param(description="the id of the vpc offering") - private final IdentityProxy id = new IdentityProxy("vpc_offerings"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the vpc offering") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the vpc offering.") private String displayText; - + @SerializedName(ApiConstants.CREATED) @Param(description="the date this vpc offering was created") private Date created; - + @SerializedName(ApiConstants.IS_DEFAULT) @Param(description="true if vpc offering is default, false otherwise") private Boolean isDefault; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the vpc offering. Can be Disabled/Enabled") private String state; - + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -71,7 +74,7 @@ public class VpcOfferingResponse extends BaseResponse{ public void setServices(List services) { this.services = services; } - + public void setState(String state) { this.state = state; } diff --git a/api/src/com/cloud/api/response/VpcResponse.java b/api/src/org/apache/cloudstack/api/response/VpcResponse.java similarity index 83% rename from api/src/com/cloud/api/response/VpcResponse.java rename to api/src/org/apache/cloudstack/api/response/VpcResponse.java index bb79e53e942..94ea5983bf6 100644 --- a/api/src/com/cloud/api/response/VpcResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpcResponse.java @@ -14,77 +14,80 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.Date; import java.util.List; -import com.cloud.api.ApiConstants; +import com.cloud.network.vpc.Vpc; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=Vpc.class) @SuppressWarnings("unused") public class VpcResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName("id") @Param(description="the id of the VPC") - private final IdentityProxy id = new IdentityProxy("vpc"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="the name of the VPC") private String name; - + @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="an alternate display text of the VPC.") private String displayText; - + @SerializedName(ApiConstants.STATE) @Param(description="state of the VPC. Can be Inactive/Enabled") private String state; - + @SerializedName(ApiConstants.ZONE_ID) @Param(description="zone id of the vpc") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.ZONE_NAME) @Param(description="the name of the zone the VPC belongs to") private String zoneName; - + @SerializedName(ApiConstants.SERVICE) @Param(description="the list of supported services", responseObject = ServiceResponse.class) private List services; - + @SerializedName(ApiConstants.CIDR) @Param(description="the cidr the VPC") private String cidr; - + @SerializedName(ApiConstants.VPC_OFF_ID) @Param(description="vpc offering id the VPC is created from") - private IdentityProxy vpcOfferingId = new IdentityProxy("vpc_offerings"); - + private String vpcOfferingId; + @SerializedName(ApiConstants.CREATED) @Param(description="the date this VPC was created") private Date created; - + @SerializedName(ApiConstants.ACCOUNT) @Param(description="the owner of the VPC") private String accountName; - + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the VPC") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the VPC") private String projectName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the VPC owner") - private IdentityProxy domainId = new IdentityProxy("domain"); - + private String domainId; + @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the owner") private String domain; - + @SerializedName(ApiConstants.NETWORK) @Param(description="the list of networks belongign to the VPC", responseObject = NetworkResponse.class) private List networks; - + @SerializedName(ApiConstants.RESTART_REQUIRED) @Param(description="true VPC requires restart") private Boolean restartRequired; - + @SerializedName(ApiConstants.NETWORK_DOMAIN) @Param(description="the network domain of the VPC") private String networkDomain; - + @SerializedName(ApiConstants.TAGS) @Param(description="the list of resource tags associated with the project", responseObject = ResourceTagResponse.class) private List tags; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -102,7 +105,7 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons public void setServices(List services) { this.services = services; } - + public void setState(String state) { this.state = state; } @@ -113,8 +116,8 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons } @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override @@ -123,8 +126,8 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons } @Override - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); + public void setDomainId(String domainId) { + this.domainId = domainId; } @Override @@ -132,16 +135,16 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons this.domain = domainName; } - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } public void setCidr(String cidr) { this.cidr = cidr; } - - public void setVpcOfferingId(Long vpcOfferingId) { - this.vpcOfferingId.setValue(vpcOfferingId); + + public void setVpcOfferingId(String vpcOfferingId) { + this.vpcOfferingId = vpcOfferingId; } public List getNetworks() { @@ -151,19 +154,19 @@ public class VpcResponse extends BaseResponse implements ControlledEntityRespons public void setNetworks(List networks) { this.networks = networks; } - + public void setRestartRequired(Boolean restartRequired) { this.restartRequired = restartRequired; } - + public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + public void setZoneName(String zoneName) { this.zoneName = zoneName; } - + public void setTags(List tags) { this.tags = tags; } diff --git a/api/src/com/cloud/api/response/VpnUsersResponse.java b/api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java similarity index 68% rename from api/src/com/cloud/api/response/VpnUsersResponse.java rename to api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java index d1e05803c9b..958c8b59bc4 100644 --- a/api/src/com/cloud/api/response/VpnUsersResponse.java +++ b/api/src/org/apache/cloudstack/api/response/VpnUsersResponse.java @@ -14,17 +14,20 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import com.cloud.network.VpnUser; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value = VpnUser.class) @SuppressWarnings("unused") public class VpnUsersResponse extends BaseResponse implements ControlledEntityResponse{ @SerializedName(ApiConstants.ID) @Param(description="the vpn userID") - private IdentityProxy id = new IdentityProxy("vpn_users"); + private String id; @SerializedName(ApiConstants.USERNAME) @Param(description="the username of the vpn user") private String userName; @@ -33,46 +36,47 @@ public class VpnUsersResponse extends BaseResponse implements ControlledEntityRe private String accountName; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the domain id of the account of the remote access vpn") - private IdentityProxy domainId = new IdentityProxy("domain"); + private String domainId; @SerializedName(ApiConstants.DOMAIN) @Param(description="the domain name of the account of the remote access vpn") - private String domainName; - + private String domainName; + @SerializedName(ApiConstants.PROJECT_ID) @Param(description="the project id of the vpn") - private IdentityProxy projectId = new IdentityProxy("projects"); - + private String projectId; + @SerializedName(ApiConstants.PROJECT) @Param(description="the project name of the vpn") private String projectName; - - public void setId(Long id) { - this.id.setValue(id); - } - - public void setUserName(String name) { - this.userName = name; - } - public void setAccountName(String accountName) { - this.accountName = accountName; - } + public void setId(String id) { + this.id = id; + } - public void setDomainId(Long domainId) { - this.domainId.setValue(domainId); - } + public void setUserName(String name) { + this.userName = name; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public void setDomainName(String name) { - this.domainName = name; - } - @Override - public void setProjectId(Long projectId) { - this.projectId.setValue(projectId); + public void setDomainId(String domainId) { + this.domainId = domainId; + } + + public void setDomainName(String name) { + this.domainName = name; + } + + @Override + public void setProjectId(String projectId) { + this.projectId = projectId; } @Override public void setProjectName(String projectName) { this.projectName = projectName; - } + } } diff --git a/api/src/com/cloud/api/response/ZoneResponse.java b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java old mode 100755 new mode 100644 similarity index 83% rename from api/src/com/cloud/api/response/ZoneResponse.java rename to api/src/org/apache/cloudstack/api/response/ZoneResponse.java index 98f808d7044..72e0bb2844d --- a/api/src/com/cloud/api/response/ZoneResponse.java +++ b/api/src/org/apache/cloudstack/api/response/ZoneResponse.java @@ -14,19 +14,22 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.response; +package org.apache.cloudstack.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.dc.DataCenter; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; @SuppressWarnings("unused") +@EntityReference(value = DataCenter.class) public class ZoneResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="Zone id") - private IdentityProxy id = new IdentityProxy("data_center"); + private String id; @SerializedName(ApiConstants.NAME) @Param(description="Zone name") private String name; @@ -45,52 +48,52 @@ public class ZoneResponse extends BaseResponse { @SerializedName(ApiConstants.INTERNAL_DNS2) @Param(description="the second internal DNS for the Zone") private String internalDns2; - + @SerializedName(ApiConstants.VLAN) @Param(description="the vlan range of the zone") private String vlan; @SerializedName(ApiConstants.GUEST_CIDR_ADDRESS) @Param(description="the guest CIDR address for the Zone") private String guestCidrAddress; - + //TODO - generate description @SerializedName("status") private String status; @SerializedName(ApiConstants.DISPLAY_TEXT) @Param(description="the display text of the zone") private String displayText; - + @SerializedName(ApiConstants.DOMAIN) @Param(description="Network domain name for the networks in the zone") private String domain; @SerializedName(ApiConstants.DOMAIN_ID) @Param(description="the ID of the containing domain, null for public zones") private Long domainId; - + @SerializedName("domainname") @Param(description="the name of the containing domain, null for public zones") private String domainName; - + @SerializedName(ApiConstants.NETWORK_TYPE) @Param(description="the network type of the zone; can be Basic or Advanced") private String networkType; - + @SerializedName("securitygroupsenabled") @Param(description="true if security groups support is enabled, false otherwise") private boolean securityGroupsEnabled; - + @SerializedName("allocationstate") @Param(description="the allocation state of the cluster") - private String allocationState; - + private String allocationState; + @SerializedName(ApiConstants.ZONE_TOKEN) @Param(description="Zone Token") - private String zoneToken; - + private String zoneToken; + @SerializedName(ApiConstants.DHCP_PROVIDER) @Param(description="the dhcp Provider for the Zone") - private String dhcpProvider; - + private String dhcpProvider; + @SerializedName("capacity") @Param(description="the capacity of the Zone", responseObject = CapacityResponse.class) private List capacitites; @SerializedName(ApiConstants.LOCAL_STORAGE_ENABLED) @Param(description="true if local storage offering enabled, false otherwise") private boolean localStorageEnabled; - public void setId(Long id) { - this.id.setValue(id); + public void setId(String id) { + this.id = id; } public void setName(String name) { @@ -137,10 +140,10 @@ public class ZoneResponse extends BaseResponse { this.domain = domain; } - public void setDomainId(Long domainId) { - this.domainId = domainId; - } - + public void setDomainId(Long domainId) { + this.domainId = domainId; + } + public void setType(String networkType) { this.networkType = networkType; } @@ -148,26 +151,26 @@ public class ZoneResponse extends BaseResponse { public void setSecurityGroupsEnabled(boolean securityGroupsEnabled) { this.securityGroupsEnabled = securityGroupsEnabled; } - + public void setAllocationState(String allocationState) { - this.allocationState = allocationState; + this.allocationState = allocationState; } - - public void setZoneToken(String zoneToken) { - this.zoneToken = zoneToken; - } - public void setDhcpProvider(String dhcpProvider) { - this.dhcpProvider = dhcpProvider; - } + public void setZoneToken(String zoneToken) { + this.zoneToken = zoneToken; + } - public void setCapacitites(List capacitites) { - this.capacitites = capacitites; - } + public void setDhcpProvider(String dhcpProvider) { + this.dhcpProvider = dhcpProvider; + } - public void setDomainName(String domainName) { - this.domainName = domainName; - } + public void setCapacitites(List capacitites) { + this.capacitites = capacitites; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } public void setLocalStorageEnabled(boolean localStorageEnabled) { this.localStorageEnabled = localStorageEnabled; diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java similarity index 89% rename from server/src/com/cloud/network/ExternalNetworkDeviceManager.java rename to api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java index b1de86f70f2..426a3b57dd9 100644 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManager.java +++ b/api/src/org/apache/cloudstack/network/ExternalNetworkDeviceManager.java @@ -14,19 +14,21 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.network; +package org.apache.cloudstack.network; import java.util.ArrayList; import java.util.List; -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; + +import com.cloud.network.Network; +import org.apache.cloudstack.api.command.admin.network.AddNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.ListNetworkDeviceCmd; import com.cloud.host.Host; -import com.cloud.server.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; import com.cloud.utils.component.Manager; public interface ExternalNetworkDeviceManager extends Manager { - + public static class NetworkDevice { private String _name; private String _provider; @@ -47,7 +49,7 @@ public interface ExternalNetworkDeviceManager extends Manager { _provider = ntwkServiceprovider; supportedNetworkDevices.add(this); } - + public String getName() { return _name; } @@ -67,11 +69,11 @@ public interface ExternalNetworkDeviceManager extends Manager { } public Host addNetworkDevice(AddNetworkDeviceCmd cmd); - + public NetworkDeviceResponse getApiResponse(Host device); - + public List listNetworkDevice(ListNetworkDeviceCmd cmd); - + public boolean deleteNetworkDevice(DeleteNetworkDeviceCmd cmd); - + } diff --git a/api/src/org/apache/cloudstack/query/QueryService.java b/api/src/org/apache/cloudstack/query/QueryService.java new file mode 100644 index 00000000000..480eb316e97 --- /dev/null +++ b/api/src/org/apache/cloudstack/query/QueryService.java @@ -0,0 +1,91 @@ +// 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 org.apache.cloudstack.query; + +import java.util.List; + +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; + + + +import com.cloud.async.AsyncJob; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.utils.Pair; + +/** + * Service used for list api query. + * @author minc + * + */ +public interface QueryService { + + public ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException; + + public ListResponse searchForEvents(ListEventsCmd cmd); + + public ListResponse listTags(ListTagsCmd cmd); + + public ListResponse searchForVmGroups(ListVMGroupsCmd cmd); + + public ListResponse searchForUserVMs(ListVMsCmd cmd); + + public ListResponse searchForSecurityGroups(ListSecurityGroupsCmd cmd); + + public ListResponse searchForRouters(ListRoutersCmd cmd); + + public ListResponse listProjectInvitations(ListProjectInvitationsCmd cmd); + + public ListResponse listProjects(ListProjectsCmd cmd); + + public ListResponse listProjectAccounts(ListProjectAccountsCmd cmd); + + public ListResponse searchForServers(ListHostsCmd cmd); + + public ListResponse searchForVolumes(ListVolumesCmd cmd); + + public ListResponse searchForAccounts(ListAccountsCmd cmd); + + public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd); +} diff --git a/api/test/integration/api/__init__.py b/api/test/integration/api/__init__.py new file mode 100644 index 00000000000..d216be4ddc9 --- /dev/null +++ b/api/test/integration/api/__init__.py @@ -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. \ No newline at end of file diff --git a/api/test/integration/api/setup.py b/api/test/integration/api/setup.py new file mode 100644 index 00000000000..13a83393a91 --- /dev/null +++ b/api/test/integration/api/setup.py @@ -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/api/test/integration/api/test/__init__.py b/api/test/integration/api/test/__init__.py new file mode 100644 index 00000000000..d216be4ddc9 --- /dev/null +++ b/api/test/integration/api/test/__init__.py @@ -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. \ No newline at end of file diff --git a/api/test/integration/api/test/account/__init__.py b/api/test/integration/api/test/account/__init__.py new file mode 100644 index 00000000000..d216be4ddc9 --- /dev/null +++ b/api/test/integration/api/test/account/__init__.py @@ -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. \ No newline at end of file diff --git a/api/test/integration/api/test/account/testCreateAccount.py b/api/test/integration/api/test/account/testCreateAccount.py new file mode 100644 index 00000000000..b094e819421 --- /dev/null +++ b/api/test/integration/api/test/account/testCreateAccount.py @@ -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. + +import factory +import marvin +from marvin import cloudstackTestCase +from marvin.integration.lib.base import * +from marvin.integration.lib import utils + +class AccountFactory(factory.Factory): + FACTORY_FOR = createAccount.createAccountCmd + + firstname = 'firstname-'+random_gen() + lastname = 'lastname-'+random_gen() + email = factory.lazy_attribute(lambda e: '{0}.{1}@cloudstack.org'.format(e.firstname, e.lastname).lower()) + +class AdminAccountFactory(AccountFactory): + accounttype = 1 + +class UserAccountFactory(AccountFactory): + accounttype = 0 + +class TestCreateAccount(cloudstackTestCase): + def setUp(self): + self.apiClient = self.testClient.getApiClient() + self.userApiClient = self.testClient.getUserApiClient(account='test'+utils.random_gen(), 'ROOT') + + def test_createAccountAsAdmin(self): + """ + creates an account for a user as admin + """ + Account.create(self.apiClient, services=None) + from marvin.cloudstackAPI.createAccount import createAccountCmd + self.assertEqual(True, False) + + def test_createAccountAsUser(self): + """ + negative: create account as a user + """ + self.assertEqual(True, False) + + def tearDown(self): + self.apiClient.close() + self.userApiClient.close() + +if __name__ == '__main__': + unittest.main() diff --git a/api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java new file mode 100644 index 00000000000..d0e8b4c7337 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AgentControlAnswerTest.java @@ -0,0 +1,35 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +import com.cloud.agent.api.AgentControlAnswer; +import com.cloud.agent.api.AgentControlCommand; + +public class AgentControlAnswerTest { + AgentControlCommand acc = new AgentControlCommand(); + AgentControlAnswer aca = new AgentControlAnswer(acc); + + @Test + public void testExecuteInSequence() { + boolean b = acc.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java new file mode 100644 index 00000000000..24d0fe587b8 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AgentControlCommandTest.java @@ -0,0 +1,33 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; + +import org.junit.Test; + +import com.cloud.agent.api.AgentControlCommand; + +public class AgentControlCommandTest { + AgentControlCommand acc = new AgentControlCommand(); + + @Test + public void testExecuteInSequence() { + boolean b = acc.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java new file mode 100644 index 00000000000..343a3ce2a51 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AnswerTest.java @@ -0,0 +1,73 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.AgentControlCommand; +import com.cloud.agent.api.Answer; +import com.cloud.agent.api.UnsupportedAnswer; + +public class AnswerTest { + AgentControlCommand acc = new AgentControlCommand(); + Answer a = new Answer(acc, true, "details"); + + @Test + public void testExecuteInSequence() { + boolean b = a.executeInSequence(); + assertFalse(b); + } + + @Test + public void testGetResult() { + boolean b = a.getResult(); + assertTrue(b); + } + + @Test + public void testGetDetails() { + String d = a.getDetails(); + assertTrue(d.equals("details")); + } + + @Test + public void testCreateUnsupportedCommandAnswer() { + UnsupportedAnswer usa = Answer.createUnsupportedCommandAnswer(acc); + boolean b = usa.executeInSequence(); + assertFalse(b); + + b = usa.getResult(); + assertFalse(b); + + String d = usa.getDetails(); + assertTrue(d.equals("Unsupported command issued:" + acc.toString() + + ". Are you sure you got the right type of server?")); + + usa = Answer.createUnsupportedVersionAnswer(acc); + b = usa.executeInSequence(); + assertFalse(b); + + b = usa.getResult(); + assertFalse(b); + + d = usa.getDetails(); + assertTrue(d.equals("Unsuppored Version.")); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java new file mode 100644 index 00000000000..d189d9ca858 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachIsoCommandTest.java @@ -0,0 +1,80 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.AttachIsoCommand; + +public class AttachIsoCommandTest { + AttachIsoCommand aic = new AttachIsoCommand("vmname", "isopath", false); + + @Test + public void testGetVmName() { + String vmName = aic.getVmName(); + assertTrue(vmName.equals("vmname")); + } + + @Test + public void testGetIsoPath() { + String isoPath = aic.getIsoPath(); + assertTrue(isoPath.equals("isopath")); + } + + @Test + public void testIsAttach() { + boolean b = aic.isAttach(); + assertFalse(b); + } + + @Test + public void testGetStoreUrl() { + aic.setStoreUrl("http://incubator.apache.org/cloudstack/"); + String url = aic.getStoreUrl(); + assertTrue(url.equals("http://incubator.apache.org/cloudstack/")); + } + + @Test + public void testExecuteInSequence() { + boolean b = aic.executeInSequence(); + assertTrue(b); + } + + @Test + public void testAllowCaching() { + boolean b = aic.allowCaching(); + assertTrue(b); + } + + @Test + public void testGetWait() { + int b; + aic.setWait(5); + b = aic.getWait(); + assertEquals(b, 5); + aic.setWait(-3); + b = aic.getWait(); + assertEquals(b, -3); + aic.setWait(0); + b = aic.getWait(); + assertEquals(b, 0); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java new file mode 100644 index 00000000000..251a6cb917e --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeAnswerTest.java @@ -0,0 +1,65 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.AttachVolumeAnswer; +import com.cloud.agent.api.AttachVolumeCommand; +import com.cloud.storage.Storage.StoragePoolType; + +public class AttachVolumeAnswerTest { + AttachVolumeCommand avc = new AttachVolumeCommand(true, "vmname", + StoragePoolType.Filesystem, "vFolder", "vPath", "vName", + 123456789L, "chainInfo"); + AttachVolumeAnswer ava1 = new AttachVolumeAnswer(avc); + String results = ""; + AttachVolumeAnswer ava2 = new AttachVolumeAnswer(avc, results); + Long deviceId = 10L; + AttachVolumeAnswer ava3 = new AttachVolumeAnswer(avc, deviceId); + + @Test + public void testGetDeviceId() { + Long dId = ava1.getDeviceId(); + assertTrue(dId == null); + + dId = ava2.getDeviceId(); + assertTrue(dId == null); + + dId = ava3.getDeviceId(); + Long expected = 10L; + assertEquals(expected, dId); + } + + @Test + public void testGetChainInfo() { + ava1.setChainInfo("chainInfo"); + String chainInfo = ava1.getChainInfo(); + assertTrue(chainInfo.equals("chainInfo")); + + ava2.setChainInfo("chainInfo"); + chainInfo = ava2.getChainInfo(); + assertTrue(chainInfo.equals("chainInfo")); + + ava3.setChainInfo("chainInfo"); + chainInfo = ava3.getChainInfo(); + assertTrue(chainInfo.equals("chainInfo")); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java new file mode 100644 index 00000000000..1ec416a4d02 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/AttachVolumeCommandTest.java @@ -0,0 +1,120 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.AttachVolumeCommand; +import com.cloud.storage.Storage.StoragePoolType; + +public class AttachVolumeCommandTest { + AttachVolumeCommand avc = new AttachVolumeCommand(true, "vmname", + StoragePoolType.Filesystem, "vFolder", "vPath", "vName", + 123456789L, "chainInfo"); + + @Test + public void testExecuteInSequence() { + boolean b = avc.executeInSequence(); + assertTrue(b); + } + + @Test + public void testGetAttach() { + boolean b = avc.getAttach(); + assertTrue(b); + } + + @Test + public void testGetVmName() { + String vmName = avc.getVmName(); + assertTrue(vmName.equals("vmname")); + } + + @Test + public void testGetPooltype() { + StoragePoolType pt = avc.getPooltype(); + assertTrue(pt.equals(StoragePoolType.Filesystem)); + + avc.setPooltype(StoragePoolType.NetworkFilesystem); + pt = avc.getPooltype(); + assertTrue(pt.equals(StoragePoolType.NetworkFilesystem)); + + avc.setPooltype(StoragePoolType.IscsiLUN); + pt = avc.getPooltype(); + assertTrue(pt.equals(StoragePoolType.IscsiLUN)); + + avc.setPooltype(StoragePoolType.Iscsi); + pt = avc.getPooltype(); + assertTrue(pt.equals(StoragePoolType.Iscsi)); + } + + @Test + public void testGetVolumeFolder() { + String vFolder = avc.getVolumeFolder(); + assertTrue(vFolder.equals("vFolder")); + } + + @Test + public void testGetVolumePath() { + String vPath = avc.getVolumePath(); + assertTrue(vPath.equals("vPath")); + } + + @Test + public void testGetVolumeName() { + String vName = avc.getVolumeName(); + assertTrue(vName.equals("vName")); + } + + @Test + public void testGetDeviceId() { + Long dId = avc.getDeviceId(); + Long expected = 123456789L; + assertEquals(expected, dId); + + avc.setDeviceId(5L); + dId = avc.getDeviceId(); + expected = 5L; + assertEquals(expected, dId); + + avc.setDeviceId(0L); + dId = avc.getDeviceId(); + expected = 0L; + assertEquals(expected, dId); + + avc.setDeviceId(-5L); + dId = avc.getDeviceId(); + expected = -5L; + assertEquals(expected, dId); + } + + @Test + public void testGetPoolUuid() { + avc.setPoolUuid("420fa39c-4ef1-a83c-fd93-46dc1ff515ae"); + String pUuid = avc.getPoolUuid(); + assertTrue(pUuid.equals("420fa39c-4ef1-a83c-fd93-46dc1ff515ae")); + } + + @Test + public void testGetWait() { + String cInfo = avc.getChainInfo(); + assertTrue(cInfo.equals("chainInfo")); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java new file mode 100644 index 00000000000..ede86e9d857 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotAnswerTest.java @@ -0,0 +1,75 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.cloud.agent.api.BackupSnapshotAnswer; +import com.cloud.agent.api.BackupSnapshotCommand; +import com.cloud.storage.StoragePool; + +public class BackupSnapshotAnswerTest { + private BackupSnapshotCommand bsc; + private BackupSnapshotAnswer bsa; + + @Before + public void setUp() { + + StoragePool pool = Mockito.mock(StoragePool.class); + + bsc = new BackupSnapshotCommand( + "secondaryStoragePoolURL", 101L, 102L, 103L, 104L, + "volumePath", pool, "snapshotUuid", "snapshotName", + "prevSnapshotUuid", "prevBackupUuid", false, "vmName", 5); + bsa = new BackupSnapshotAnswer(bsc, true, "results", "bussname", false); + } + + @Test + public void testExecuteInSequence() { + boolean b = bsa.executeInSequence(); + assertFalse(b); + } + + @Test + public void testIsFull() { + boolean b = bsa.isFull(); + assertFalse(b); + } + + @Test + public void testGetBackupSnapshotName() { + String name = bsa.getBackupSnapshotName(); + assertTrue(name.equals("bussname")); + } + + @Test + public void testGetResult() { + boolean b = bsa.getResult(); + assertTrue(b); + } + + @Test + public void testDetails() { + String details = bsa.getDetails(); + assertTrue(details.equals("results")); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java new file mode 100644 index 00000000000..91573d03c43 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/BackupSnapshotCommandTest.java @@ -0,0 +1,271 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.junit.Test; + +import com.cloud.agent.api.BackupSnapshotCommand; +import com.cloud.agent.api.to.StorageFilerTO; +import com.cloud.agent.api.to.SwiftTO; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.storage.StoragePool; +import com.cloud.storage.StoragePoolStatus; + +public class BackupSnapshotCommandTest { + 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; + }; + }; + + BackupSnapshotCommand bsc = new BackupSnapshotCommand( + "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( + "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); + + @Test + public void testGetPrimaryStoragePoolNameLabel() { + String label = bsc.getPrimaryStoragePoolNameLabel(); + assertTrue(label.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + } + + @Test + public void testGetSecondaryStorageUrl() { + String url = bsc.getSecondaryStorageUrl(); + assertTrue(url.equals("http://secondary.Storage.Url")); + } + + @Test + public void testGetDataCenterId() { + Long dcId = bsc.getDataCenterId(); + Long expected = 101L; + assertEquals(expected, dcId); + } + + @Test + public void testGetAccountId() { + Long aId = bsc.getAccountId(); + Long expected = 102L; + assertEquals(expected, aId); + } + + @Test + public void testGetVolumeId() { + Long vId = bsc.getVolumeId(); + Long expected = 103L; + assertEquals(expected, vId); + } + + @Test + public void testGetSnapshotId() { + Long ssId = bsc.getSnapshotId(); + Long expected = 104L; + assertEquals(expected, ssId); + } + + @Test + public void testGetPool() { + StorageFilerTO pool = bsc.getPool(); + + Long id = pool.getId(); + Long expectedL = 1L; + assertEquals(expectedL, id); + + String uuid = pool.getUuid(); + assertTrue(uuid.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + + String host = pool.getHost(); + assertTrue(host.equals("hostAddress")); + + String path = pool.getPath(); + assertTrue(path.equals("path")); + + String userInfo = pool.getUserInfo(); + assertTrue(userInfo.equals("userInfo")); + + Integer port = pool.getPort(); + Integer expectedI = 25; + assertEquals(expectedI, port); + + StoragePoolType type = pool.getType(); + assertEquals(StoragePoolType.Filesystem, type); + + String str = pool.toString(); + assertTrue(str.equals("Pool[" + id.toString() + "|" + host + ":" + + port.toString() + "|" + path + "]")); + } + + @Test + public void testGetCreated() { + try { + Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/1970 12:12:12"); + Date d = pool.getCreated(); + assertTrue(d.compareTo(date) == 0); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testGetSwift() { + SwiftTO s1 = new SwiftTO(); + bsc.setSwift(s1); + SwiftTO s2 = bsc.getSwift(); + assertEquals(s1, s2); + } + + @Test + public void testGetSnapshotName() { + String ssName = bsc.getSnapshotName(); + assertTrue(ssName.equals("sName")); + } + + @Test + public void testGetSnapshotUuid() { + String uuid = bsc.getSnapshotUuid(); + assertTrue(uuid.equals("420fa39c-4ef1-a83c-fd93-46dc1ff515ae")); + } + + @Test + public void testGetPrevSnapshotUuid() { + String uuid = bsc.getPrevSnapshotUuid(); + assertTrue(uuid.equals("9012793e-0657-11e2-bebc-0050568b0057")); + } + + @Test + public void testGetPrevBackupUuid() { + String uuid = bsc.getPrevBackupUuid(); + assertTrue(uuid.equals("7167e0b2-f5b0-11e1-8414-0050568b0057")); + } + + @Test + public void testGetVolumePath() { + String path = bsc.getVolumePath(); + assertTrue(path.equals("vPath")); + + bsc.setVolumePath("vPath1"); + path = bsc.getVolumePath(); + assertTrue(path.equals("vPath1")); + + bsc1.setVolumePath("vPath2"); + path = bsc1.getVolumePath(); + assertTrue(path.equals("vPath2")); + } + + @Test + public void testExecuteInSequence() { + boolean b = bsc.executeInSequence(); + assertFalse(b); + + b = bsc1.executeInSequence(); + assertFalse(b); + } + +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java new file mode 100644 index 00000000000..f5f59852ea8 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/BumpUpPriorityCommandTest.java @@ -0,0 +1,83 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.BumpUpPriorityCommand; +import com.cloud.agent.api.routing.NetworkElementCommand; + +public class BumpUpPriorityCommandTest { + + BumpUpPriorityCommand bupc = new BumpUpPriorityCommand(); + + // test super class + @Test + public void testSuperGetAccessDetail() { + String value; + bupc.setAccessDetail(NetworkElementCommand.ACCOUNT_ID, "accountID"); + value = bupc.getAccessDetail(NetworkElementCommand.ACCOUNT_ID); + assertTrue(value.equals("accountID")); + + bupc.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR, + "GuestNetworkCIDR"); + value = bupc.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_CIDR); + assertTrue(value.equals("GuestNetworkCIDR")); + + bupc.setAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY, + "GuestNetworkGateway"); + value = bupc + .getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); + assertTrue(value.equals("GuestNetworkGateway")); + + bupc.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, + "GuestVlanTag"); + value = bupc.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG); + assertTrue(value.equals("GuestVlanTag")); + + bupc.setAccessDetail(NetworkElementCommand.ROUTER_NAME, "RouterName"); + value = bupc.getAccessDetail(NetworkElementCommand.ROUTER_NAME); + assertTrue(value.equals("RouterName")); + + bupc.setAccessDetail(NetworkElementCommand.ROUTER_IP, "RouterIP"); + value = bupc.getAccessDetail(NetworkElementCommand.ROUTER_IP); + assertTrue(value.equals("RouterIP")); + + bupc.setAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP, + "RouterGuestIP"); + value = bupc.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); + assertTrue(value.equals("RouterGuestIP")); + + bupc.setAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE, + "ZoneNetworkType"); + value = bupc.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); + assertTrue(value.equals("ZoneNetworkType")); + + bupc.setAccessDetail(NetworkElementCommand.GUEST_BRIDGE, "GuestBridge"); + value = bupc.getAccessDetail(NetworkElementCommand.GUEST_BRIDGE); + assertTrue(value.equals("GuestBridge")); + } + + @Test + public void testExecuteInSequence() { + boolean b = bupc.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java b/api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java similarity index 54% rename from api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java rename to api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java index af90df9282b..19827fd5753 100644 --- a/api/src/com/cloud/api/commands/ListTemplatePermissionsCmd.java +++ b/api/test/org/apache/cloudstack/api/agent/test/CancelCommandTest.java @@ -14,29 +14,33 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -package com.cloud.api.commands; +package org.apache.cloudstack.api.agent.test; -import org.apache.log4j.Logger; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; -import com.cloud.storage.Storage.ImageFormat; -import com.cloud.template.VirtualMachineTemplate; +import org.junit.Test; -public class ListTemplatePermissionsCmd extends ListTemplateOrIsoPermissionsCmd { - protected String getResponseName() { - return "listtemplatepermissionsresponse"; +import com.cloud.agent.api.CancelCommand; + +public class CancelCommandTest { + CancelCommand cc = new CancelCommand(123456789L, "goodreason"); + + @Test + public void testGetSequence() { + Long s = cc.getSequence(); + assertTrue(123456789L == s); } - - @Override - public String getMediaType() { - return "template"; + + @Test + public void testGetReason() { + String r = cc.getReason(); + assertTrue(r.equals("goodreason")); + } + + @Test + public void testExecuteInSequence() { + boolean b = cc.executeInSequence(); + assertFalse(b); } - - @Override - protected Logger getLogger() { - return Logger.getLogger(ListTemplatePermissionsCmd.class.getName()); - } - - protected boolean templateIsCorrectType(VirtualMachineTemplate template) { - return !template.getFormat().equals(ImageFormat.ISO); - } } diff --git a/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java new file mode 100644 index 00000000000..8933e6e9b27 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentAnswerTest.java @@ -0,0 +1,44 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.ChangeAgentAnswer; +import com.cloud.agent.api.ChangeAgentCommand; +import com.cloud.host.Status.Event; + +public class ChangeAgentAnswerTest { + ChangeAgentCommand cac = new ChangeAgentCommand(123456789L, + Event.AgentConnected); + ChangeAgentAnswer caa = new ChangeAgentAnswer(cac, true); + + @Test + public void testGetResult() { + boolean b = caa.getResult(); + assertTrue(b); + } + + @Test + public void testExecuteInSequence() { + boolean b = caa.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java new file mode 100644 index 00000000000..d0c2bf8b47b --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/ChangeAgentCommandTest.java @@ -0,0 +1,50 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.ChangeAgentCommand; +import com.cloud.host.Status.Event; + +public class ChangeAgentCommandTest { + + ChangeAgentCommand cac = new ChangeAgentCommand(123456789L, + Event.AgentConnected); + + @Test + public void testGetAgentId() { + Long aid = cac.getAgentId(); + assertTrue(123456789L == aid); + } + + @Test + public void testGetEvent() { + Event e = cac.getEvent(); + assertEquals(Event.AgentConnected, e); + } + + @Test + public void testExecuteInSequence() { + boolean b = cac.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java new file mode 100644 index 00000000000..6fa94f9884d --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthAnswerTest.java @@ -0,0 +1,49 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.CheckHealthAnswer; +import com.cloud.agent.api.CheckHealthCommand; + +public class CheckHealthAnswerTest { + CheckHealthCommand chc = new CheckHealthCommand(); + CheckHealthAnswer cha = new CheckHealthAnswer(chc, true); + + @Test + public void testGetResult() { + boolean r = cha.getResult(); + assertTrue(r); + } + + @Test + public void testGetDetails() { + String d = cha.getDetails(); + boolean r = cha.getResult(); + assertTrue(d.equals("resource is " + (r ? "alive" : "not alive"))); + } + + @Test + public void testExecuteInSequence() { + boolean b = cha.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java new file mode 100644 index 00000000000..1b565a5505b --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckHealthCommandTest.java @@ -0,0 +1,40 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +import com.cloud.agent.api.CheckHealthCommand; + +public class CheckHealthCommandTest { + CheckHealthCommand chc = new CheckHealthCommand(); + + @Test + public void testGetWait() { + int wait = chc.getWait(); + assertTrue(wait == 50); + } + + @Test + public void testExecuteInSequence() { + boolean b = chc.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java new file mode 100644 index 00000000000..1853d3967c9 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkAnswerTest.java @@ -0,0 +1,62 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.cloud.agent.api.CheckNetworkAnswer; +import com.cloud.agent.api.CheckNetworkCommand; + +public class CheckNetworkAnswerTest { + CheckNetworkCommand cnc; + CheckNetworkAnswer cna; + + @Before + public void setUp() { + cnc = Mockito.mock(CheckNetworkCommand.class); + cna = new CheckNetworkAnswer(cnc, true, "details", true); + } + + @Test + public void testGetResult() { + boolean b = cna.getResult(); + assertTrue(b); + } + + @Test + public void testGetDetails() { + String d = cna.getDetails(); + assertTrue(d.equals("details")); + } + + @Test + public void testNeedReconnect() { + boolean b = cna.needReconnect(); + assertTrue(b); + } + + @Test + public void testExecuteInSequence() { + boolean b = cna.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java new file mode 100644 index 00000000000..0b87b587563 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckNetworkCommandTest.java @@ -0,0 +1,53 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import com.cloud.agent.api.CheckNetworkCommand; +import com.cloud.network.PhysicalNetworkSetupInfo; + +public class CheckNetworkCommandTest { + CheckNetworkCommand cnc; + + @Before + public void setUp() { + @SuppressWarnings("unchecked") + List net = Mockito.mock(List.class); + cnc = new CheckNetworkCommand(net); + } + + @Test + public void testGetPhysicalNetworkInfoList() { + List networkInfoList = cnc + .getPhysicalNetworkInfoList(); + assertEquals(0, networkInfoList.size()); + } + + @Test + public void testExecuteInSequence() { + boolean b = cnc.executeInSequence(); + assertTrue(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java new file mode 100644 index 00000000000..1b682761996 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/CheckOnHostCommandTest.java @@ -0,0 +1,483 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import org.junit.Test; + +import com.cloud.agent.api.CheckOnHostCommand; +import com.cloud.agent.api.to.HostTO; +import com.cloud.host.Host; +import com.cloud.host.Status; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.resource.ResourceState; + +public class CheckOnHostCommandTest { + public Host host = new Host() { + public Status getState() { + return Status.Up; + }; + + public long getId() { + return 101L; + }; + + + @Override + public String getUuid() { + return "101"; + } + + public String getName() { + return "hostName"; + }; + + public Type getType() { + return Host.Type.Storage; + }; + + 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 Status getStatus() { + return Status.Up; + }; + + public String getPrivateIpAddress() { + return "10.1.1.1"; + }; + + public String getStorageIpAddress() { + return "10.1.1.2"; + }; + + public String getGuid() { + return "bed9f83e-cac3-11e1-ac8a-0050568b007e"; + }; + + public Long getTotalMemory() { + return 100000000000L; + }; + + public Integer getCpus() { + return 16; + }; + + public Long getSpeed() { + return 2000000000L; + }; + + public Integer getProxyPort() { + return 22; + }; + + public Long getPodId() { + return 16L; + }; + + public long getDataCenterId() { + return 17L; + }; + + public String getParent() { + return "parent"; + }; + + public String getStorageIpAddressDeux() { + return "10.1.1.3"; + }; + + public HypervisorType getHypervisorType() { + return HypervisorType.XenServer; + }; + + public Date getDisconnectedOn() { + Date date = null; + try { + date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/2012 12:12:12"); + } catch (ParseException e) { + e.printStackTrace(); + } + return date; + } + + public String getVersion() { + return "4.0.1"; + }; + + public long getTotalSize() { + return 100000000000L; + }; + + public String getCapabilities() { + return "capabilities"; + }; + + public long getLastPinged() { + return 1L; + }; + + public Long getManagementServerId() { + return 2L; + }; + + public Date getRemoved() { + Date date = null; + try { + date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("02/01/2012 12:12:12"); + } catch (ParseException e) { + e.printStackTrace(); + } + return date; + }; + + public Long getClusterId() { + return 3L; + }; + + public String getPublicIpAddress() { + return "10.1.1.4"; + }; + + public String getPublicNetmask() { + return "255.255.255.8"; + }; + + public String getPrivateNetmask() { + return "255.255.255.16"; + }; + + public String getStorageNetmask() { + return "255.255.255.24"; + }; + + public String getStorageMacAddress() { + return "01:f4:17:38:0e:26"; + }; + + public String getPublicMacAddress() { + return "02:f4:17:38:0e:26"; + }; + + public String getPrivateMacAddress() { + return "03:f4:17:38:0e:26"; + }; + + public String getStorageNetmaskDeux() { + return "255.255.255.25"; + }; + + public String getStorageMacAddressDeux() { + return "01:f4:17:38:0e:27"; + }; + + public String getHypervisorVersion() { + return "1.2.3.0"; + }; + + public boolean isInMaintenanceStates() { + return false; + }; + + public ResourceState getResourceState() { + return ResourceState.Enabled; + }; + }; + + CheckOnHostCommand cohc = new CheckOnHostCommand(host); + + @Test + public void testGetHost() { + HostTO h = cohc.getHost(); + assertNotNull(h); + } + + @Test + public void testGetState() { + Status s = host.getState(); + assertTrue(s == Status.Up); + } + + @Test + public void testGetId() { + Long id = host.getId(); + assertTrue(101L == id); + } + + @Test + public void testGetName() { + String name = host.getName(); + assertTrue(name.equals("hostName")); + } + + @Test + public void testGetType() { + Host.Type t = host.getType(); + assertTrue(t == Host.Type.Storage); + } + + @Test + public void testGetCreated() { + try { + Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/1970 12:12:12"); + Date d = host.getCreated(); + assertTrue(d.compareTo(date) == 0); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testGetStatus() { + Status s = host.getStatus(); + assertTrue(s == Status.Up); + } + + @Test + public void testGetPrivateIpAddress() { + String addr = host.getPrivateIpAddress(); + assertTrue(addr.equals("10.1.1.1")); + } + + @Test + public void testGetStorageIpAddress() { + String addr = host.getStorageIpAddress(); + assertTrue(addr.equals("10.1.1.2")); + } + + @Test + public void testGetGuid() { + String guid = host.getGuid(); + assertTrue(guid.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + } + + @Test + public void testGetTotalMemory() { + Long m = host.getTotalMemory(); + assertTrue(m == 100000000000L); + } + + @Test + public void testGetCpus() { + int cpus = host.getCpus(); + assertTrue(cpus == 16); + } + + @Test + public void testGetSpeed() { + Long spped = host.getSpeed(); + assertTrue(spped == 2000000000L); + } + + @Test + public void testGetProxyPort() { + Integer port = host.getProxyPort(); + assertTrue(port == 22); + } + + @Test + public void testGetPodId() { + Long pID = host.getPodId(); + assertTrue(pID == 16L); + } + + @Test + public void testGetDataCenterId() { + long dcID = host.getDataCenterId(); + assertTrue(dcID == 17L); + } + + @Test + public void testGetParent() { + String p = host.getParent(); + assertTrue(p.equals("parent")); + } + + @Test + public void testGetStorageIpAddressDeux() { + String addr = host.getStorageIpAddressDeux(); + assertTrue(addr.equals("10.1.1.3")); + } + + @Test + public void testGetHypervisorType() { + HypervisorType type = host.getHypervisorType(); + assertTrue(type == HypervisorType.XenServer); + } + + @Test + public void testGetDisconnectedOn() { + try { + Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("01/01/2012 12:12:12"); + Date d = host.getDisconnectedOn(); + assertTrue(d.compareTo(date) == 0); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testGetVersion() { + String v = host.getVersion(); + assertTrue(v.equals("4.0.1")); + } + + @Test + public void testGetTotalSize() { + long size = host.getTotalSize(); + assertTrue(size == 100000000000L); + } + + @Test + public void testGetCapabilities() { + String c = host.getCapabilities(); + assertTrue(c.equals("capabilities")); + } + + @Test + public void testGetLastPinged() { + long lp = host.getLastPinged(); + assertTrue(lp == 1L); + } + + @Test + public void testGetManagementServerId() { + Long msID = host.getManagementServerId(); + assertTrue(msID == 2L); + } + + @Test + public void testGetRemoved() { + try { + Date date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss") + .parse("02/01/2012 12:12:12"); + Date d = host.getRemoved(); + assertTrue(d.compareTo(date) == 0); + } catch (ParseException e) { + e.printStackTrace(); + } + } + + @Test + public void testGetClusterId() { + Long cID = host.getClusterId(); + assertTrue(cID == 3L); + } + + @Test + public void testGetPublicIpAddress() { + String pipAddr = host.getPublicIpAddress(); + assertTrue(pipAddr.equals("10.1.1.4")); + } + + @Test + public void testGetPublicNetmask() { + String pMask = host.getPublicNetmask(); + assertTrue(pMask.equals("255.255.255.8")); + } + + @Test + public void testGetPrivateNetmask() { + String pMask = host.getPrivateNetmask(); + assertTrue(pMask.equals("255.255.255.16")); + } + + @Test + public void testGetStorageNetmask() { + String sMask = host.getStorageNetmask(); + assertTrue(sMask.equals("255.255.255.24")); + } + + @Test + public void testGetStorageMacAddress() { + String sMac = host.getStorageMacAddress(); + assertTrue(sMac.equals("01:f4:17:38:0e:26")); + } + + @Test + public void testGetPublicMacAddress() { + String pMac = host.getPublicMacAddress(); + assertTrue(pMac.equals("02:f4:17:38:0e:26")); + } + + @Test + public void testGetPrivateMacAddress() { + String pMac = host.getPrivateMacAddress(); + assertTrue(pMac.equals("03:f4:17:38:0e:26")); + } + + @Test + public void testGetStorageNetmaskDeux() { + String sMask = host.getStorageNetmaskDeux(); + assertTrue(sMask.equals("255.255.255.25")); + } + + @Test + public void testGetStorageMacAddressDeux() { + String sMac = host.getStorageMacAddressDeux(); + assertTrue(sMac.equals("01:f4:17:38:0e:27")); + } + + @Test + public void testGetHypervisorVersion() { + String v = host.getHypervisorVersion(); + assertTrue(v.equals("1.2.3.0")); + } + + @Test + public void testIsInMaintenanceStates() { + boolean b = host.isInMaintenanceStates(); + assertFalse(b); + } + + @Test + public void testGetResourceState() { + ResourceState r = host.getResourceState(); + assertTrue(r == ResourceState.Enabled); + } + + @Test + public void testGetWait() { + int wait = cohc.getWait(); + assertTrue(20 == wait); + } + + @Test + public void testExecuteInSequence() { + boolean b = cohc.executeInSequence(); + assertFalse(b); + } +} diff --git a/api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java b/api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java new file mode 100644 index 00000000000..a7359134f0a --- /dev/null +++ b/api/test/org/apache/cloudstack/api/agent/test/SnapshotCommandTest.java @@ -0,0 +1,197 @@ +// 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 org.apache.cloudstack.api.agent.test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +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 { + + 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(pool, + "secondaryStorageUrl", "snapshotUuid", "snapshotName", 101L, + 102L, 103L); + } + + @Test + public void testGetPrimaryStoragePoolNameLabel() { + String label = ssc.getPrimaryStoragePoolNameLabel(); + assertTrue(label.equals("bed9f83e-cac3-11e1-ac8a-0050568b007e")); + } + + @Test + public void testGetSecondaryStorageUrl() { + String url = ssc.getSecondaryStorageUrl(); + assertTrue(url.equals("http://secondary.Storage.Url")); + } + + @Test + public void testGetSnapshotUuid() { + String uuid = ssc.getSnapshotUuid(); + assertTrue(uuid.equals("420fa39c-4ef1-a83c-fd93-46dc1ff515ae")); + } + + @Test + public void testGetSnapshotName() { + String name = ssc.getSnapshotName(); + assertTrue(name.equals("snapshotName")); + } + + @Test + public void testGetVolumePath() { + ssc.setVolumePath("vPath"); + String path = ssc.getVolumePath(); + assertTrue(path.equals("vPath")); + + ssc1.setVolumePath("vPath1"); + path = ssc1.getVolumePath(); + assertTrue(path.equals("vPath1")); + } + + @Test + public void testExecuteInSequence() { + boolean b = ssc.executeInSequence(); + assertFalse(b); + + b = ssc1.executeInSequence(); + assertFalse(b); + } + + @Test + public void testGetDataCenterId() { + Long dcId = ssc.getDataCenterId(); + Long expected = 101L; + assertEquals(expected, dcId); + } + + @Test + public void testGetAccountId() { + Long aId = ssc.getAccountId(); + Long expected = 102L; + assertEquals(expected, aId); + } + + @Test + public void testGetVolumeId() { + Long vId = ssc.getVolumeId(); + Long expected = 103L; + assertEquals(expected, vId); + } +} diff --git a/api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java new file mode 100644 index 00000000000..49b5b0e1a16 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/ActivateProjectCmdTest.java @@ -0,0 +1,87 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.user.project.ActivateProjectCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.projects.Project; +import com.cloud.projects.ProjectService; +import com.cloud.user.Account; + +public class ActivateProjectCmdTest extends TestCase { + + private ActivateProjectCmd activateProjectCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + + activateProjectCmd = new ActivateProjectCmd() { + + @Override + public Long getId() { + return 2L; + } + + }; + } + + @Test + public void testGetEntityOwnerIdForNullProject() { + ProjectService projectService = Mockito.mock(ProjectService.class); + Mockito.when(projectService.getProject(Mockito.anyLong())).thenReturn( + null); + activateProjectCmd._projectService = projectService; + + try { + activateProjectCmd.getEntityOwnerId(); + } catch (InvalidParameterValueException exception) { + Assert.assertEquals("Unable to find project by id 2", + exception.getLocalizedMessage()); + } + } + + @Test + public void testGetEntityOwnerIdForProject() { + Project project = Mockito.mock(Project.class); + Mockito.when(project.getId()).thenReturn(2L); + ProjectService projectService = Mockito.mock(ProjectService.class); + Account account = Mockito.mock(Account.class); + Mockito.when(account.getId()).thenReturn(2L); + Mockito.when(projectService.getProject(Mockito.anyLong())).thenReturn( + project); + + Mockito.when(projectService.getProjectOwner(Mockito.anyLong())) + .thenReturn(account); + activateProjectCmd._projectService = projectService; + + Assert.assertEquals(2L, activateProjectCmd.getEntityOwnerId()); + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java new file mode 100644 index 00000000000..4d2000d4249 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddAccountToProjectCmdTest.java @@ -0,0 +1,175 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.user.account.AddAccountToProjectCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.projects.Project; +import com.cloud.projects.ProjectService; +import com.cloud.user.Account; + +public class AddAccountToProjectCmdTest extends TestCase { + + private AddAccountToProjectCmd addAccountToProjectCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + addAccountToProjectCmd = new AddAccountToProjectCmd() { + + @Override + public Long getProjectId() { + return 2L; + } + + @Override + public String getAccountName() { + + // to run the test testGetEventDescriptionForAccount set the + // accountName + // return "accountName"; + // to run the test the testGetEventDescriptionForNullAccount + // return accountname as null + return null; + } + + @Override + public String getEmail() { + // return "customer@abc.com"; + return null; + } + + }; + } + + /**** + * Condition not handled in the code + * + *****/ + + /* + * @Test public void testGetEntityOwnerIdForNullProject() { + * + * ProjectService projectService = Mockito.mock(ProjectService.class); + * Mockito + * .when(projectService.getProject(Mockito.anyLong())).thenReturn(null); + * addAccountToProjectCmd._projectService = projectService; + * + * try { addAccountToProjectCmd.getEntityOwnerId(); } + * catch(InvalidParameterValueException exception) { + * Assert.assertEquals("Unable to find project by id 2", + * exception.getLocalizedMessage()); } + * + * } + */ + + @Test + public void testGetEntityOwnerIdForProject() { + + Project project = Mockito.mock(Project.class); + Mockito.when(project.getId()).thenReturn(2L); + + ProjectService projectService = Mockito.mock(ProjectService.class); + Account account = Mockito.mock(Account.class); + + Mockito.when(account.getId()).thenReturn(2L); + Mockito.when(projectService.getProject(Mockito.anyLong())).thenReturn( + project); + + Mockito.when(projectService.getProjectOwner(Mockito.anyLong())) + .thenReturn(account); + addAccountToProjectCmd._projectService = projectService; + + Assert.assertEquals(2L, addAccountToProjectCmd.getEntityOwnerId()); + + } + + /** + * To run the test uncomment the return statement for getAccountName() in + * setup() and return null + * + * **/ + + /* + * @Test public void testGetEventDescriptionForNullAccount() { + * + * String result = addAccountToProjectCmd.getEventDescription(); String + * expected = "Sending invitation to email null to join project: 2"; + * Assert.assertEquals(expected, result); + * + * } + */ + + /*** + * + * + * + * ***/ + + /* + * @Test public void testGetEventDescriptionForAccount() { + * + * String result = addAccountToProjectCmd.getEventDescription(); String + * expected = "Adding account accountName to project: 2"; + * Assert.assertEquals(expected, result); + * + * } + */ + + @Test + public void testExecuteForNullAccountNameEmail() { + + try { + addAccountToProjectCmd.execute(); + } catch (InvalidParameterValueException exception) { + Assert.assertEquals("Either accountName or email is required", + exception.getLocalizedMessage()); + } + + } + + /* + * @Test public void testExecuteForAccountNameEmail() { + * + * try { + * + * ComponentLocator c = Mockito.mock(ComponentLocator.class); UserContext + * userContext = Mockito.mock(UserContext.class); + * + * // Mockito.when(userContext.current()).thenReturn(userContext); + * + * + * addAccountToProjectCmd.execute(); } catch(InvalidParameterValueException + * exception) { + * Assert.assertEquals("Either accountName or email is required", + * exception.getLocalizedMessage()); } + * + * } + */ + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java new file mode 100644 index 00000000000..60fea9e54d2 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddClusterCmdTest.java @@ -0,0 +1,120 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.exception.DiscoveryException; +import com.cloud.exception.ResourceInUseException; +import com.cloud.org.Cluster; +import com.cloud.resource.ResourceService; + +import edu.emory.mathcs.backport.java.util.Arrays; + +public class AddClusterCmdTest extends TestCase { + + private AddClusterCmd addClusterCmd; + private ResourceService resourceService; + private ResponseGenerator responseGenerator; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + /* + * resourceService = Mockito.mock(ResourceService.class); + * responseGenerator = Mockito.mock(ResponseGenerator.class); + */addClusterCmd = new AddClusterCmd() { + }; + } + + @Test + public void testExecuteForNullResult() { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + + try { + Mockito.when(resourceService.discoverCluster(addClusterCmd)) + .thenReturn(null); + } catch (ResourceInUseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (DiscoveryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + addClusterCmd._resourceService = resourceService; + + try { + addClusterCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add cluster", + exception.getDescription()); + } + + } + + @Test + public void testExecuteForEmptyResult() { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addClusterCmd._resourceService = resourceService; + + try { + addClusterCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add cluster", + exception.getDescription()); + } + + } + + @Test + public void testExecuteForResult() throws Exception { + + resourceService = Mockito.mock(ResourceService.class); + responseGenerator = Mockito.mock(ResponseGenerator.class); + + addClusterCmd._resourceService = resourceService; + addClusterCmd._responseGenerator = responseGenerator; + + Cluster cluster = Mockito.mock(Cluster.class); + Cluster[] clusterArray = new Cluster[] { cluster }; + + Mockito.when(resourceService.discoverCluster(addClusterCmd)) + .thenReturn(Arrays.asList(clusterArray)); + + addClusterCmd.execute(); + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java new file mode 100644 index 00000000000..4c1b5ee0e0a --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddHostCmdTest.java @@ -0,0 +1,165 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.host.AddHostCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; +import com.cloud.exception.DiscoveryException; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.host.Host; +import com.cloud.resource.ResourceService; + +import edu.emory.mathcs.backport.java.util.Arrays; + +public class AddHostCmdTest extends TestCase { + + private AddHostCmd addHostCmd; + private ResourceService resourceService; + private ResponseGenerator responseGenerator; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + resourceService = Mockito.mock(ResourceService.class); + responseGenerator = Mockito.mock(ResponseGenerator.class); + addHostCmd = new AddHostCmd() { + }; + } + + @Test + public void testExecuteForEmptyResult() { + addHostCmd._resourceService = resourceService; + + try { + addHostCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add host", + exception.getDescription()); + } + + } + + @Test + public void testExecuteForNullResult() { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addHostCmd._resourceService = resourceService; + + try { + Mockito.when(resourceService.discoverHosts(addHostCmd)).thenReturn( + null); + } catch (InvalidParameterValueException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IllegalArgumentException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (DiscoveryException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + try { + addHostCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add host", + exception.getDescription()); + } + + } + + /* + * @Test public void testExecuteForResult() throws Exception { + * + * addHostCmd._resourceService = resourceService; + * addHostCmd._responseGenerator = responseGenerator; MockHost mockInstance + * = new MockHost(); MockHost[] mockArray = new MockHost[]{mockInstance}; + * HostResponse responseHost = new HostResponse(); + * responseHost.setName("Test"); + * Mockito.when(resourceService.discoverHosts(addHostCmd + * )).thenReturn(Arrays.asList(mockArray)); + * Mockito.when(responseGenerator.createHostResponse + * (mockInstance)).thenReturn(responseHost); addHostCmd.execute(); + * Mockito.verify(responseGenerator).createHostResponse(mockInstance); + * ListResponse actualResponse = + * ((ListResponse)addHostCmd.getResponseObject()); + * Assert.assertEquals(responseHost, actualResponse.getResponses().get(0)); + * Assert.assertEquals("addhostresponse", actualResponse.getResponseName()); + * } + */ + @Test + public void testExecuteForResult() throws Exception { + + addHostCmd._resourceService = resourceService; + addHostCmd._responseGenerator = responseGenerator; + Host host = Mockito.mock(Host.class); + Host[] mockArray = new Host[] { host }; + + HostResponse responseHost = new HostResponse(); + responseHost.setName("Test"); + Mockito.when(resourceService.discoverHosts(addHostCmd)).thenReturn( + Arrays.asList(mockArray)); + Mockito.when(responseGenerator.createHostResponse(host)).thenReturn( + responseHost); + addHostCmd.execute(); + Mockito.verify(responseGenerator).createHostResponse(host); + ListResponse actualResponse = ((ListResponse) addHostCmd + .getResponseObject()); + Assert.assertEquals(responseHost, actualResponse.getResponses().get(0)); + Assert.assertEquals("addhostresponse", actualResponse.getResponseName()); + + } + + @Test + public void testExecuteForDiscoveryException() { + + addHostCmd._resourceService = resourceService; + + try { + Mockito.when(resourceService.discoverHosts(addHostCmd)).thenThrow( + DiscoveryException.class); + } catch (InvalidParameterValueException e) { + e.printStackTrace(); + } catch (IllegalArgumentException e) { + e.printStackTrace(); + } catch (DiscoveryException e) { + e.printStackTrace(); + } + + try { + addHostCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertNull(exception.getDescription()); + } + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java new file mode 100644 index 00000000000..0b5798fbe23 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddNetworkServiceProviderCmdTest.java @@ -0,0 +1,122 @@ +// 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 org.apache.cloudstack.api.command.test; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.network.AddNetworkServiceProviderCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.exception.ResourceAllocationException; +import com.cloud.network.NetworkService; +import com.cloud.network.PhysicalNetworkServiceProvider; + +public class AddNetworkServiceProviderCmdTest extends TestCase { + + private AddNetworkServiceProviderCmd addNetworkServiceProviderCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + addNetworkServiceProviderCmd = new AddNetworkServiceProviderCmd() { + + @Override + public Long getPhysicalNetworkId() { + return 2L; + } + + @Override + public String getProviderName() { + return "ProviderName"; + } + + @Override + public Long getDestinationPhysicalNetworkId() { + return 2L; + } + + @Override + public List getEnabledServices() { + List lOfEnabledServices = new ArrayList(); + lOfEnabledServices.add("Enabled Services"); + return lOfEnabledServices; + } + + public Long getEntityId() { + return 2L; + } + + }; + + } + + @Test + public void testCreateProviderToPhysicalNetworkSuccess() { + + NetworkService networkService = Mockito.mock(NetworkService.class); + addNetworkServiceProviderCmd._networkService = networkService; + + PhysicalNetworkServiceProvider physicalNetworkServiceProvider = Mockito + .mock(PhysicalNetworkServiceProvider.class); + Mockito.when( + networkService.addProviderToPhysicalNetwork(Mockito.anyLong(), + Mockito.anyString(), Mockito.anyLong(), + Mockito.anyList())).thenReturn( + physicalNetworkServiceProvider); + + try { + addNetworkServiceProviderCmd.create(); + } catch (ResourceAllocationException e) { + e.printStackTrace(); + } + + } + + @Test + public void testCreateProviderToPhysicalNetworkFailure() + throws ResourceAllocationException { + + NetworkService networkService = Mockito.mock(NetworkService.class); + addNetworkServiceProviderCmd._networkService = networkService; + + Mockito.when( + networkService.addProviderToPhysicalNetwork(Mockito.anyLong(), + Mockito.anyString(), Mockito.anyLong(), + Mockito.anyList())).thenReturn(null); + + try { + addNetworkServiceProviderCmd.create(); + } catch (ServerApiException exception) { + Assert.assertEquals( + "Failed to add service provider entity to physical network", + exception.getDescription()); + } + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java new file mode 100644 index 00000000000..1cdd76fbfe2 --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddSecondaryStorageCmdTest.java @@ -0,0 +1,124 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.host.AddSecondaryStorageCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.HostResponse; +import com.cloud.host.Host; +import com.cloud.resource.ResourceService; + +import edu.emory.mathcs.backport.java.util.Arrays; + +public class AddSecondaryStorageCmdTest extends TestCase { + + private AddSecondaryStorageCmd addSecondaryStorageCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + addSecondaryStorageCmd = new AddSecondaryStorageCmd() { + }; + + } + + @Test + public void testExecuteForResult() throws Exception { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addSecondaryStorageCmd._resourceService = resourceService; + + Host host = Mockito.mock(Host.class); + Host[] mockHosts = new Host[] { host }; + + Mockito.when(resourceService.discoverHosts(addSecondaryStorageCmd)) + .thenReturn(Arrays.asList(mockHosts)); + + ResponseGenerator responseGenerator = Mockito + .mock(ResponseGenerator.class); + addSecondaryStorageCmd._responseGenerator = responseGenerator; + + HostResponse responseHost = new HostResponse(); + responseHost.setName("Test"); + + Mockito.when(responseGenerator.createHostResponse(host)).thenReturn( + responseHost); + + addSecondaryStorageCmd.execute(); + + Mockito.verify(responseGenerator).createHostResponse(host); + + HostResponse actualResponse = (HostResponse) addSecondaryStorageCmd + .getResponseObject(); + + Assert.assertEquals(responseHost, actualResponse); + Assert.assertEquals("addsecondarystorageresponse", + actualResponse.getResponseName()); + + } + + @Test + public void testExecuteForEmptyResult() throws Exception { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addSecondaryStorageCmd._resourceService = resourceService; + + Host[] mockHosts = new Host[] {}; + + Mockito.when(resourceService.discoverHosts(addSecondaryStorageCmd)) + .thenReturn(Arrays.asList(mockHosts)); + + try { + addSecondaryStorageCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add secondary storage", + exception.getDescription()); + } + + } + + @Test + public void testExecuteForNullResult() throws Exception { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addSecondaryStorageCmd._resourceService = resourceService; + + Mockito.when(resourceService.discoverHosts(addSecondaryStorageCmd)) + .thenReturn(null); + + try { + addSecondaryStorageCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add secondary storage", + exception.getDescription()); + } + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java new file mode 100644 index 00000000000..34d0baff5ab --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddSwiftCmdTest.java @@ -0,0 +1,97 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ResponseGenerator; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SwiftResponse; +import com.cloud.exception.DiscoveryException; +import com.cloud.resource.ResourceService; +import com.cloud.storage.Swift; + +public class AddSwiftCmdTest extends TestCase { + + private AddSwiftCmd addSwiftCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + addSwiftCmd = new AddSwiftCmd(); + } + + @Test + public void testExecuteSuccess() { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addSwiftCmd._resourceService = resourceService; + + Swift swift = Mockito.mock(Swift.class); + + try { + Mockito.when(resourceService.discoverSwift(addSwiftCmd)) + .thenReturn(swift); + } catch (DiscoveryException e) { + e.printStackTrace(); + } + + ResponseGenerator responseGenerator = Mockito + .mock(ResponseGenerator.class); + addSwiftCmd._responseGenerator = responseGenerator; + + SwiftResponse swiftResponse = Mockito.mock(SwiftResponse.class); + + Mockito.when(responseGenerator.createSwiftResponse(swift)).thenReturn( + swiftResponse); + + addSwiftCmd.execute(); + + } + + @Test + public void testExecuteFailure() { + + ResourceService resourceService = Mockito.mock(ResourceService.class); + addSwiftCmd._resourceService = resourceService; + try { + Mockito.when(resourceService.discoverSwift(addSwiftCmd)) + .thenReturn(null); + } catch (DiscoveryException e) { + e.printStackTrace(); + } + + try { + addSwiftCmd.execute(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add Swift", + exception.getDescription()); + } + + } + +} diff --git a/api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java b/api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java new file mode 100644 index 00000000000..78e9d92fc9b --- /dev/null +++ b/api/test/org/apache/cloudstack/api/command/test/AddVpnUserCmdTest.java @@ -0,0 +1,148 @@ +// 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 org.apache.cloudstack.api.command.test; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import org.apache.cloudstack.api.command.user.vpn.AddVpnUserCmd; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mockito; + +import org.apache.cloudstack.api.ServerApiException; +import com.cloud.network.VpnUser; +import com.cloud.network.vpn.RemoteAccessVpnService; +import com.cloud.user.Account; +import com.cloud.user.AccountService; + +public class AddVpnUserCmdTest extends TestCase { + + private AddVpnUserCmd addVpnUserCmd; + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() { + + addVpnUserCmd = new AddVpnUserCmd() { + + @Override + public Long getEntityId() { + return 2L; + } + + @Override + public long getEntityOwnerId() { + return 2L; + } + + @Override + public String getUserName() { + return "User Name"; + } + + @Override + public String getPassword() { + return "password"; + } + + }; + } + + /* + * @Test public void testExecuteVpnUserNotFound() { + * + * EntityManager entityManager = Mockito.mock(EntityManager.class); + * + * Mockito.when(entityManager.findById(VpnUser.class, + * Mockito.anyLong())).thenReturn(null); + * + * addVpnUserCmd._entityMgr = entityManager; try { addVpnUserCmd.execute(); + * } catch (Exception e) { } + * + * } + * + * + * @Test public void testExecuteVpnUserFound() { + * + * EntityManager entityManager = Mockito.mock(EntityManager.class); + * addVpnUserCmd._entityMgr = entityManager; + * + * VpnUser vpnUser = Mockito.mock(VpnUser.class); + * Mockito.when(entityManager.findById(VpnUser.class, + * Mockito.anyLong())).thenReturn(vpnUser); addVpnUserCmd.execute(); + * + * } + */ + + @Test + public void testCreateSuccess() { + + AccountService accountService = Mockito.mock(AccountService.class); + + Account account = Mockito.mock(Account.class); + Mockito.when(accountService.getAccount(Mockito.anyLong())).thenReturn( + account); + + addVpnUserCmd._accountService = accountService; + + RemoteAccessVpnService ravService = Mockito + .mock(RemoteAccessVpnService.class); + + VpnUser vpnUser = Mockito.mock(VpnUser.class); + Mockito.when( + ravService.addVpnUser(Mockito.anyLong(), Mockito.anyString(), + Mockito.anyString())).thenReturn(vpnUser); + + addVpnUserCmd._ravService = ravService; + + addVpnUserCmd.create(); + + } + + @Test + public void testCreateFailure() { + + AccountService accountService = Mockito.mock(AccountService.class); + Account account = Mockito.mock(Account.class); + Mockito.when(accountService.getAccount(Mockito.anyLong())).thenReturn( + account); + + addVpnUserCmd._accountService = accountService; + + RemoteAccessVpnService ravService = Mockito + .mock(RemoteAccessVpnService.class); + Mockito.when( + ravService.addVpnUser(Mockito.anyLong(), Mockito.anyString(), + Mockito.anyString())).thenReturn(null); + + addVpnUserCmd._ravService = ravService; + + try { + addVpnUserCmd.create(); + } catch (ServerApiException exception) { + Assert.assertEquals("Failed to add vpn user", + exception.getDescription()); + } + + } + +} diff --git a/awsapi/README.txt b/awsapi/README.txt deleted file mode 100644 index 99788bf81e1..00000000000 --- a/awsapi/README.txt +++ /dev/null @@ -1,75 +0,0 @@ -====================================================== -Apache Axis2 1.6.2 build (17-04-2012) - -http://axis.apache.org/axis2/java/core/ ------------------------------------------------------- - -___________________ -Building -=================== - -We use Maven 2 (http://maven.apache.org) to build, and you'll find a -pom.xml in each module, as well as at the top level. Use "mvn install" -(or "mvn clean install" to clean up first) to build. - -IMPORTANT: the *first* time you build a given version of Axis2, you will not -be able to do a regular "mvn install" from the top level - this is because -we have a couple of custom Maven plugins that (due to some dependency- -resolution issues in Maven) must be built and installed in your local -repository before a build will succeed. This means you need to do one -of the following: - - 1) Use ant (http://ant.apache.org) to build the first time. There is - a build.xml at the top level which automatically builds the plugins - first and then runs a regular "mvn install". - - 2) Manually "mvn install" both of the plugins in the following places: - - modules/tool/axis2-mar-maven-plugin - modules/tool/axis2-aar-maven-plugin - -___________________ -Documentation -=================== - -Documentation can be found in the 'docs' distribution of this release -and in the main site. - -___________________ -Deploying -=================== - -To deploy a new Web service in Axis2 the following three steps must -be performed: - 1) Create the Web service implementation class, supporting classes - and the services.xml file, - 2) Archive the class files into a jar with the services.xml file in - the META-INF directory - 3) Drop the jar file to the $AXIS2_HOME/WEB-INF/services directory - where $AXIS2_HOME represents the install directory of your Axis2 - runtime. (In the case of a servelet container this would be the - "axis2" directory inside "webapps".) - -To verify the deployment please go to http://:/axis2/ and -follow the "Services" Link. - -For more information please refer to the User's Guide. - -___________________ -Support -=================== - -Any problem with this release can be reported to Axis mailing list -or in the JIRA issue tracker. If you are sending an email to the mailing -list make sure to add the [Axis2] prefix to the subject. - -Mailing list subscription: - java-dev-subscribe@axis.apache.org - -Jira: - http://issues.apache.org/jira/browse/AXIS2 - - -Thank you for using Axis2! - -The Axis2 Team. diff --git a/awsapi/pom.xml b/awsapi/pom.xml index 10b9c9be5b5..3ab595211d4 100644 --- a/awsapi/pom.xml +++ b/awsapi/pom.xml @@ -47,6 +47,17 @@ axis2-webapp war ${cs.axis2.version} + + + xerces + xercesImpl + + + + + org.apache.ws.commons.axiom + axiom-api + ${cs.axiom.version} org.apache.ws.commons.axiom @@ -118,6 +129,10 @@ org.apache.xalan xalan + + org.opensaml + opensaml + @@ -134,6 +149,10 @@ org.apache.xalan xalan + + org.opensaml + opensaml + @@ -146,6 +165,10 @@ org.apache.xalan xalan + + org.opensaml + opensaml + @@ -158,6 +181,10 @@ org.apache.xalan xalan + + org.opensaml + opensaml + @@ -170,6 +197,10 @@ org.apache.xalan xalan + + org.opensaml + opensaml + @@ -235,13 +266,32 @@ mysql mysql-connector-java - 5.1.21 + ${cs.mysql.version} runtime - + + + org.antlr + antlr-runtime + 3.4 + + + dom4j + dom4j + 1.6.1 + + + javassist + javassist + 3.9.0.GA + install src + src @@ -251,58 +301,9 @@ ../utils/conf/ - + - - org.apache.maven.plugins - maven-dependency-plugin - 2.5.1 - - - copy-dependencies - install - - copy-dependencies - - - ../deps/awsapi-lib/rampart-lib - false - false - true - rampart-core,rampart-policy,rampart-trust,slf4j-jdk14,slf4j-api,wss4j,joda-time,xmltooling,openws,velocity,opensaml,xmlsec,bcprov-jdk16 - - - - copy-axis2-war - install - - copy-dependencies - - - ../deps/awsapi-lib/ - false - false - true - axis2-webapp - - - - copy-mars - install - - copy-dependencies - - - ../deps/awsapi-lib/modules - false - false - true - rampart,rahas - - - - org.mortbay.jetty maven-jetty-plugin @@ -321,7 +322,6 @@ + + + + + + + + + + + + + + + + - diff --git a/build/build-cloud.xml b/build/build-cloud.xml index 1b25fac8796..c31d00da220 100755 --- a/build/build-cloud.xml +++ b/build/build-cloud.xml @@ -527,8 +527,6 @@ - - diff --git a/build/developer.xml b/build/developer.xml index 3121813040c..fdda171aff6 100755 --- a/build/developer.xml +++ b/build/developer.xml @@ -404,6 +404,7 @@ + @@ -411,7 +412,7 @@ - + diff --git a/build/package.xml b/build/package.xml index 09ed939c6d7..3efdd7dda05 100755 --- a/build/package.xml +++ b/build/package.xml @@ -217,6 +217,10 @@ + + + + diff --git a/build/replace.properties b/build/replace.properties index 8cd0fa3c76c..c9a93c2831c 100644 --- a/build/replace.properties +++ b/build/replace.properties @@ -24,6 +24,6 @@ DBHOST=localhost AGENTLOGDIR=logs AGENTLOG=logs/agent.log MSMNTDIR=/mnt -COMPONENTS-SPEC=components-premium.xml +COMPONENTS-SPEC=components.xml AWSAPILOG=awsapi.log REMOTEHOST=localhost diff --git a/client/WEB-INF/classes/resources/messages.properties b/client/WEB-INF/classes/resources/messages.properties index 454974d4654..3dc01aa2008 100644 --- a/client/WEB-INF/classes/resources/messages.properties +++ b/client/WEB-INF/classes/resources/messages.properties @@ -17,12 +17,37 @@ #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=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 +label.quickview=Quickview +label.migrate.to.host=Migrate to host +label.migrate.to.storage=Migrate to storage +label.stop=Stop +label.reboot=Reboot +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) ************************************************************************************************ #modified labels (begin) ***************************************************************************************** +label.site.to.site.VPN=Site-to-site VPN message.zoneWizard.enable.local.storage=WARNING: If you enable local storage for this zone, you must do the following, depending on where you would like your system VMs to launch:

1. If system VMs need to be launched in primary storage, primary storage needs to be added to the zone after creation. You must also start the zone in a disabled state.

2. If system VMs need to be launched in local storage, system.vm.use.local.storage needs to be set to true before you enable the zone.


Would you like to continue? #modified labels (end) ******************************************************************************************* @@ -54,7 +79,6 @@ label.CIDR.of.destination.network=CIDR of destination network label.add.route=Add route label.add.static.route=Add static route label.remove.static.route=Remove static route -label.site.to.site.VPN=site-to-site VPN label.add.VPN.gateway=Add VPN Gateway message.add.VPN.gateway=Please confirm that you want to add a VPN Gateway label.VPN.gateway=VPN Gateway @@ -292,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 @@ -1117,6 +1139,9 @@ label.lang.chinese=Chinese (Simplified) label.lang.english=English label.lang.japanese=Japanese label.lang.spanish=Spanish +label.lang.russian=Russian +label.lang.french=French +label.lang.brportugese=Brazilian Portugese label.last.disconnected=Last Disconnected label.last.name=Last Name label.level=Level @@ -1512,3 +1537,10 @@ error.menu.select=Unable to perform action due to no items being selected. error.mgmt.server.inaccessible=The Management Server is unaccessible. Please try again later. error.session.expired=Your session has expired. error.unresolved.internet.name=Your internet name cannot be resolved. + +label.add.NiciraNvp.device=Add Nvp Controller +label.delete.NiciraNvp=Remove Nvp Controller +label.nicira.controller.address=Controller Address +label.nicira.transportzoneuuid=Transport Zone Uuid +label.nicira.l3gatewayserviceuuid=L3 Gateway Service Uuid + diff --git a/client/WEB-INF/classes/resources/messages_fr_FR.properties b/client/WEB-INF/classes/resources/messages_fr_FR.properties new file mode 100644 index 00000000000..4ba3c725892 --- /dev/null +++ b/client/WEB-INF/classes/resources/messages_fr_FR.properties @@ -0,0 +1,1512 @@ +# 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. + + +#new labels (begin) ********************************************************************************************** +# label.isolation.uri=Isolation URI +# label.broadcast.uri=Broadcast URI +#new labels (end) ************************************************************************************************ + + +#modified labels (begin) ***************************************************************************************** +# message.zoneWizard.enable.local.storage=WARNING\: If you enable local storage for this zone, you must do the following, depending on where you would like your system VMs to launch\:

1. If system VMs need to be launched in primary storage, primary storage needs to be added to the zone after creation. You must also start the zone in a disabled state.

2. If system VMs need to be launched in local storage, system.vm.use.local.storage needs to be set to true before you enable the zone.


Would you like to continue? +#modified labels (end) ******************************************************************************************* + +# label.configure.network.ACLs=Configure Network ACLs +# label.network.ACLs=Network ACLs +# label.add.network.ACL=Add network ACL +# label.private.Gateway=Private Gateway +# label.VPC.router.details=VPC router details +# label.VMs.in.tier=VMs in tier +# label.local.storage.enabled=Local storage enabled +# label.tier.details=Tier details +# label.edit.tags=Edit tags +label.action.enable.physical.network=Activer le réseau physique +label.action.disable.physical.network=Désactiver le réseau physique +message.action.enable.physical.network=Confirmer l\'activation de ce réseau physique. +message.action.disable.physical.network=Confirmer la désactivation de ce réseau physique. + +# label.select.tier=Select Tier +# label.add.ACL=Add ACL +# label.remove.ACL=Remove ACL +# label.tier=Tier +# label.network.ACL=Network ACL +# label.network.ACL.total=Network ACL Total +# label.add.new.gateway=Add new gateway +# message.add.new.gateway.to.vpc=Please specify the information to add a new gateway to this VPC. +# label.delete.gateway=delete gateway +# message.delete.gateway=Please confirm you want to delete the gateway +# label.CIDR.of.destination.network=CIDR of destination network +# label.add.route=Add route +# label.add.static.route=Add static route +# label.remove.static.route=Remove static route +# label.site.to.site.VPN=site-to-site VPN +# label.add.VPN.gateway=Add VPN Gateway +# message.add.VPN.gateway=Please confirm that you want to add a VPN Gateway +# label.VPN.gateway=VPN Gateway +# label.delete.VPN.gateway=delete VPN Gateway +# message.delete.VPN.gateway=Please confirm that you want to delete this VPN Gateway +# label.VPN.connection=VPN Connection +# label.IPsec.preshared.key=IPsec Preshared-Key +# label.IKE.policy=IKE policy +# label.ESP.policy=ESP policy +# label.create.VPN.connection=Create VPN Connection +# label.VPN.customer.gateway=VPN Customer Gateway +# label.CIDR.list=CIDR list +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.reset.VPN.connection=Reset VPN connection +# message.reset.VPN.connection=Please confirm that you want to reset VPN connection +# label.delete.VPN.connection=delete VPN connection +# message.delete.VPN.connection=Please confirm that you want to delete VPN connection +# label.add.new.tier=Add new tier +# label.add.VM.to.tier=Add VM to tier +# label.remove.tier=Remove tier + +# label.local.storage.enabled=Local storage enabled +# label.associated.network=Associated Network +# label.add.port.forwarding.rule=Add port forwarding rule +# label.dns=DNS + +# label.vpc=VPC +# label.vpc.id=VPC ID +# label.tier=Tier +# label.add.vpc=Add VPC +# label.super.cidr.for.guest.networks=Super CIDR for Guest Networks +# label.DNS.domain.for.guest.networks=DNS domain for Guest Networks +# label.configure.vpc=Configure VPC +# label.edit.vpc=Edit VPC +# label.restart.vpc=restart VPC +# message.restart.vpc=Please confirm that you want to restart the VPC +# label.remove.vpc=remove VPC +# message.remove.vpc=Please confirm that you want to remove the VPC +# label.vpn.customer.gateway=VPN Customer Gateway +# label.add.vpn.customer.gateway=Add VPN Customer Gateway +# label.IKE.encryption=IKE Encryption +# label.IKE.hash=IKE Hash +# label.IKE.DH=IKE DH +# label.ESP.encryption=ESP Encryption +# label.ESP.hash=ESP Hash +# label.perfect.forward.secrecy=Perfect Forward Secrecy +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.delete.VPN.customer.gateway=delete VPN Customer Gateway +# message.delete.VPN.customer.gateway=Please confirm that you want to delete this VPN Customer Gateway + +label.network.domain.text=Texte du domaine réseau +label.memory.mb=Mémoire +label.cpu.mhz=CPU (en MHz) + +message.action.remove.host=Supprimer le dernier/seul hôte dans le cluster et le réinstaller va supprimer l\'environnement/la base de données sur l\'hôte et rendre les VMs invitées inutilisables. + +message.action.reboot.router=Confirmez que vous souhaitez redémarrer ce routeur. +message.action.stop.router=Confirmez que vous souhaitez arrêter ce routeur. +message.restart.network=Confirmer le redémarrage du réseau + + +label.ipaddress=Adresse IP +label.vcdcname=Nom du DC vCenter +label.vcipaddress=Adresse IP vCenter +label.vsmctrlvlanid=VLAN ID Controle +label.vsmpktvlanid=VLAN ID Paquet +label.vsmstoragevlanid=VLAN ID Stockage +label.nexusVswitch=Nexus Vswitch +label.action.delete.nexusVswitch=Supprimer le NexusVswitch +label.action.enable.nexusVswitch=Activer le NexusVswitch +label.action.disable.nexusVswitch=Désactiver le NexusVswitch +label.action.list.nexusVswitch=Lister les NexusVswitch +message.action.delete.nexusVswitch=Confirmer la suppression de ce NexusVswitch. +message.action.enable.nexusVswitch=Confirmer l\'activation de ce NexusVswitch. +message.action.disable.nexusVswitch=Confirmer la désactivation de ce NexusVswitch. +message.specify.url=Renseigner l\'URL +label.select.instance.to.attach.volume.to=Sélectionner l\'instance à laquelle rattacher ce volume +label.upload=Charger +label.upload.volume=Charger un volume +label.virtual.routers=Routeurs virtuels +label.primary.storage.count=Groupes de stockage primaire +label.secondary.storage.count=Groupes de stokage secondaire +label.number.of.system.vms=Nombre de VM système +label.number.of.virtual.routers=Nombre de routeurs virtuels +label.action.register.iso=Enregistrer ISO +label.isolation.method=Méthode de séparation +label.action.register.template=Enregister image +label.checksum=Checksum MD5 +label.vpn=VPN +label.vlan=VLAN + + +label.management.ips=Adresses IP de management +label.devices=Machines +label.rules=Règles +label.traffic.label=Label trafic +label.vm.state=Etat VM +# message.setup.physical.network.during.zone.creation.basic=When adding a basic zone, you can set up one physical network, which corresponds to a NIC on the hypervisor. The network carries several types of traffic.

You may also drag and drop other traffic types onto the physical network. +label.domain.router=Routeur du domaine +label.console.proxy=Console proxy +label.secondary.storage.vm=VM stockage secondaire +label.add.netScaler.device=Ajouter un Netscaler +label.add.F5.device=Ajouter un F5 +label.add.SRX.device=Ajouter un SRX +label.account.and.security.group=Compte, groupe de sécurité +label.fetch.latest=Raffraichir +label.system.offering=Offre système +message.validate.instance.name=le nom de l\'instance de l\'instance ne peut dépasser 63 caractères. Seuls les lettres de a à z, les chiffres de 0 à 9 et les tirets sont acceptés. Le nom doit commencer par une lettre et se terminer par une lettre ou un chiffre. + + +label.isolated.networks=Réseaux isolés +label.latest.events=Derniers évenements +state.Enabled=Actifs +label.system.wide.capacity=Capacité globale +label.network.service.providers=Provider de réseau +message.launch.zone=La zone est prête à démarrer; Continuer. +error.unable.to.reach.management.server=Impossible de joindre le serveur de management +label.internal.name=Nom interne +message.configure.all.traffic.types=Vous avez de multiples réseaux physiques; veuillez configurer les labels pour chaque type de trafic en cliquant sur le bouton Modifier. +message.edit.traffic.type=Spécifier le label de trafic associé avec ce type de trafic +label.edit.traffic.type=Modifer le type de trafic +label.label=Label +label.max.networks=Réseaux Max. +error.invalid.username.password=Utilisateur ou mot de passe invalide +message.enabling.security.group.provider=Activation du groupe de sécurité pour le provider +message.adding.Netscaler.provider=Ajouter un Netscaler provider +message.creating.guest.network=Création du réseau pour les instances +label.action.delete.physical.network=Supprimer le réseau physique +message.action.delete.physical.network=Confirmer la suppression du réseau physique +# message.installWizard.copy.whatIsAHost=A host is a single computer. Hosts provide the computing resources that run the guest virtual machines. Each host has hypervisor software installed on it to manage the guest VMs (except for bare metal hosts, which are a special case discussed in the Advanced Installation Guide). For example, a Linux KVM-enabled server, a Citrix XenServer server, and an ESXi server are hosts. In a Basic Installation, we use a single host running XenServer or KVM.

The host is the smallest organizational unit within a CloudStack&\#8482; deployment. Hosts are contained within clusters, clusters are contained within pods, and pods are contained within zones. + + +label.add.compute.offering=Ajouter une offre de calcul +label.compute.offering=Offre de calcul +label.compute.offerings=Offres de calcul +label.select.offering=Choisir une offre +label.menu.infrastructure=Infrastructure +label.sticky.tablesize=Taille du tableau +label.sticky.expire=Expiration +label.sticky.cookie-name=Nom du cookie +label.sticky.mode=Mode +label.sticky.length=Longueur +label.sticky.holdtime=Temps de pause +label.sticky.request-learn=Apprendre la requête +label.sticky.prefix=Préfixe +label.sticky.nocache=Pas de cache +label.sticky.indirect=Indirect +label.sticky.postonly=Après seulement +label.sticky.domain=Domaine +state.Allocating=Allocation en cours +state.Migrating=Migration en cours +error.please.specify.physical.network.tags=L\'offre réseau ne sera pas disponible tant que des label n\'auront pas été renseigner pour ce réseau physique. + + +state.Stopping=Arrêt en cours +message.add.load.balancer.under.ip=La règle de load balancer a été ajoutée sous l\'adresse IP \: +message.select.instance=Sélectionner une instance. +label.select=Selectionner +label.select.vm.for.static.nat=Sélectionner une VM pour le NAT statique +label.select.instance=Sélectionner une instance. +label.nat.port.range=Plage de port NAT +label.static.nat.vm.details=NAT statique, détails par VM +label.edit.lb.rule=Modifier la règle LB +message.migrate.instance.to.host=Merci de confirmer la migration de l\'instance vers un autre serveur +label.migrate.instance.to.host=Migration de l\'instance sur un autre serveur +message.migrate.instance.to.ps=Merci de confirmer la migration de l\'instance vers un autre stockage primaire +label.migrate.instance.to.ps=Migration de l\'instance sur un autre stockage primaire +label.corrections.saved=Modifications enregistrées +# message.installWizard.copy.whatIsSecondaryStorage=Secondary storage is associated with a zone, and it stores the following\:
  • Templates - OS images that can be used to boot VMs and can include additional configuration information, such as installed applications
  • ISO images - OS images that can be bootable or non-bootable
  • Disk volume snapshots - saved copies of VM data which can be used for data recovery or to create new templates
+# message.installWizard.copy.whatIsPrimaryStorage=A CloudStack&\#8482; cloud infrastructure makes use of two types of storage\: primary storage and secondary storage. Both of these can be iSCSI or NFS servers, or localdisk.

Primary storage is associated with a cluster, and it stores the disk volumes of each guest VM for all the VMs running on hosts in that cluster. The primary storage server is typically located close to the hosts. +# message.installWizard.copy.whatIsACluster=A cluster provides a way to group hosts. The hosts in a cluster all have identical hardware, run the same hypervisor, are on the same subnet, and access the same shared storage. Virtual machine instances (VMs) can be live-migrated from one host to another within the same cluster, without interrupting service to the user. A cluster is the third-largest organizational unit within a CloudStack&\#8482; deployment. Clusters are contained within pods, and pods are contained within zones.

CloudStack&\#8482; allows multiple clusters in a cloud deployment, but for a Basic Installation, we only need one cluster. +# message.installWizard.copy.whatIsAPod=A pod often represents a single rack. Hosts in the same pod are in the same subnet.

A pod is the second-largest organizational unit within a CloudStack&\#8482; deployment. Pods are contained within zones. Each zone can contain one or more pods; in the Basic Installation, you will have just one pod in your zone. +# message.installWizard.copy.whatIsAZone=A zone is the largest organizational unit within a CloudStack&\#8482; deployment. A zone typically corresponds to a single datacenter, although it is permissible to have multiple zones in a datacenter. The benefit of organizing infrastructure into zones is to provide physical isolation and redundancy. For example, each zone can have its own power supply and network uplink, and the zones can be widely separated geographically (though this is not required). +# message.installWizard.copy.whatIsCloudStack=CloudStack&\#8482 is a software platform that pools computing resources to build public, private, and hybrid Infrastructure as a Service (IaaS) clouds. CloudStack&\#8482 manages the network, storage, and compute nodes that make up a cloud infrastructure. Use CloudStack&\#8482 to deploy, manage, and configure cloud computing environments.

Extending beyond individual virtual machine images running on commodity hardware, CloudStack&\#8482 provides a turnkey cloud infrastructure software stack for delivering virtual datacenters as a service - delivering all of the essential components to build, deploy, and manage multi-tier and multi-tenant cloud applications. Both open-source and Premium versions are available, with the open-source version offering nearly identical features. +message.installWizard.tooltip.addSecondaryStorage.path=Le chemin exporté, situé sur le serveur spécifié précédement +message.installWizard.tooltip.addSecondaryStorage.nfsServer=Adresse IP du server NFS supportant le stockage secondaire +# message.installWizard.tooltip.addPrimaryStorage.path=(for NFS) In NFS this is the exported path from the server. Path (for SharedMountPoint). With KVM this is the path on each host that is where this primary storage is mounted. For example, "/mnt/primary". +message.installWizard.tooltip.addPrimaryStorage.server=(pour NFS, iSCSI ou PreSetup) Adresse IP ou nom DNS du stockage +message.installWizard.tooltip.addPrimaryStorage.name=Nom pour ce stockage +message.installWizard.tooltip.addHost.password=Le mot de passe pour l\'utilisateur indiqué précédement (issu de l\'installation XenServer). +message.installWizard.tooltip.addHost.username=Habituellement root. +message.installWizard.tooltip.addHost.hostname=Le nom DNS ou adresse IP du serveur. +message.installWizard.tooltip.addCluster.name=Un nom pour le cluster. Ce choix est libre et n\'est pas utilisé par CloudStack. +# message.installWizard.tooltip.addPod.reservedSystemEndIp=This is the IP range in the private network that the CloudStack uses to manage Secondary Storage VMs and Console Proxy VMs. These IP addresses are taken from the same subnet as computing servers. +# message.installWizard.tooltip.addPod.reservedSystemStartIp=This is the IP range in the private network that the CloudStack uses to manage Secondary Storage VMs and Console Proxy VMs. These IP addresses are taken from the same subnet as computing servers. +message.installWizard.tooltip.addPod.reservedSystemNetmask=Le masque réseau que les instances utiliseront sur le réseau +message.installWizard.tooltip.addPod.reservedSystemGateway=Passerelle pour les serveurs dans ce pod +message.installWizard.tooltip.addPod.name=Nom pour le pod +# message.installWizard.tooltip.configureGuestTraffic.guestEndIp=The range of IP addresses that will be available for allocation to guests in this zone. If one NIC is used, these IPs should be in the same CIDR as the pod CIDR. +# message.installWizard.tooltip.configureGuestTraffic.guestStartIp=The range of IP addresses that will be available for allocation to guests in this zone. If one NIC is used, these IPs should be in the same CIDR as the pod CIDR. +message.installWizard.tooltip.configureGuestTraffic.guestNetmask=Le masque réseau que les instances devrait utiliser sur le réseau +message.installWizard.tooltip.configureGuestTraffic.guestGateway=La passerelle que les instances clientes doivent utiliser +message.installWizard.tooltip.configureGuestTraffic.description=Desctiption pour ce réseau +message.installWizard.tooltip.configureGuestTraffic.name=Nom pour ce réseau +# message.installWizard.tooltip.addZone.internaldns2=These are DNS servers for use by system VMs in the zone. These DNS servers will be accessed via the private network interface of the System VMs. The private IP address you provide for the pods must have a route to the DNS server named here. +# message.installWizard.tooltip.addZone.internaldns1=These are DNS servers for use by system VMs in the zone. These DNS servers will be accessed via the private network interface of the System VMs. The private IP address you provide for the pods must have a route to the DNS server named here. +# message.installWizard.tooltip.addZone.dns2=These are DNS servers for use by guest VMs in the zone. These DNS servers will be accessed via the public network you will add later. The public IP addresses for the zone must have a route to the DNS server named here. +message.installWizard.tooltip.addZone.name=Nom pour la zone +# message.installWizard.tooltip.addZone.dns1=These are DNS servers for use by guest VMs in the zone. These DNS servers will be accessed via the public network you will add later. The public IP addresses for the zone must have a route to the DNS server named here. +message.setup.successful=Installation Cloud réussie \! +label.may.continue=Vous pouvez continuer. +error.installWizard.message=Une erreur s\'est produite; vous pouvez retourner en arrière et corriger les erreurs +message.installWizard.now.building=Construction de votre Cloud en cours +message.installWizard.click.retry=Appuyer sur le bouton pour essayer à nouveau le démarrage. +label.launch=Démarrer +label.installWizard.click.launch=Appuyer sur le bouton démarrer. +label.congratulations=Félicitations \! +label.installWizard.addSecondaryStorageIntro.subtitle=Qu\'est ce que le stockage secondaire ? +label.installWizard.addSecondaryStorageIntro.title=Ajoutons du stockage secondaire +label.installWizard.addPrimaryStorageIntro.subtitle=Qu\'est ce que le stockage primaire ? +label.installWizard.addPrimaryStorageIntro.title=Ajoutons du stockage primaire +label.installWizard.addHostIntro.subtitle=Qu\'est ce qu\'un serveur ? +label.installWizard.addHostIntro.title=Ajoutons un serveur +label.installWizard.addClusterIntro.subtitle=Qu\'est ce qu\'un cluster ? +label.installWizard.addClusterIntro.title=Ajoutons un cluster +label.installWizard.addPodIntro.subtitle=Qu\'est ce qu\'un pod ? +label.installWizard.addPodIntro.title=Ajoutons un pod +label.installWizard.addZone.title=Ajouter une zone +label.installWizard.addZoneIntro.subtitle=Qu\'est ce qu\'une zone ? +label.installWizard.addZoneIntro.title=Ajoutons une zone +error.password.not.match=Les mot de passe ne correspondent pas +label.confirm.password=Confirmer le mot de passe +message.change.password=Merci de modifier votre mot de passe. +label.save.and.continue=Enregistrer et continuer +label.skip.guide=J\'ai déjà utilisé CloudStack avant, passer ce tutorial +label.continue.basic.install=Continuer avec l\'installation basique +label.introduction.to.cloudstack=Introduction à CloudStack +label.what.is.cloudstack=Qu\'est ce que CloudStack ? +label.hints=Astuces +label.installWizard.subtitle=Ce tutorial vous aidera à configurer votre installation CloudStack +label.continue=Continuer +label.installWizard.title=Bonjour et bienvenue dans CloudStack +label.agree=Accepter +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 +label.networking.and.security=Réseau et sécurité +label.bandwidth=Bande passante +label.virtual.machines=Machines virtuelles +label.compute.and.storage=Processeur et Stockage +label.task.completed=Tâche terminée +label.update.project.resources=Mettre à jour les ressources du projet +label.remove.project.account=Supprimer le compte projet +label.item.listing=Liste des éléments +message.select.item=Merci de sélectionner un élément. +label.removing=Suppression +label.invite=Inviter +label.add.by=Ajouté par +label.max.vms=Max VMs utilisateur +label.max.public.ips=Max IP publiques +label.max.volumes=Max volumes +label.max.snapshots=Max snapshots +label.max.templates=Max images +# label.max.vpcs=Max. VPCs +label.project.dashboard=Tableau de bord projet +label.remind.later=Rappeler moi plus tard +label.invited.accounts=Comptes invités +label.invite.to=Inviter sur +label.add.accounts.to=Ajouter des comptes sur +label.add.accounts=Ajouter des comptes +label.project.name=Nom du projet +label.create.project=Créer un projet +label.networks=Réseaux +label.launch.vm=Démarrer VM +label.new.vm=Nouvelle VM +label.previous=Retour +label.add.to.group=Ajouter au groupe +message.vm.review.launch=Merci de vérifier les informations suivantes et de confirmer que votre instance virtuelle est correcte avant de la démarrer. +message.select.security.groups=Merci de sélectionner un(des) groupe(s) de sécurité pour la nouvelle VM +label.new=Nouveau +message.please.select.networks=Selectionner les réseaux pour votre instance. +message.please.proceed=Continuer vers la prochaine étape. +message.zone.no.network.selection=La zone sélectionnée ne propose pas le réseau choisi +label.no.thanks=Non merci +label.my.templates=Mes images +message.select.template=Sélectionner une image pour votre nouvelle instance virtuelle. +message.select.iso=Sélectionner une ISO pour votre nouvelle instance virtuelle. +message.template.desc=Image OS pouvant être utilisée pour démarrer une VM +message.iso.desc=Image ISO contenant des données ou des binaires de démarrage +label.select.iso.or.template=Sélectionner une ISO ou une image +message.select.a.zone=Une zone corespond en général à un seul datacenter. Des zones multiples peuvent permettre de rendre votre cloud plus fiable en apportant une isolation physique et de la redondance. +label.select.a.zone=Sélectionner une zone +label.review=Revoir +label.select.a.template=Sélectionner une image +label.setup=Configuration +state.Allocated=Alloué +changed.item.properties=Propriétés de l\'élément modifiées +label.apply=Appliquer +label.default=Par défaut +label.viewing=Consultation en cours +label.move.to.top=Placer au dessus +label.move.up.row=Monter d\'un cran +label.move.down.row=Descendre d\'un cran +# label.move.to.bottom=Move to bottom +label.drag.new.position=Déplacer sur une autre position +label.order=Ordre +label.no.data=Aucune donnée +label.change.value=Modifier la valeur +label.clear.list=Purger la liste +label.full.path=Chemin complet +message.add.domain=Spécifier le sous domaine que vous souhaitez créer sous ce domaine +message.delete.user=Confirmer la suppression de l\'utilisateur. +message.enable.user=Confirmer l\'activation de cet utilisateur. +message.disable.user=Confirmer la désactivation de l\'utilisateur. +message.generate.keys=Confirmer la génération de nouvelles clefs pour cet utilisateur. +message.update.resource.count=Confirmer la mise à jour des ressources pour ce compte. +message.edit.account=Modifier ("-1" signifie pas de limite de ressources) +label.total.of.vm=Total VM +label.total.of.ip=Total adresses IP +state.enabled=Actif +message.action.download.iso=Confirmer le téléchargement de l\'ISO +message.action.download.template=Confirmer le téléchargement de l\'image +label.destination.zone=Zone destination +label.keyboard.type=Type de clavier +label.nic.adapter.type=Type de carte réseau +label.root.disk.controller=Controlleur disque principal +label.community=Communauté +label.remove.egress.rule=Supprimer la règle sortante +label.add.egress.rule=Ajouter la règle sortante +label.egress.rule=Règle sortante +label.remove.ingress.rule=Supprimer la règle entrante +label.delete.vpn.user=Supprimer l\'utilisateur VPN +label.add.vpn.user=Ajouter un utilisateur VPN +label.remove.pf=Supprimer la règle de transfert de port +label.remove.vm.from.lb=Supprimer la VM de la règle de répartition de charge +label.add.vms.to.lb=Ajouter une/des VM(s) à la règle de répartition de charge +label.add.vm=Ajouter VM +label.remove.static.nat.rule=Supprimer le NAT statique +label.remove.rule=Supprimer la règle +label.add.static.nat.rule=Ajouter une règle de NAT statique +label.add.rule=Ajouter règle +label.configuration=Configuration +message.disable.vpn=Etes vous sûr de vouloir désactiver le VPN ? +label.disable.vpn=Désactiver le VPN +message.enable.vpn=Confirmer l\'activation de l\'accès VPN pour cette adresse IP. +label.enable.vpn=Activer VPN +message.acquire.new.ip=Confirmer l\'ajout d\'une nouvelle adresse IP pour ce réseau. +label.elastic=Elastique +label.my.network=Mon réseau +label.add.vms=Ajouter VMs +label.configure=Configurer +label.stickiness=Fidélité +label.source=Origine +label.least.connections=Le moins de connexions +label.round.robin=Aléatoire +label.restart.required=Rédémarrage nécessaire +label.clean.up=Nettoyage +label.restart.network=Redémarrage du réseau +label.edit.network.details=Modifier les paramètres réseau +label.add.guest.network=Ajout d\'un réseau pour les VM +label.guest.networks=Réseau pour les VM +message.ip.address.changed=Vos adresses IP ont peut être changées; Voulez vous raffraichir la liste ? Dans ce cas, le panneau de détail se fermera. +state.BackingUp=Sauvegarde en cours +state.BackedUp=Sauvegardé +label.done=Terminé +label.vm.name=Nom de la VM +message.migrate.volume=Confirmer la migration du volume vers un autre stockage primaire. +label.migrate.volume=Migration du volume vers un autre stockage primaire +message.create.template=Voulez vous créer l\'image ? +label.create.template=Création d\'image +message.download.volume.confirm=Confirmer le téléchargement du volume +message.detach.disk=Voulez vous détacher ce disque ? +state.ready=Prêt +state.Ready=Prêt +label.vm.display.name=Nom d\'affichage de la VM +label.select-view=Sélectionner la vue +label.local.storage=Stockage local +label.direct.ips=IP directes +label.view.all=Voir tout +label.zone.details=Détails de la zone +message.alert.state.detected=Etat d\'alerte détecté +state.Starting=Démarrage en cours +state.Expunging=Purge en cours +state.Creating=Création en cours +message.decline.invitation=Voulez vous refuser cette invitation au projet ? +label.decline.invitation=Refuser l\'invitation +message.confirm.join.project=Confirmer l\'invitation au projet +message.join.project=Vous avez rejoint un projet. Sélectionnez la vue Projet pour le voir. +label.accept.project.invitation=Accepter l\'invitation au projet +label.token=Jeton unique +label.project.id=ID projet +message.enter.token=Entrer le jeton unique reçu dans le message d\'invitation. +label.enter.token=Entrez le jeton unique +state.Accepted=Accepté +state.Pending=En attente +state.Completed=Terminé +state.Declined=Refusé +label.project=Projet +label.invitations=Invitations +label.delete.project=Supprimer projet +message.delete.project=Confirmer la suppression du projet +message.activate.project=Confirmer l\'activation de ce projet +label.activate.project=Activer projet +label.suspend.project=Suspendre projet +message.suspend.project=Confirmer la suspension de ce projet +state.Suspended=Suspendu +label.edit.project.details=Modifier les détails du projet +label.new.project=Nouveau projet +state.Active=Actif +state.Disabled=Désactivé +label.projects=Projets +label.make.project.owner=Devenir propriétaire du projet +label.remove.project.account=Supprimer le compte projet +message.project.invite.sent=Invitation envoyée; les utilisateurs seront ajoutés après acceptation de l\'invitation +label.add.account.to.project=Ajouter un compte au projet +label.revoke.project.invite=Revoquer l\'invitation +label.project.invite=Inviter sur le projet +label.select.project=Sélectionner un projet +message.no.projects=Vous n\'avez pas de projet.
Vous pouvez en créer un depuis la section projets. +message.no.projects.adminOnly=Vous n\'avez pas de projet.
Contacter votre administrateur pour ajouter un projet. +message.pending.projects.1=Vous avez des invitations projet en attente \: +message.pending.projects.2=Pour les visualiser, aller dans la section projets, puis sélectionner invitation dans la liste déroulante. +message.instanceWizard.noTemplates=Vous n\'avez pas de image disponible; Ajouter une image compatible puis relancer l\'assistant de création d\'instance. +label.view=Voir +instances.actions.reboot.label=Redémarrer l\'instance +label.filterBy=Filtrer par +label.ok=OK +notification.reboot.instance=Redémarrer l\'instance +notification.start.instance=Démarrer l\'instance +notification.stop.instance=Stopper l\'instance +label.display.name=Nom d\'affichage +label.zone.name=Nom de la zone +ui.listView.filters.all=Tous +ui.listView.filters.mine=Mon +state.Running=Démarrée +state.Stopped=Arrétée +state.Destroyed=Supprimée +state.Error=Erreur +message.reset.password.warning.notPasswordEnabled=L\'image de cette instance a été créée sans la gestion de mot de passe +message.reset.password.warning.notStopped=Votre instance doit être arretée avant de changer son mot de passe +label.notifications=Messages +label.default.view=Vue par défaut +label.project.view=Vue projet + +message.add.system.service.offering=Ajouter les informations suivantes pour créer une nouvelle offre système. +message.action.delete.system.service.offering=Confirmer la suppression de l\'offre système. +label.action.delete.system.service.offering=Supprimer l\'offre système +label.hypervisor.capabilities=Fonctions hyperviseur +label.hypervisor.version=Version hyperviseur +label.max.guest.limit=Nombre maximum d\'instances +label.add.network.offering=Ajouter une offre réseau +label.supported.services=Services supportés +label.service.capabilities=Fonctions disponibles +label.guest.type=Type d\'instance +label.specify.IP.ranges=Plages IP +label.conserve.mode=Conserver le mode +label.created.by.system=Créé par le system +label.menu.system.service.offerings=Offres système +label.add.system.service.offering=Ajouter une offre de service système +label.redundant.router.capability=Router redondant +label.supported.source.NAT.type=Type de NAT supporté +label.elastic.LB=Répartition de charge extensible +label.LB.isolation=Répartition de charge isolée +label.elastic.IP=IP extensible +label.network.label.display.for.blank.value=Utiliser la passerelle par défaut +label.xen.traffic.label=Label pour le trafic Xenserver +label.kvm.traffic.label=Label pour le trafic KVM +label.vmware.traffic.label=Label pour le trafic VMware +label.start.IP=Démarrer l\'IP +label.end.IP=Résilier l\'IP +label.remove.ip.range=Supprimer la plage IP +label.ip.ranges=Plages IP +label.start.vlan=VLAN de départ +label.end.vlan=VLAN de fin +label.broadcast.domain.range=Plage de brodcast domaine +label.compute=Processeur +message.add.guest.network=Confirmer l\'ajout du réseau +label.subdomain.access=Accès au sous domaine +label.guest.start.ip=Adresse IP de début pour les instances +label.guest.end.ip=Adresse IP de fin pour les instances +label.virtual.router=Routeur Virtuel +label.physical.network.ID=ID du réseau physique +label.destination.physical.network.id=ID du réseau physique de destination +label.dhcp=DHCP +label.destroy.router=Supprimer le routeur +message.confirm.destroy.router=Confirmer la suppression du routeur +label.change.service.offering=Modifier l\'offre de service +label.view.console=Voir la console +label.redundant.state=Etat redondant +label.enable.provider=Activer le provider +message.confirm.enable.provider=Confirmer l\'activation de ce provider +label.disable.provider=Désactiver ce provider +message.confirm.disable.provider=Confirmer la désactivation de ce provider +label.shutdown.provider=Eteindre le provider +message.confirm.shutdown.provider=Confirmer l\'extinction de ce provider +label.netScaler=Netscaler +label.add.new.NetScaler=Ajouter Netscaler +label.capacity=Capacité +label.dedicated=Dédié +label.f5=F5 +label.add.new.F5=Ajouter un F5 +label.srx=SRX +label.providers=Fournisseurs +label.add.new.SRX=Ajouter un SRX +label.timeout=Expiration +label.public.network=Réseau public +label.private.network=Réseau privé +label.enable.swift=Activer Swift +confirm.enable.swift=Remplir les informations suivantes pour activer Swift +message.after.enable.swift=Swift configuré. Remarque \: une fois quitter cette page, il ne sera plus possible de reconfiguré Swift une nouvelle fois. +label.key=Clef +label.delete.NetScaler=Supprimer Netscaler +message.confirm.delete.NetScaler=Confirmer la suppression du Netscaler +label.delete.F5=Supprimer F5 +message.confirm.delete.F5=Confirmer la suppression du F5 +label.delete.SRX=Supprimer SRX +message.confirm.delete.SRX=Confirmer la suppression du SRX +label.pods=Pods +label.pod.name=Nom du pod +label.reserved.system.gateway=Gateway système réservée +label.reserved.system.netmask=Masque réseau système réservé +label.start.reserved.system.IP=Adresse IP de démarrage réservée pour le système +label.end.reserved.system.IP=Adresse IP de fin réservée pour le système +label.clusters=Clusters +label.cluster.name=Nom du cluster +label.host.MAC=MAC serveur +label.agent.username=Compte de l\'agent +label.agent.password=Mot de passe de l\'agent +message.confirm.action.force.reconnect=Confirmer que reconnection forcée de ce serveur. +label.resource.state=Etat des ressources +label.LUN.number=N° LUN +message.confirm.remove.IP.range=Confirmer la suppression de cette plage d\'adresses IP +message.tooltip.zone.name=Nom pour la zone. +message.tooltip.dns.1=Nom d\'un serveur DNS utilisé par les VM de la zone. Les adresses IP publiques de cette zones doivent avoir une route vers ce serveur. +message.tooltip.dns.2=Nom d\'un serveur DNS secondaire utilisé par les VM de la zone. Les adresses IP publiques de cette zones doivent avoir une route vers ce serveur. +message.tooltip.internal.dns.1=Nom d\'un serveur DNS que CloudStack peut utiliser pour les VM système dans cette zone. Les adresses IP privées des pods doivent avoir une route vers ce serveur. +message.tooltip.internal.dns.2=Nom d\'un serveur DNS que CloudStack peut utiliser pour les VM système dans cette zone. Les adresses IP privées des pods doivent avoir une route vers ce serveur. +message.tooltip.network.domain=Suffixe DNS pour les noms de domaine personnalisés accèdé par les intances. +message.tooltip.pod.name=Nom pour le pod. +message.tooltip.reserved.system.gateway=La passerelle pour les serveur du pod. +message.tooltip.reserved.system.netmask=Le préfixe réseau utilisé par le sous-réseau du pod. Au format CIDR. +message.creating.zone=Création de la zone +message.creating.physical.networks=Création des réseaux physiques +message.configuring.physical.networks=Configuration des réseaux physiques +message.adding.Netscaler.device=Ajout du Netscaler +message.creating.pod=Création d\'un pod +message.configuring.public.traffic=Configuration du réseau public +message.configuring.storage.traffic=Configuration du réseau de stockage +message.configuring.guest.traffic=Configuration du réseau VM +message.creating.cluster=Création du cluster +message.adding.host=Ajout du serveur +message.creating.primary.storage=Création du stockage primaire +message.creating.secondary.storage=Création du stockage secondaire +message.Zone.creation.complete=Création de la zone terminée +message.enabling.zone=Activation de la zone +error.something.went.wrong.please.correct.the.following=Erreur; corriger le point suivant +error.could.not.enable.zone=Impossible d\'activer la zone +message.zone.creation.complete.would.you.like.to.enable.this.zone=Création de la zone terminée. Voulez vous l\'activer ? +message.please.add.at.lease.one.traffic.range=Ajouter au moins une plage réseau +message.you.must.have.at.least.one.physical.network=Vous devez avoir au moins un réseau physique +message.please.select.a.different.public.and.management.network.before.removing=Sélectionner un réseau publique et management différent avant de supprimer + +label.zone.type=Type de zone +label.setup.zone=Configurer la zone +label.setup.network=Configurer le réseau +label.add.resources=Ajouter des resssources +label.launch=Démarrer +label.set.up.zone.type=configurer le type de zone +message.please.select.a.configuration.for.your.zone=Sélectionner une configuration pour la zone. +# message.desc.basic.zone=Provide a single network where each VM instance is assigned an IP directly from the network. Guest isolation can be provided through layer-3 means such as security groups (IP address source filtering). +label.basic=Basic +# message.desc.advanced.zone=For more sophisticated network topologies. This network model provides the most flexibility in defining guest networks and providing custom network offerings such as firewall, VPN, or load balancer support. +label.advanced=Avancé +# message.desc.zone=A zone is the largest organizational unit in CloudStack, and it typically corresponds to a single datacenter. Zones provide physical isolation and redundancy. A zone consists of one or more pods (each of which contains hosts and primary storage servers) and a secondary storage server which is shared by all pods in the zone. +label.physical.network=Réseau physique +label.public.traffic=Trafic public +label.guest.traffic=Trafic invité +label.storage.traffic=Trafic stockage +# message.setup.physical.network.during.zone.creation=When adding an advanced zone, you need to set up one or more physical networks. Each network corresponds to a NIC on the hypervisor. Each physical network can carry one or more types of traffic, with certain restrictions on how they may be combined.

Drag and drop one or more traffic types onto each physical network. +label.add.physical.network=Ajouter un réseau physique +label.traffic.types=Type de trafic +label.management=Management +label.guest=Invité +label.please.specify.netscaler.info=Renseigner les informations sur le Netscaler +# message.public.traffic.in.advanced.zone=Public traffic is generated when VMs in the cloud access the internet. Publicly-accessible IPs must be allocated for this purpose. End users can use the CloudStack UI to acquire these IPs to implement NAT between their guest network and their public network.

Provide at least one range of IP addresses for internet traffic. +# message.public.traffic.in.basic.zone=Public traffic is generated when VMs in the cloud access the Internet or provide services to clients over the Internet. Publicly accessible IPs must be allocated for this purpose. When a instance is created, an IP from this set of Public IPs will be allocated to the instance in addition to the guest IP address. Static 1-1 NAT will be set up automatically between the public IP and the guest IP. End users can also use the CloudStack UI to acquire additional IPs to implement static NAT between their instances and the public IP. +# message.add.pod.during.zone.creation=Each zone must contain in one or more pods, and we will add the first pod now. A pod contains hosts and primary storage servers, which you will add in a later step. First, configure a range of reserved IP addresses for CloudStack\'s internal management traffic. The reserved IP range must be unique for each zone in the cloud. +# message.guest.traffic.in.advanced.zone=Guest network traffic is communication between end-user virtual machines. Specify a range of VLAN IDs to carry guest traffic for each physical network. +# message.guest.traffic.in.basic.zone=Guest network traffic is communication between end-user virtual machines. Specify a range of IP addresses that CloudStack can assign to guest VMs. Make sure this range does not overlap the reserved system IP range. +# message.storage.traffic=Traffic between CloudStack\'s internal resources, including any components that communicate with the Management Server, such as hosts and CloudStack system VMs. Please configure storage traffic here. +# message.desc.cluster=Each pod must contain one or more clusters, and we will add the first cluster now. A cluster provides a way to group hosts. The hosts in a cluster all have identical hardware, run the same hypervisor, are on the same subnet, and access the same shared storage. Each cluster consists of one or more hosts and one or more primary storage servers. +# message.desc.host=Each cluster must contain at least one host (computer) for guest VMs to run on, and we will add the first host now. For a host to function in CloudStack, you must install hypervisor software on the host, assign an IP address to the host, and ensure the host is connected to the CloudStack management server.

Give the host\'s DNS or IP address, the user name (usually root) and password, and any labels you use to categorize hosts. +# message.desc.primary.storage=Each cluster must contain one or more primary storage servers, and we will add the first one now. Primary storage contains the disk volumes for all the VMs running on hosts in the cluster. Use any standards-compliant protocol that is supported by the underlying hypervisor. +# message.desc.secondary.storage=Each zone must have at least one NFS or secondary storage server, and we will add the first one now. Secondary storage stores VM templates, ISO images, and VM disk volume snapshots. This server must be available to all hosts in the zone.

Provide the IP address and exported path. +label.launch.zone=Démarrer la zone +message.please.wait.while.zone.is.being.created=Patienter pendant la création de la zone, cela peut prendre du temps... + +label.load.balancing=Load Balancing +label.static.nat.enabled=NAT statique activé +label.zones=Zones +label.view.more=Voir plus +label.number.of.zones=Nombre de zones +label.number.of.pods=Nombre de Pods +label.number.of.clusters=Nombre de clusters +label.number.of.hosts=Nombre de serveurs +label.total.hosts=Total serveurs +label.total.CPU=Capacité Totale en CPU +label.total.memory=Total mémoire +label.total.storage=Total stockage +label.purpose=Rôle + + + + +label.action.migrate.router=Migration routeur +label.action.migrate.router.processing=Migration routeur en cours... +message.migrate.router.confirm=Confirmer la migration du routeur vers \: +label.migrate.router.to=Migrer le routeur vers + +label.action.migrate.systemvm=Migration VM système +label.action.migrate.systemvm.processing=Migration VM système en cours ... +message.migrate.systemvm.confirm=Confirmer la migration de la VM système vers \: +label.migrate.systemvm.to=Miger la VM système vers + + +mode=Mode +side.by.side=Côte à cote +inline=Aligné + +extractable=Décompressable + +label.ocfs2=OCFS2 + +label.action.edit.host=Modifier l\'hôte + +network.rate=Débit Réseau + +ICMP.type=Type ICMP +ICMP.code=Code ICMP + +image.directory=Répertoire d\'images + +label.action.create.template.from.vm=Créer un modèle depuis la VM +label.action.create.template.from.volume=Créer un modèle depuis le volume + +message.vm.create.template.confirm=Créer un modèle va redémarrer la VM automatiquement + +label.action.manage.cluster=Gérer le Cluster +message.action.manage.cluster=Confirmez que vous voulez gérer le cluster +label.action.manage.cluster.processing=Gestion du cluster... + +label.action.unmanage.cluster=Ne plus gérer le Cluster +message.action.unmanage.cluster=Confirmez que vous ne voulez plus gérer le cluster +label.action.unmanage.cluster.processing=Arrêt de la gestion du Cluster + +label.allocation.state=Etat de l\'allocation +managed.state=Etat de la gestion + +label.default.use=Utilisation par défaut +label.host.tags=Labels Server + +label.cidr=CIDR +label.cidr.list=CIDR Source + +label.storage.tags=Etiquettes de stockage + +label.redundant.router=Routeur redondant +label.is.redundant.router=Redondant + +force.delete=Forcer la suppression +force.delete.domain.warning=Attention\: Choisir cette opion entrainera la suppression de tous les domaines issus et l\'ensemble des comptes associées, ainsi que de leur ressources + +force.remove=Forcer la suppression +force.remove.host.warning=Attention\: Choisir cette option entrainera CloudStack à  arrêter l\'ensemble des machines virtuelles avant d\'enlever l\'hôte du cluster + +force.stop=Forcer l\'arrêt +force.stop.instance.warning=Attention \: un arrêt forcé sur cette instance est l\'option ultime. Cela peut engendrer des pertes de données et/ou un comportement inconsitent de votre instance. + +label.PreSetup=PreSetup +label.SR.name = Nom du point de montage +label.SharedMountPoint=Point de montage partagé +label.clvm=CLVM +label.volgroup=Volume Group +label.VMFS.datastore=datastore VMFS + +label.network.device=Equipement Réseau +label.add.network.device=Ajouter un équipement réseau +label.network.device.type=Type d\'équipement réseau +label.DHCP.server.type=Serveur DHCP +label.Pxe.server.type=Serveur PXE +label.PING.storage.IP=adresse PING (stockage) +label.PING.dir=répertoire PING +label.TFTP.dir=répertoire TFTP +label.PING.CIFS.username=utilisateur CIFS PING +label.PING.CIFS.password=mot de passe CIFS PING +label.CPU.cap=Utilisation maximum du CPU + + +label.action.enable.zone=Activer la zone +label.action.enable.zone.processing=Activation de la zone... +message.action.enable.zone=Confirmez que vous voulez activer cette zone +label.action.disable.zone=Désactivation de la zone +label.action.disable.zone.processing=Désactivation de la zone... +message.action.disable.zone=Confirmez que vous voulez désactiver cette zone + +label.action.enable.pod=Activer le Pod +label.action.enable.pod.processing=Activation du Pod... +message.action.enable.pod=Confirmez que vous souhaitez activer ce Pod +label.action.disable.pod=Désactiver le Pod +label.action.disable.pod.processing=Désactivation du Pod... +message.action.disable.pod=Confirmez que vous voulez désactiver ce Pod + +label.action.enable.cluster=Activer le cluster +label.action.enable.cluster.processing=Activation du cluster... +message.action.enable.cluster=Confirmez que vous souhaitez activer ce cluster +label.action.disable.cluster=Désactiver le cluster +label.action.disable.cluster.processing=Désactivation du cluster... +message.action.disable.cluster=Confirmez que vous souhaitez désactiver ce cluster + +label.account.id=ID du Compte +label.account.name=Nom du compte +label.account.specific=Spécifique au compte +label.account=Compte +label.accounts=Comptes +label.acquire.new.ip=Acquérir une nouvelle adresse IP +label.show.ingress.rule=Montrer la règle Ingress +label.hide.ingress.rule=Cacher la règle Ingress +label.action.attach.disk.processing=Attachement du Disque... +label.action.attach.disk=Attacher un disque +label.action.attach.iso.processing=Attachement de l\'image ISO +label.action.attach.iso=Attacher une image ISO +label.action.cancel.maintenance.mode.processing=Annulation du mode maintenance... +label.action.cancel.maintenance.mode=Annuler le mode maintenance +label.action.change.password=Changer le mot de passe +label.action.change.service.processing=Changement de d\'offre de service... +label.action.change.service=Changer d\'offre de service +label.action.copy.ISO.processing=Copie de l\'image ISO... +label.action.copy.ISO=Copier une image ISO +label.action.copy.template.processing=Copie du Modèle... +label.action.copy.template=Copier un modèle +label.action.create.template.processing=Création du Modèle... +label.action.create.template=Créer un modèle +label.action.create.vm.processing=Création de la VM.. +label.action.create.vm=Créer une VM +label.action.create.volume.processing=Création du Volume... +label.action.create.volume=Créer un Volume +label.action.delete.IP.range.processing=Suppression de la plage IP... +label.action.delete.IP.range=Supprimer la plage IP +label.action.delete.ISO.processing=Suppression de l\'image ISO... +label.action.delete.ISO=Supprimer l\'image ISO +label.action.delete.account.processing=Suppression du compte... +label.action.delete.account=Supprimer un compte +label.action.delete.cluster.processing=Suppression du Cluster... +label.action.delete.cluster=Supprimer le Cluster +label.action.delete.disk.offering.processing=Suppression de l\'offre Disque... +label.action.delete.disk.offering=Supprimer l\'offre Disque + +label.action.update.resource.count=Mettre à jour le compte d\'utilisation des ressources +label.action.update.resource.count.processing=Mise à jour du compteur... + +label.action.delete.domain=Supprimer le domaine +label.action.delete.domain.processing=Suppression du domaine... + +label.action.delete.firewall.processing=Suppression du Parefeu... +label.action.delete.firewall=Supprimer la règle de firewall +label.action.delete.ingress.rule.processing=Suppression de la règle Ingress.. +label.action.delete.ingress.rule=Supprimer la règle Ingress +label.action.delete.load.balancer.processing=Suppression de l\'équilibreur de charge... +label.action.delete.load.balancer=Supprimer la règle de load balancer +label.action.edit.network.processing=Modification du Réseau... +label.action.edit.network=Modifier le réseau +label.action.delete.network.processing=Suppression du réseau... +label.action.delete.network=Supprimer le réseau +label.action.delete.pod.processing=Suppression du pod... +label.action.delete.pod=Supprimer le Pod +label.action.delete.primary.storage.processing=Suppression du stockage primaire... +label.action.delete.primary.storage=Supprimer le stockage primaire +label.action.delete.secondary.storage.processing=Suppression du stockage secondaire... +label.action.delete.secondary.storage=Supprimer le stockage secondaire +label.action.delete.security.group.processing=Suppression du groupe de sécurité +label.action.delete.security.group=Supprimer le groupe de sécurité +label.action.delete.service.offering.processing=Suppression de l\'offre de service... +label.action.delete.service.offering=Supprimer l\'offre de service +label.action.delete.snapshot.processing=Suppresison de l\'instantané... +label.action.delete.snapshot=Supprimer l\'instantané +label.action.delete.template.processing=Suppression du modèle... +label.action.delete.template=Supprimer le modèle +label.action.delete.user.processing=Suppression de l\'utilisateur... +label.action.delete.user=Supprimer l\'utilisateur +label.action.delete.volume.processing=Suppression du volume... +label.action.delete.volume=Supprimer le volume +label.action.delete.zone.processing=Suppression de la zone... +label.action.delete.zone=Supprimer la zone +label.action.destroy.instance.processing=Suppression de l\'instance... +label.action.destroy.instance=Supprimer l\'instance +label.action.destroy.systemvm.processing=Suppression de la VM Système... +label.action.destroy.systemvm=Supprimer la VM Système +label.action.detach.disk.processing=Détachement du disque... +label.action.detach.disk=Détacher le disque +label.action.detach.iso.processing=Détachement de l\'image ISO... +label.action.detach.iso=Détacher l\'image ISO +label.action.disable.account.processing=Désactivation du compte... +label.action.disable.account=Désactiver le compte +label.action.disable.static.NAT.processing=Désactivation du NAT Statique... +label.action.disable.static.NAT=Désactiver le NAT Statique +label.action.disable.user.processing=Désactivation du l\'utilisateur... +label.action.disable.user=Désactiver l\'utilisateur +label.action.download.ISO=Télécharger une image ISO +label.action.download.template=Télécharger un modèle +label.action.download.volume.processing=Téléchargement du volume... +label.action.download.volume=Télécharger un volume +label.action.edit.ISO=Modifier l\'image ISO +label.action.edit.account=Modifier le Compte +label.action.edit.disk.offering=Modifier l\'offre de disque +label.action.edit.domain=Modifier le domaine +label.action.edit.global.setting=Modifier la configuration globale +label.action.edit.instance=Modifier l\'instancer +label.action.edit.network.offering=Modifier l\'offre de service réseau +label.action.edit.pod=Modifier le pod +label.action.edit.primary.storage=Modifier le stockage primaire +label.action.edit.resource.limits=Modifier les limites de ressources +label.action.edit.service.offering=Modifier l\'offre de service +label.action.edit.template=Modifier le modèle +label.action.edit.user=Modifier l\'utilisateur +label.action.edit.zone=Modifier la zone +label.action.enable.account.processing=Activation du compte... +label.action.enable.account=Activer le compte +label.action.enable.maintenance.mode.processing=Activation du mode maintenance... +label.action.enable.maintenance.mode=Activer le mode maintenance +label.action.enable.static.NAT.processing=Activation du NAT Statique... +label.action.enable.static.NAT=Activer le NAT Statique +label.action.enable.user.processing=Activation de l\'utilisateur... +label.action.enable.user=Activer l\'utilisateur +label.action.force.reconnect.processing=Reconnexion en cours... +label.action.force.reconnect=Forcer la reconnexion +label.action.generate.keys.processing=Génération des clés... +label.action.generate.keys=Générer les clés +label.action.lock.account.processing=Blocage du compte... +label.action.lock.account=Bloquer le compte +label.action.migrate.instance=Migrer l\'instance +label.action.migrate.instance.processing=Migration de l\'instance... +label.action.reboot.instance.processing=Redémarrage de l\'instance... +label.action.reboot.instance=Redémarrer l\'instance +label.action.reboot.router.processing=Redémarrage du routeur... +label.action.reboot.router=Redémarrer le routeur +label.action.reboot.systemvm.processing=Redémarrage de la VM Système... +label.action.reboot.systemvm=Redémarre la VM Système +label.action.recurring.snapshot=Snapshots récurrents +label.action.release.ip.processing=Libération de l\'adresse IP... +label.action.release.ip=Libérer l\'adresse IP +label.action.remove.host.processing=Suppression de l\'hôte... +label.action.remove.host=Supprimer l\'hôte +label.action.reset.password.processing=Réinitialisation le mot de passe... +label.action.reset.password=Réinitialiser le mot de passe +label.action.resource.limits=Limites de ressources +label.action.restore.instance.processing=Restauration de l\'instance... +label.action.restore.instance=Restaurer l\'instance +label.action.start.instance.processing=Démarrage de l\'instance +label.action.start.instance=Démarrer l\'instance +label.action.start.router.processing=Démarrage du routeur... +label.action.start.router=Démarrer le routeur +label.action.start.systemvm.processing=Démarrage de la VM système +label.action.start.systemvm=Démarrer la VM système +label.action.stop.instance.processing=Arrêt de l\'Instance... +label.action.stop.instance=Arrêter l\'Instance +label.action.stop.router.processing=Arrêt du routeur... +label.action.stop.router=Arrêter le routeur +label.action.stop.systemvm.processing=Arrêt de la VM système... +label.action.stop.systemvm=Arrêter la VM système +label.action.take.snapshot.processing=Prise de l\'instantané +label.action.take.snapshot=Prendre un instantané +label.action.update.OS.preference.processing=Mise à jour des préférences d\'OS... +label.action.update.OS.preference=Mettre à jour les préférences d\'OS +label.actions=Actions +label.active.sessions=Sessions actives +label.add.account=Ajouter un compte +label.add.by.cidr=Ajouter par CIDR +label.add.by.group=Ajouter par groupe +label.add.cluster=Ajouter un cluster +label.add.direct.iprange=Ajouter une plage d\'adresse IP directe +label.add.disk.offering=Ajouter une offre disque +label.add.domain=Ajouter un domaine +label.add.firewall=Ajouter une règle firewall +label.add.host=Ajouter un hôte +label.add.ingress.rule=Ajouter une règle Ingress +label.add.ip.range=Ajouter une plage IP +label.add.load.balancer=Ajouter un partageur de charge +label.add.more=Ajouter plus +label.add.network=Ajouter un réseau +label.add.pod=Ajouter un pod +label.add.primary.storage=Ajouter un stockage primaire +label.add.secondary.storage=Ajouter un stockage secondaire +label.add.security.group=Ajouter un groupe de sécurité +label.add.service.offering=Ajouter un offre de service +label.add.template=Ajouter un modèle +label.add.user=Ajouter un utilisateur +label.add.vlan=Ajouter un vlan +label.add.volume=Ajouter un volume +label.add.zone=Ajouter une zone +label.add=Ajouter +label.adding.cluster=Ajout du Cluster +label.adding.failed=Echec de l\'ajout +label.adding.pod=Ajout du Pod +label.adding.processing=Ajout... +label.adding.succeeded=Ajout réussi +label.adding.user=Ajout de l\'utilisateur +label.adding.zone=Ajout de la zone +label.adding=Ajout +label.additional.networks=Réseaux additionnels +label.admin.accounts=Comptes Administrateur +label.admin=Administrateur +label.advanced.mode=Mode avancé +label.advanced.search=Recherche avancée +label.advanced=Avancé +label.alert=Alerte +label.algorithm=Algorithme +label.allocated=Alloué +label.api.key=Clé d\'API +label.assign.to.load.balancer=Assigner l\'instance au partageur de charge +label.assign=Assigner +label.associated.network.id=ID du réseau associé +label.attached.iso=Image ISO attachée +label.availability.zone=Zone de disponibilité +label.availability=Disponibilité +label.available.public.ips=Adresses IP publiques disponibles +label.available=Disponible +label.back=Retour +label.basic.mode=Mode basique +label.bootable=Bootable +label.broadcast.domain.type=Type de domaine de broadcast +label.by.account=Par compte +label.by.availability=Par disponibilité +label.by.domain=Par domaine +label.by.end.date=Par date de fin +label.by.level=Par niveau +label.by.pod=Par Pod +label.by.role=Par role +label.by.start.date=Par date de début +label.by.state=Par état +label.by.traffic.type=Par type de traffic +label.by.type.id=Par type d\'ID +label.by.type=Par type +label.by.zone=Par zone +label.bytes.received=Octets reçus +label.bytes.sent=Octets envoyés +label.cancel=Annuler +label.certificate=Certificat +label.privatekey=Clé privée PKCS\#8 +label.domain.suffix=Suffixe de domaine DNS (i.e., xyz.com) +label.character=Caractère +label.cidr.account=CIDR ou Compte/Groupe de sécurité +label.close=Fermer +label.cloud.console=Console de gestion du cloud +label.cloud.managed=Géré par Cloud.com +label.cluster.type=Type de Cluster +label.cluster=Cluster +label.code=Code +label.confirmation=Confirmation +label.cpu.allocated.for.VMs=CPU alloué aux VMs +label.cpu.allocated=CPU alloué +label.cpu.utilized=CPU utilisé +label.cpu=CPU +label.created=Créé +label.cross.zones=Multi Zones +label.custom.disk.size=Taille de disque personnalisée +label.daily=Quotidien +label.data.disk.offering=Offre de disque de données +label.date=Date +label.day.of.month=Jour du mois +label.day.of.week=Jour de la semaine +label.delete=Supprimer +label.deleting.failed=Suppression échouée +label.deleting.processing=Suppression... +label.description=Description +label.detaching.disk=Détacher le disque +label.details=Details +label.device.id=ID du périphérique +label.disabled=Désactivé +label.disabling.vpn.access=Désactiver l\'accès VPN +label.disk.allocated=Disque Alloué +label.disk.offering=Offre de Disque +label.disk.size.gb=Taille du disque (en Go) +label.disk.size=Taille du disque +label.disk.total=Espace disque total +label.disk.volume=Volume disque +label.display.text=Texte affiché +label.dns.1=DNS1 +label.dns.2=DNS2 +label.domain.admin=Administrateur du domaine +label.domain.id=ID du domaine +label.domain.name=Nom de domaine +label.domain=Domaine +label.double.quotes.are.not.allowed=Les guillemets ne sont pas autorisés +label.download.progress=Progression du téléchargement +label.edit=Modifier +label.email=Email +label.enabling.vpn.access=Activation de l\'accès VPN +label.enabling.vpn=Activation du VPN +label.end.port=Port de fin +label.endpoint.or.operation=Terminaison ou Opération +label.error.code=Code d\'erreur +label.error=Erreur +label.esx.host=Hôte ESX/ESXi +label.example=Exemple +label.failed=Echoué +label.featured=Sponsorisé +label.firewall=Parefeu +label.first.name=Prénom +label.format=Format +label.friday=Vendredi +label.full=Complet +label.gateway=Passerelle +label.general.alerts=Alertes générales +label.generating.url=Génération de l\'URL +label.go.step.2=Aller à l\'étape 2 +label.go.step.3=Aller à l\'étape 3 +label.go.step.4=Aller à l\'étape 4 +label.go.step.5=Aller à l\'étape 5 +label.group.optional=Groupe (optionnel) +label.group=Groupe +label.guest.cidr=CIDR invités +label.guest.gateway=Passerelle pour les invités +label.guest.ip.range=Plage d\'adresses IP des invités +label.guest.ip=Adresse IP des invités +label.guest.netmask=Masque de réseau des invités +label.ha.enabled=Haute disponibilité active +label.help=Aide +label.host.alerts=Alertes des hôtes +label.host.name=Nom d\'hôte +label.host=Serveur +label.hosts=Serveurs +label.hourly=A l\'heure +label.hypervisor.type=Type d\'hyperviseur +label.hypervisor=Hyperviseur +label.id=ID +label.info=Information +label.ingress.rule=Règle Ingress +label.initiated.by=Initié par +label.instance.limits=Limites des instances +label.instance.name=Nom de lìnstance +label.instance=Instance +label.instances=Instances +label.internal.dns.1=DNS interne 1 +label.internal.dns.2=DNS interne 2 +label.interval.type=Type d\'ìntervalle +label.invalid.integer=Nombre entier invalide +label.invalid.number=Nombre invalide +label.ip.address=Adresse IP +label.ip.allocations=Allocations de IPs +label.ip.limits=Limite de IPs publiques +label.ip.or.fqdn=IP ou FQDN +label.ip.range=Plage IP +label.ip=IP +label.ips=IPs +label.is.default=Est par défaut +label.is.shared=Est partagé +label.is.system=Type système +label.iscsi=iSCSI +label.iso.boot=Démarrage par ISO +label.iso=ISO +label.isolation.mode=Mode d\'isolation +label.keep=Conserver +label.lang.chinese=Chinois (simplifié) +label.lang.english=Anglais +label.lang.japanese=Japonais +label.lang.spanish=Espagnol +label.last.disconnected=Dernière Déconnexion +label.last.name=Nom de famille +label.level=Niveau +label.linklocal.ip=Adresse IP de lien local +label.load.balancer=Partageur de charge +label.loading=Chargement en cours +label.local=Local +# label.local.storage.enabled=Local storage enabled +label.login=Connexion +label.logout=Déconnexion +label.lun=LUN +label.manage=Géré +label.maximum=Maximum +label.memory.allocated=Mémoire allouée +label.memory.total=Mémoire totale +label.memory.used=Mémoire utilisée +label.memory=Mémoire (en MB) +label.menu.accounts=Comptes +label.menu.alerts=Alertes +label.menu.all.accounts=Tout les comptes +label.menu.all.instances=Toutes les instances +label.menu.community.isos=ISO de la communauté +label.menu.community.templates=Modèles de la communauté +label.menu.configuration=Configuration +label.menu.dashboard=Tableau de bord +label.menu.destroyed.instances=Instances détruites +label.menu.disk.offerings=Offres de disque +label.menu.domains=Domaines +label.menu.events=Evénements +label.menu.featured.isos=ISOs Sponsorisées +label.menu.featured.templates=Modèles sponsorisés +label.menu.global.settings=Paramètres globaux +label.menu.instances=Instances +label.menu.ipaddresses=Adresses IP +label.menu.isos=ISOs +label.menu.my.accounts=Mes comptes +label.menu.my.instances=Mes instances +label.menu.my.isos=Mes ISOs +label.menu.my.templates=Mes modèles +label.menu.network.offerings=Offres de Service Réseau +label.menu.network=Réseau +label.menu.physical.resources=Ressources physiques +label.menu.running.instances=Instances actives +label.menu.security.groups=Groupes de sécurité +label.menu.service.offerings=Offres de Service +label.menu.snapshots=Instantanés +label.menu.stopped.instances=Instances Arrêtées +label.menu.storage=Stockage +label.menu.system.vms=\ VMs Systèmes +label.menu.system=Système +label.menu.templates=Modèles +label.menu.virtual.appliances=Appliances Virtuelles +label.menu.virtual.resources=Ressources Virtuelles +label.menu.volumes=Volumes +label.migrate.instance.to=Migrer l\'instance vers +label.minimum=Minimum +label.minute.past.hour=minute(s) +label.monday=Lundi +label.monthly=Mensuel +label.more.templates=Plus de modèles +label.my.account=Mon compte +label.name.optional=Nom (optionnel) +label.name=Nom +label.netmask=Masque de réseau +label.network.desc=Description réseau +label.network.domain=Nom de domaine +label.network.id=ID réseau +label.network.name=Nom du réseau +label.network.offering.display.text=Texte affiché d\'Offre de Réseau +label.network.offering.id=ID de l\'Offre de Service Réseau +label.network.offering.name=Nom de l\'Offre de Service Réseau +label.network.offering=Offre de Service Réseau +label.network.rate=Débit réseau +label.network.read=Lecture réseau +label.network.type=Type de réseau +label.network.write=Écriture réseau +label.network=Réseau +label.new.password=Nouveau mot de passe +label.next=Suivant +label.nfs.server=Serveur NFS +label.nfs.storage=Stockage NFS +label.nfs=NFS +label.nics=Cartes NIC +label.no.actions=Aucune action disponibles +label.no.alerts=Aucune alerte récentes +label.no.errors=Aucune erreur récentes +label.no.isos=Aucun ISOs disponibles +label.no.items=Aucun élément disponibles +label.no.security.groups=Aucun groupe de sécurité disponibles +label.no.thanks=Non merci +label.no=Non +label.none=Aucun +label.not.found=Introuvable +label.num.cpu.cores=Nombre de c\u0153urs de processeur +label.numretries=Nombre de tentatives +label.offer.ha=Offrir la haute disponibilité +label.optional=Facultatif +label.os.preference=Préférence du OS +label.os.type=Type du OS +label.owned.public.ips=Addresses IP Publique détenues +label.owner.account=Compte propriétaire +label.owner.domain=Propriétaire du domaine +label.parent.domain=Domaine Parent +label.password.enabled=Mot de passe activé +label.password=Mot de passe +label.path=Chemin +label.please.wait=Patientez s\'il vous plait +label.pod=Pod +label.port.forwarding=Redirection de port +label.port.range=Plage de ports +label.prev=Précédent +label.primary.allocated=Stockage primaire alloué +label.primary.network=Réseau primaire +label.primary.storage=Stockage primaire +label.primary.used=Stockage primaire utilisé +label.private.interface=Interface privée +label.private.ip.range=Plage d\'adresses IP Privées +label.private.ip=Adresse IP Privée +label.private.ips=Adresses IP Privées +label.private.port=Port privé +label.private.zone=Zone Privée +label.protocol=Protocole +label.public.interface=Interface publique +label.public.ip=Adresse IP publique +label.public.ips=Adresses IP publiques +label.public.port=Port public +label.public.zone=Zone publique +label.public=Publique +label.recent.errors=Erreurs récentes +label.refresh=Actualiser +label.related=Connexes +label.remove.from.load.balancer=Supprimer l\'instance du partageur de charge +label.removing.user=Retrait de l\'utilisateur +label.required=Requis +label.reserved.system.ip=Adresse IP Système réservé +label.resource.limits=Limite des ressources +label.resource=Ressource +label.resources=Ressources +label.role=Rôle +label.root.disk.offering=Offre de disque racine +label.running.vms=VMs actives +label.saturday=Samedi +label.save=Sauvegarder +label.saving.processing=Sauvegarde en cours.... +label.scope=Portée +label.search=Rechercher +label.secondary.storage=Stockage secondaire +label.secondary.used=Stockage secondaire utilisé +label.secret.key=clé privée +label.security.group.name=Nom du groupe de sécurité +label.security.group=Groupe de sécurité +label.security.groups.enabled=Groupes de sécurité Activés +label.security.groups=Groupes de sécurité +label.sent=Envoyer +label.server=Serveur +label.service.offering=Offre de Service +label.system.service.offering=Offre de Service Système +label.session.expired=Session expiré +label.shared=En partage +label.size=Taille +label.snapshot.limits=Limite d\'instantanés +label.snapshot.name=Nom de l\'instantané +label.snapshot.s=Instantané(s) +label.snapshot.schedule=Configurer un snapshot récurrent +label.snapshot=Instantané +label.snapshots=Instantanés +label.source.nat=NAT Source +label.specify.vlan=Précisez le VLAN +label.start.port=Port de +label.state=État +label.static.nat.to=NAT Static vers +label.static.nat=NAT Static +label.statistics=Statistiques +label.status=Statut +label.step.1.title=Etape 1 \: Sélectionnez un modèle +label.step.1=Étape 1 +label.step.2.title=Etape 2\: Offre de Service +label.step.2=Étape 2 +label.step.3.title=Etape 3\: Sélectionnez une offre de service +label.step.3=Étape 3 +label.step.4.title=Etape 4\: Réseau +label.step.4=Étape 4 +label.step.5.title=Etape 5\: Vérification +label.step.5=Étape 5 +label.stopped.vms=VMs arrêtés +label.storage.type=Type de stockage +label.storage=Stockage +label.submit=Envoyer +label.submitted.by=[Soumis par\: ] +label.succeeded=Réussi +label.sunday=Dimanche +label.system.capacity=Capacité système +label.system.vm.type=Type de VM système +label.system.vm=VM Système +label.system.vms=\ VMs systèmes +label.tagged=Taggé +label.tags=Tags +label.target.iqn=IQN de la Cible +label.template.limits=Limites des modèles +label.template=Modèle +label.theme.default=Thème par défaut +label.theme.grey=Personnalisé - Gris +label.theme.lightblue=Personnalisé - Blue clair +label.thursday=Jeudi +label.time.zone=Fuseau horaire +label.time=Temps +label.timeout.in.second = Timeout (secondes) +label.timezone=Fuseau horaire +label.total.cpu=Capacité Totale en CPU +label.total.vms=Nombre total de VMs +label.traffic.type=Type de Traffic +label.tuesday=Mardi +label.type.id=ID du Type +label.type=Type +label.unavailable=Indisponible +label.unlimited=Illimité +label.untagged=Non Taggé +label.update.ssl.cert=Mettre à jour le certificate SSL +label.update.ssl=Mettre à jour le certificate SSL +label.updating=Mise à jour +label.url=URL +label.usage.interface=Interface d\'Usage +label.used=Utilisé +label.user=Utilisateur +label.username=Nom d\'Utilisateur +label.users=Utilisateurs +label.value=Valeur +label.vcenter.cluster=Cluster vCenter +label.vcenter.datacenter=Datacenter vCenter +label.vcenter.datastore=Datastore vCenter +label.vcenter.host=Hôte Vcenter +label.vcenter.password=Mot de passe vCenter +label.vcenter.username=Nom d\'utilisateur vCenter +label.version=Version +label.virtual.appliance=Appliance Virtuelle +label.virtual.appliances=Appliances Virtuelles +label.virtual.network=Réseau virtuel +label.vlan.id=ID du VLAN +label.vlan.range=Plage du VLAN +label.vm.add=Ajouter une instance +label.vm.destroy=Détruire +label.vm.reboot=Redémarrer +label.vm.start=Démarrer +label.vm.stop=Arrêtez +label.vmfs=VMFS +label.vms=VMs +label.volume.limits=Limites des volumes +label.volume.name=Nom du volume +label.volume=Volume +label.volumes=Volumes +label.vsphere.managed=Gérée par vSphere +label.waiting=En attente +label.warn=Avertir +label.wednesday=Mercredi +label.weekly=Hebdomadaire +label.welcome.cloud.console=Bienvenue dans la console de gestion +label.welcome=Bienvenue +label.yes=Oui +label.zone.id=ID de la zone +label.zone.step.1.title=Etape 1\: Sélectionnez un réseau +label.zone.step.2.title=Etape 2\: Ajoutez une zone +label.zone.step.3.title=Etape 3\: Ajoutez un Pod +label.zone.step.4.title=Etape 4\: Ajoutez une plage d\'adresses IP +label.zone.wide=Transverse à la zone +label.zone=Zone + +#Messages +message.acquire.public.ip=Sélectionnez la zone dans laquelle vous voulez acquérir votre nouvelle adresse IP. +message.action.cancel.maintenance.mode=Confirmer que vous souhaitez annuler cette maintenance. +message.action.cancel.maintenance=Votre hôte a été annulée de la maintenance. Ce processus peut prendre jusqu\'à plusieurs minutes. +message.action.delete.ISO.for.all.zones=L\'ISO est utilisé par toutes les zones. S\'il vous plaît confirmer que vous voulez le supprimer de toutes les zones. +message.action.delete.ISO=Confirmer que vous souhaitez supprimer cette ISO. +message.action.delete.cluster=Confirmer que vous voulez supprimer ce cluster. +message.action.delete.disk.offering=Confirmer que vous souhaitez supprimer cette offre de disque. +message.action.delete.domain=Confirmer que vous voulez supprimer ce domaine. +message.action.delete.external.firewall=Confirmer que vous souhaitez supprimer ce pare-feu externe. Attention\: Si vous prévoyez de rajouter le même pare-feu externe de nouveau, vous devez réinitialiser les données d\'utilisation sur l\'appareil. +message.action.delete.external.load.balancer=Confirmez que vous souhaitez supprimer ce partageur de charge externe. Attention \: Si vous pensez ajouter le même partageur de charge plus tard, vous devez remettre à zéro les statistiques d\'usage de cet équipement. +message.action.delete.ingress.rule=Confirmez que vous souhaitez supprimer cette règle Ingress +message.action.delete.network=Confirmer que vous voulez supprimer ce réseau. +message.action.delete.pod=Confirmez que vous souhaitez supprimer ce pod. +message.action.delete.primary.storage=Confirmer que vous voulez supprimer ce stockage primaire. +message.action.delete.secondary.storage=Confirmez que vous souhaitez supprimer ce stockage secondaire. +message.action.delete.security.group=Confirmez que vous souhaitez supprimer ce groupe de sécurité. +message.action.delete.service.offering=Confirmez que vous souhaitez supprimer cette offre de service. +message.action.delete.snapshot=Confirmez que vous souhaitez supprimer cet instantané +message.action.delete.template.for.all.zones=Ce modèle est utilisé par toutes les zones. Confirmez que vous souhaitez le supprimer de toutes les zones. +message.action.delete.template=Confirmez que vous souhaitez supprimer ce modèle. +message.action.delete.volume=Confirmez que vous souhaitez supprimer ce volume. +message.action.delete.zone=Confirmez que vous souhaitez supprimer cette zone. +message.action.destroy.instance=Confirmez que vous souhaitez supprimer cette instance. +message.action.destroy.systemvm=Confirmez que vous souhaitez supprimer cette VM Système. +message.action.disable.static.NAT=Confirmez que vous souhaitez désactiver le NAT statique. +message.action.enable.maintenance=Votre hôte a été mis en mode maintenance avec succès. Ce processus peut durer plusieurs minutes ou plus suivant le nombre de VMs actives sur cet hôte. +message.action.force.reconnect=Votre hôte a été forcé à se reconnecter avec succès. Ce processus peut prendre jusqu\'à plusieurs minutes. +message.action.host.enable.maintenance.mode=Activer le mode maintenance va causer la migration à chaud de l\'ensemble des instances de cet hôte sur les autres hôtes disponibles. +message.action.instance.reset.password=Confirmer le changement du mot de passe ROOT pour cette machine virtuelle. +message.action.primarystorage.enable.maintenance.mode=Attention \: placer ce stockage primaire en mode maintenance que l\'ensemble des VMs utilisant des volumes sur ce stockage. Souhaitez vous continuer ? +message.action.reboot.instance=Confirmez que vous souhaitez redémarrer cette instance. +message.action.reboot.systemvm=Confirmez que vous souhaitez redémarrer cette VM Système +message.action.release.ip=Confirmez que vous souhaitez libérer cette IP. +message.action.remove.host=Supprimer le dernier/seul hôte dans le cluster et le réinstaller va supprimer l\'environnement/la base de données sur l\'hôte et rendre les VMs invitées inutilisables. +message.action.restore.instance=Confirmez que vous souhaitez restaurer cette instance. +message.action.start.instance=Confirmez que vous souhaitez démarrer cette instance. +message.action.start.router=Confirmez que vous souhaitez démarrer ce routeur. +message.action.start.systemvm=Confirmez que vous souhaitez redémarrer cette VM système. +message.action.stop.instance=Confirmez que vous souhaitez arrêter cette instance. +message.action.stop.systemvm=Confirmez que vous souhaitez arrêter cette VM. +message.action.take.snapshot=Confirmer la prise d\'un snapshot pour ce volume. +message.add.cluster.zone=Ajouter un cluster d\'hyperviseurs géré pour cette zone +message.add.cluster=Ajouter un cluster d\'hyperviseurs géré pour cette zone , pod +message.add.disk.offering=Renseignez les paramètres suivants pour ajouter un offre de service de disques +message.add.firewall=Ajouter un parefeu à cette zone +message.add.host=Renseignez les paramètres suivant pour ajouter un hôte +message.add.ip.range.direct.network=Ajouter une plage IP au réseau direct dans la zone +message.add.ip.range.to.pod=

Ajouter une plage IP pour le pod\:

+message.add.ip.range=Ajouter une plage IP pour le réseau publique dans la zone +message.add.load.balancer=Ajouter un partageur de charge à la zone +message.add.network=Ajouter un nouveau réseau à la zone\: +message.add.pod=Ajouter un nouveau pod à la zone +message.add.primary.storage=Ajouter un nouveau stockage primaire à la zone , pod +message.add.primary=Renseignez les paramètres suivants pour ajouter un sotckage primaire +message.add.secondary.storage=Ajouter un nouveau stockage pour la zone +message.add.service.offering=Renseigner les informations suivantes pour ajouter une nouvelle offre de service computing. +message.add.template=Renseignez les informations suivantes pour créer votre nouveau modèle +message.add.volume=Renseignez les informations suivantes pour ajouter un nouveau volume +message.additional.networks.desc=Sélectionnez le(s) réseau(x) additionnel(s) au(x)quel(s) sera connectée votre instance. +message.advanced.mode.desc=Choisissez ce modèle de réseau si vous souhaitez bénéficier du support des VLANs. Ce mode de réseau donne le plus de flexibilité aux administrateurs pour fournir des offres de service réseau personnalisées comme fournir des parefeux, vpn, partageurs de charge ou également activer des réseaux virtuels ou directs. +message.advanced.security.group=Choisissez ceci si vous souhaitez utiliser les groupes de sécurité pour fournir l\'isolation des VMs invitées. +message.advanced.virtual=Choisissez ceci si vous souhaitez utiliser des VLANs pour fournir l\'isolation des VMs invitées. +message.allow.vpn.access=Entrez un nom d\'utilisateur et un mot de passe pour l\'utilisateur que vous souhaitez autorisé à utiliser l\'accès VPN. +message.attach.iso.confirm=Confirmez que vous souhaitez attacher l\'image ISO à cette instance. +message.attach.volume=Renseignez les données suivante pour attacher un nouveau volume. Si vous attachez un volume disque à une machine virtuelle sous Windows, vous aurez besoin de redémarrer l\'instance pour voir le nouveau disque. +message.basic.mode.desc=Choisissez ce modèle de réseau si vous *ne voulez pas* activer le support des VLANs. Toutes les instances créées avec ce modèle de réseau se verront assignées une adresse IP et les groupes de sécurité seront utilisés pour fournir l\'isolation entre les VMs.\n +message.change.offering.confirm=Confirmez que vous souhaitez changer l\'offre de service de cette instance. +message.copy.iso.confirm=Confirmez que vous souhaitez copier votre image ISO vers +message.copy.template=Copier le modèle XXX de la zone vers +message.create.template.vm=Créer la VM depuis le modèle +message.create.template.volume=Renseignez les informations suivantes avec de créer un modèle à partir de votre volume de disque\:. La création du modèle peut prendre plusieurs minutes suivant la taille du volume. +message.delete.account=Confirmez que vous souhaitez supprimer ce compte. +message.detach.iso.confirm=Confirmez que vous souhaitez détacher l\'image ISO de cette instance. +# message.disable.account=Please confirm that you want to disable this account. By disabling the account, all users for this account will no longer have access to their cloud resources. All running virtual machines will be immediately shut down. +message.disable.vpn.access=Confirmez que vous souhaitez désactiver l\'accès VPN. +message.download.ISO=Cliquer le lien 00000 pour télécharger une image ISO +message.download.template=Cliquer le lien 00000 pour télécharger une template +message.download.volume=Cliquez sur 00000 pour télécharger le volume +message.edit.confirm=Confirmer les changement avant de cliquer sur "Enregistrer". +message.edit.limits=Renseignez les limites pour les ressources suivantes. "-1" indique qu\'il n\'y a pas de limites pour la création de ressources. +message.enable.account=Confirmez que vous souhaitez activer ce compte. +message.enable.vpn.access=Le VPN est désactivé pour cette adresse IP. Voulez vous activer l\'accès VPN ? +message.enabled.vpn.ip.sec=Votre clé partagée IPSec est +message.enabled.vpn=Votre accès VPN est activé et peut être accédé par l\'IP +message.launch.vm.on.private.network=Souhaitez vous démarrer cette instance sur votre propre réseau privé ? +message.lock.account=Confirmez que vous souhaitez verrouiller ce compte. En le verrouillant, les utilisateurs de ce compte ne seront plus capable de gérer leurs ressources. Les ressources existantes resteront toutefois accessibles. +message.migrate.instance.confirm=Confirmez l\'hôte vers lequel vous souhaitez migrer cette instance +message.new.user=Renseigner les informations suivantes pour ajouter un nouveau compte utilisateur +message.no.network.support.configuration.not.true=Il n\'y a pas de zone avec la fonction groupe de sécurité active. Dès lors, pas de fonction réseau supplémentaires disponibles. Continuer à l\'étape 5. +message.no.network.support=Sélectionnez l\'hyperviseur. vSphere, n\'a pas de fonctionnalités supplémentaires pour le réseau. Continuez à l\'étape 5. +message.number.clusters=

\# of Clusters

+message.number.hosts=

\# of Hôtes

+message.number.pods=

\# of Pods

+message.number.storage=

\# of Volumes de Stockage Primaire

+message.number.zones=

\# of Zones

+message.remove.vpn.access=Confirmez que vous souhaitez supprimer l\'accès VPN à l\'utilisateur suivant. +message.restart.mgmt.server=Redémarrez votre(vos) serveur(s) de management pour appliquer les nouveaux paramètres. +message.restart.mgmt.usage.server=Redémarrer le ou les management server et usage server pour que les nouveaux paramètres soient pris en compte. +message.security.group.usage=(Utilisez Ctrl-clic pour séléctionner les groupes de sécurité visés) +message.snapshot.schedule=Vous pouvez mettre en place les politiques de génération d\'instantanés en sélectionnant les options disponibles ci-dessous et en appliquant votre politique. +message.step.1.continue=Sélectionnez un modèle ou une image ISO pour continuer +message.step.1.desc=Sélectionnez un template pour votre nouvelle instance virtuelle. Vous pouvez également choisir un modèle vierge sur lequel une image ISO pourra être installé. +message.step.2.continue=Sélectionnez une offre de service pour continuer +message.step.2.desc= +message.step.3.continue=Sélectionnez un offre de service de disque pour continuer +message.step.3.desc= +message.step.4.continue=Sélectionnez au moins un réseau pour continuer +message.step.4.desc=Sélectionnez le réseau principal auquel votre instance va être connecté. +message.update.os.preference=Choisissez votre OS préféré pour cet hôte. Toutes les instances avec des préférences similaires seront d\'abord allouées à cet hôte avant d\'en choisir un autre. +message.update.ssl=Soumettez un nouveau certificat SSL compatible X.509 qui sera mis à jour sur l\'ensemble de instance de proxy console. +message.virtual.network.desc=Un réseau virtuel dédié pour votre compte. Ce domaine de broadcast est contenu dans un VLAN et l\'ensemble de accès réseau publique sont routés par un routeur virtuel. +message.volume.create.template.confirm=Confirmez que vous souhaitez créer un modèle pour ce disque. La création peut prendre plusieurs minutes, voire plus, selon la taille du volume. +message.zone.step.1.desc=Sélectionnez un modèle de réseau pour votre zone. +message.zone.step.2.desc=Renseigner les informations suivantes pour ajouter une nouvelle zone +message.zone.step.3.desc=Renseigner les informations suivantes pour ajouter un nouveau pod +message.apply.snapshot.policy=Vous avez mis à jour votre politique d\'instantanés avec succès. +message.disable.snapshot.policy=Vous avez désactivé votre politique de snapshots avec succès. +message.action.change.service.warning.for.instance=Votre instance doit être arrêtée avant d\'essayer de changer son offre de service. +message.action.change.service.warning.for.router=Votre routeur doit être arrêté avant d\'essayer de changer son offre de service. +message.action.reset.password.warning=Votre instance doit être arrêtée avant d\'essayer de changer son mot de passe. +message.action.reset.password.off=Votre instance ne supporte pas pour le moment cette fonctionnalité. + +#Errors +error.login=Votre nom d\'utilisateur /mot de passe ne correspond pas à nos données. +error.menu.select=Echec de l\'action car il n\'y a aucun élément sélectionné. +error.mgmt.server.inaccessible=Le serveur de management est indisponible. Essayez plus tard. +error.session.expired=Votre session a expiré. +error.unresolved.internet.name=Votre nom internet ne peut pas être résolu. 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 new file mode 100644 index 00000000000..3bc435b9717 --- /dev/null +++ b/client/WEB-INF/classes/resources/messages_pt_BR.properties @@ -0,0 +1,1512 @@ +# 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. + + +#new labels (begin) ********************************************************************************************** +# label.isolation.uri=Isolation URI +# label.broadcast.uri=Broadcast URI +#new labels (end) ************************************************************************************************ + + +#modified labels (begin) ***************************************************************************************** +# message.zoneWizard.enable.local.storage=WARNING\: If you enable local storage for this zone, you must do the following, depending on where you would like your system VMs to launch\:

1. If system VMs need to be launched in primary storage, primary storage needs to be added to the zone after creation. You must also start the zone in a disabled state.

2. If system VMs need to be launched in local storage, system.vm.use.local.storage needs to be set to true before you enable the zone.


Would you like to continue? +#modified labels (end) ******************************************************************************************* + +# label.configure.network.ACLs=Configure Network ACLs +# label.network.ACLs=Network ACLs +# label.add.network.ACL=Add network ACL +# label.private.Gateway=Private Gateway +# label.VPC.router.details=VPC router details +# label.VMs.in.tier=VMs in tier +# label.local.storage.enabled=Local storage enabled +# label.tier.details=Tier details +# label.edit.tags=Edit tags +label.action.enable.physical.network=Habilitar rede física +label.action.disable.physical.network=Desabilitar rede física +message.action.enable.physical.network=Por favor confirme que você deseja habilitar esta rede física. +message.action.disable.physical.network=Por favor confirme que você deseja desabilitar esta rede física. + +# label.select.tier=Select Tier +# label.add.ACL=Add ACL +# label.remove.ACL=Remove ACL +# label.tier=Tier +# label.network.ACL=Network ACL +# label.network.ACL.total=Network ACL Total +# label.add.new.gateway=Add new gateway +# message.add.new.gateway.to.vpc=Please specify the information to add a new gateway to this VPC. +# label.delete.gateway=delete gateway +# message.delete.gateway=Please confirm you want to delete the gateway +# label.CIDR.of.destination.network=CIDR of destination network +# label.add.route=Add route +# label.add.static.route=Add static route +# label.remove.static.route=Remove static route +# label.site.to.site.VPN=site-to-site VPN +# label.add.VPN.gateway=Add VPN Gateway +# message.add.VPN.gateway=Please confirm that you want to add a VPN Gateway +# label.VPN.gateway=VPN Gateway +# label.delete.VPN.gateway=delete VPN Gateway +# message.delete.VPN.gateway=Please confirm that you want to delete this VPN Gateway +# label.VPN.connection=VPN Connection +# label.IPsec.preshared.key=IPsec Preshared-Key +# label.IKE.policy=IKE policy +# label.ESP.policy=ESP policy +# label.create.VPN.connection=Create VPN Connection +# label.VPN.customer.gateway=VPN Customer Gateway +# label.CIDR.list=CIDR list +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.reset.VPN.connection=Reset VPN connection +# message.reset.VPN.connection=Please confirm that you want to reset VPN connection +# label.delete.VPN.connection=delete VPN connection +# message.delete.VPN.connection=Please confirm that you want to delete VPN connection +# label.add.new.tier=Add new tier +# label.add.VM.to.tier=Add VM to tier +# label.remove.tier=Remove tier + +# label.local.storage.enabled=Local storage enabled +# label.associated.network=Associated Network +# label.add.port.forwarding.rule=Add port forwarding rule +# label.dns=DNS + +# label.vpc=VPC +# label.vpc.id=VPC ID +# label.tier=Tier +# label.add.vpc=Add VPC +# label.super.cidr.for.guest.networks=Super CIDR for Guest Networks +# label.DNS.domain.for.guest.networks=DNS domain for Guest Networks +# label.configure.vpc=Configure VPC +# label.edit.vpc=Edit VPC +# label.restart.vpc=restart VPC +# message.restart.vpc=Please confirm that you want to restart the VPC +# label.remove.vpc=remove VPC +# message.remove.vpc=Please confirm that you want to remove the VPC +# label.vpn.customer.gateway=VPN Customer Gateway +# label.add.vpn.customer.gateway=Add VPN Customer Gateway +# label.IKE.encryption=IKE Encryption +# label.IKE.hash=IKE Hash +# label.IKE.DH=IKE DH +# label.ESP.encryption=ESP Encryption +# label.ESP.hash=ESP Hash +# label.perfect.forward.secrecy=Perfect Forward Secrecy +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.delete.VPN.customer.gateway=delete VPN Customer Gateway +# message.delete.VPN.customer.gateway=Please confirm that you want to delete this VPN Customer Gateway + +label.network.domain.text=Texto do domínio de rede +label.memory.mb=Memória +label.cpu.mhz=CPU (em MHz) + +message.action.remove.host=Remover o único/último host do cluster e reinstalar o host irá provocar a perda do ambiente/banco do host tornando os Cloud Servers inutilizáveis. + +message.action.reboot.router=Confirme que você deseja reiniciar este roteador. +message.action.stop.router=Confirme que você deseja parar este roteador. +message.restart.network=Por favor confirme que você deseja reiniciar a rede + + +label.ipaddress=Endereço IP +label.vcdcname=Nome do vCenter DC +label.vcipaddress=Endereço IP do vCenter +label.vsmctrlvlanid=Control VLAN ID +label.vsmpktvlanid=Packet VLAN ID +label.vsmstoragevlanid=Storage VLAN ID +label.nexusVswitch=Nexus Vswitch +label.action.delete.nexusVswitch=Remover NexusVswitch +label.action.enable.nexusVswitch=Habilitar NexusVswitch +label.action.disable.nexusVswitch=Desabilitar NexusVswitch +label.action.list.nexusVswitch=Listar NexusVswitch +message.action.delete.nexusVswitch=Por favor confirme que você deseja remover este nexusVswitch. +message.action.enable.nexusVswitch=Por favor confirme que você deseja habilitar este nexusVswitch. +message.action.disable.nexusVswitch=Por favor confirme que você deseja desabilitar este nexusVswitch +message.specify.url=Por favor especifique a URL +label.select.instance.to.attach.volume.to=Escolha uma instância para conectar o volume +label.upload=Enviar +label.upload.volume=Enviar o Volume +label.virtual.routers=Roteadores Virtuais +label.primary.storage.count=Pools de Storage Primários +label.secondary.storage.count=Pools de Storage secundários +label.number.of.system.vms=Número de VMs de sistema +label.number.of.virtual.routers=Número de Roteadores Virtuais +label.action.register.iso=Registrar ISO +label.isolation.method=Método de isolação +label.action.register.template=Registrar template +label.checksum=MD5 checksum +label.vpn=VPN +label.vlan=VLAN + + +label.management.ips=Gerenciamento de Endereços IP +label.devices=Dispositivos +label.rules=Regras +# label.traffic.label=Traffic label +label.vm.state=Estado da VM +message.setup.physical.network.during.zone.creation.basic=Quando adicionar uma zona básica, você pode configurar uma rede física, que corresponde a uma NIC no hypervisor. A rede carrega diversos tipos de tráfego.

Você pode adicionar e remover outros tipos de tráfego na mesma interface de rede física. +label.domain.router=Roteador do Domínio +label.console.proxy=Console proxy +label.secondary.storage.vm=VM de storage secundário +label.add.netScaler.device=Adicionar dispositivo Netscaler +label.add.F5.device=Adicionar dispositivo F5 +label.add.SRX.device=Adicionar dispositivo SRX +label.account.and.security.group=Contas, grupos de Segurança +label.fetch.latest=Obter últimos +label.system.offering=Ofertas de Sistema +message.validate.instance.name=Nomes de instâncias não podem ter mais de 63 caracteres. Somente letras ASCII a~z, A~Z, dígitos 0~9 e hífen são permitidos. Deve começar com uma letra e terminar com uma letra ou dígito. + + +label.isolated.networks=Redes Isoladas +label.latest.events=Últimos eventos +state.Enabled=Habilitado +label.system.wide.capacity=Capacidade Total do Sistema +label.network.service.providers=Provedores de Serviços de Rede +message.launch.zone=A zona está pronta para ser executada; por favor continue para o próximo passo. +error.unable.to.reach.management.server=Não foi possível acessar o Servidor de Gerenciamento +label.internal.name=Nome interno +# message.configure.all.traffic.types=You have multiple physical networks; please configure labels for each traffic type by clicking on the Edit button. +# message.edit.traffic.type=Please specify the traffic label you want associated with this traffic type. +label.edit.traffic.type=Editar tipo de tráfego +# label.label=Label +label.max.networks=Máx. de redes +error.invalid.username.password=Usuário ou senha inválidos +message.enabling.security.group.provider=Habilitar provider de grupo de segurança +message.adding.Netscaler.provider=Adicionando Netscaler provider +message.creating.guest.network=Criando rede guest +label.action.delete.physical.network=Deletar rede física +message.action.delete.physical.network=Por favor confirme que você deseja deletar esta rede física +message.installWizard.copy.whatIsAHost=Um host é um único computador. Os Hosts provêem os recursos computacionais para executar as máquinas virtuais. Cada host possuí o software do hypervisor instalado nele para gerenciar as guest VMs (Exceto os hosts bare metal, que são um caso especial discutido no Guia Avançado de Instalação). Por exemplo, um servidor Linux com KVM habilitado, um servidor Citrix XenServer e um servidor ESXi são hosts. Na Instalação Básica, nós utilizamos um único host rodando XenServer ou KVM.

O host é a menor unidade organizacional dentro de uma instalação CloudStack&\#8482; . Hosts estão contidos dentro de Clusters, clusters estão contidos dentro de pods e pods estão contidos dentro de zonas. + + +label.add.compute.offering=Adicionar oferta de computação +label.compute.offering=Oferta de Computação +label.compute.offerings=Ofertas de Computação +label.select.offering=Selecionar Oferta +label.menu.infrastructure=Infra-estrutura +label.sticky.tablesize=Tamanho da Tabela +label.sticky.expire=Expires +label.sticky.cookie-name=Nome do Cookie +label.sticky.mode=Modo +label.sticky.length=Tamanho +label.sticky.holdtime=Tempo de espera +# label.sticky.request-learn=Request learn +label.sticky.prefix=Prefixo +label.sticky.nocache=Sem Cache +label.sticky.indirect=Indireto +# label.sticky.postonly=Post only +label.sticky.domain=Domínio +state.Allocating=Alocando +state.Migrating=Migrando +error.please.specify.physical.network.tags=Ofertas de Rede não estarão disponíveis enquanto você não especificar tags para esta interface física. + + +state.Stopping=Parando +message.add.load.balancer.under.ip=A regra do balanceador de carga foi adicionada para o IP\: +message.select.instance=Por favor selecione uma instância. +label.select=Selecionar +label.select.vm.for.static.nat=Selecionar VM para NAT estático +label.select.instance=Selecionar instância +label.nat.port.range=Range de Portas NAT +label.static.nat.vm.details=Detalhes de NAT estático da VM +label.edit.lb.rule=Editar regra de LB +message.migrate.instance.to.host=Por favor confirme que você deseja migrar a instância para outro host. +label.migrate.instance.to.host=Migrar instância para outro host +message.migrate.instance.to.ps=Por favor confirme que você deseja migrar a instância para outro storage primário. +label.migrate.instance.to.ps=Migrar instância para outro storage primário +label.corrections.saved=Alterações salvas +message.installWizard.copy.whatIsSecondaryStorage=O storage secundário está associado a uma zona, ele é responsável por armazenar o seguinte\:
  • Imagens de Templates do SO - que podem ser utilizadas para boot das VMs e podem incluir configurações adicionais, como por exemplo as aplicações instaladas
  • Imagens ISO - Imagens de sistema operacional que podem ser bootáveis ou não
  • Snapshots do volume de discos - cópias salvas dos dados de uma VM que pode ser utilizada para recuperação de dados ou criação de novos templates
+message.installWizard.copy.whatIsPrimaryStorage=Uma infraestrutura de Cloud CloudStack&\#8482; utiliza dois tipos de storage\: storage primário e storage secundário. Ambos os tipos podem ser iSCSI, NFS servers, ou disco local.

O Storage primário está associado com um cluster, e armazena os volumes de disco de cada guest VM para todas as VMs em execução nos hosts deste cluster. O servidor de storage primário tipicamente encontra-se localizado perto dos hosts. +message.installWizard.copy.whatIsACluster=Um cluster provê uma maneira de agrupar hosts. Os hosts em um cluster tem hardware idêntico, rodam o mesmo hypervisor, estão na mesma subnet, acessam o mesmo storage compartilhado. Instâncias de máquinas virtuais (VMs) podem ser migradas a quente - live migration - de um host para outro host no mesmo cluster, sem interromper o serviço para o usuário. Um Cluster é a terceira maior unidade organizacional em uma instalação CloudStack&\#8482; . Clusters estão contidos em pods e pods estão contidos em zonas.

O CloudStack&\#8482; permite múltiplos clusters em uma mesma cloud, entretanto para a instalação básica, nós iremos precisar apenas de um cluster. +message.installWizard.copy.whatIsAPod=Um pod normalmente representa um único rack. Hosts no mesmo pod estão na mesma subrede.

Um pod é a segunda maior unidade organizacional de uma instalação CloudStack&\#8482; . Pods estão contidos dentro de zonas. Cada zona, pode conter um ou mais pods; Na instalação básica, você irá ter apenas um pod na sua zona. +message.installWizard.copy.whatIsAZone=Uma zona é a maior unidade organizacional em uma instalação CloudStack&\#8482; . Uma zona tipicamente corresponde a um único datacenter, apesar de ser possível ter múltiplas zonas no mesmo datacenter. O benefício de se organizar a infra-estrutura em zonas é permitir o isolamento físico e redundância. Por exemplo, cada zona pode possuir sua própria alimentação de energia e link de saída de internet e zonas podem estar geograficamente separadas (apesar de não ser obrigatório). +message.installWizard.copy.whatIsCloudStack=O CloudStack&\#8482 é uma plataforma de software que agrega recursos computacionais para construir uma Cloud de Infra-estrutura como Serviço (IaaS) pública, privada ou híbrida. O CloudStack&\#8482 gerência a rede, o storage e os recursos computacionais que compõem a infra-estrutura de cloud. Utilize o CloudStack&\#8482 para instalar, gerenciar e configurar os ambientes de cloud computing.

Indo além de imagens de máquinas virtuais individuais rodando em hardware commodity, CloudStack&\#8482 provê uma solução completa de software de infra-estrutura de cloud para entregar datacenters virtuais como um serviço - possuindo todos os componentes essenciais para contruir, instalar e gerenciar aplicações na cloud multi-camadas e multi-tenant. Ambas as versões open-source e premium estão disponíveis, com a versão opensource oferecendo praticamente os mesmos recursos. +message.installWizard.tooltip.addSecondaryStorage.path=Path exportado, localizado no servidor que você especificou acima +message.installWizard.tooltip.addSecondaryStorage.nfsServer=O endereço IP do servidor NFS hospedando o storage secundário +message.installWizard.tooltip.addPrimaryStorage.path=(para NFS) No NFS este é o path exportado pelo servidor. Path (para SharedMountPoint). Com o KVM este é o path em cada host onde o storage primário está montado. Por exemplo, "/mnt/primary". +message.installWizard.tooltip.addPrimaryStorage.server=(para NFS, iSCSI ou PreSetup) O Endereço IP ou nome DNS do dispositivo de storage. +message.installWizard.tooltip.addPrimaryStorage.name=O Nome do dispositivo de storage. +message.installWizard.tooltip.addHost.password=Este é a senha do usuário especificado acima (da sua instalação do XenServer) +message.installWizard.tooltip.addHost.username=Usualmente root. +message.installWizard.tooltip.addHost.hostname=O nome DNS ou endereço IP do host. +message.installWizard.tooltip.addCluster.name=Um nome para o cluster. Este nome pode ser um nome de sua escolha e não é usado pelo CloudStack. +message.installWizard.tooltip.addPod.reservedSystemEndIp=Este é o range de IP na rede privada que o CloudStack utiliza para gerenciar o storage secundário das VMs e Proxy Console das VMs. Estes endereços IP são obtidos da mesma subrede dos servidores hosts. +message.installWizard.tooltip.addPod.reservedSystemStartIp=Este é o range de IP na rede privada que o CloudStack utiliza para gerenciar as VMs de storage secundário e as VMs de Console Proxy. Estes endereços IP devem estar na mesma subnet dos servidores de processamento. +message.installWizard.tooltip.addPod.reservedSystemNetmask=A máscara de rede está em uso na subrede que os guests irão utilizar. +message.installWizard.tooltip.addPod.reservedSystemGateway=O gateway para os hosts neste pod. +message.installWizard.tooltip.addPod.name=O nome para o pod +message.installWizard.tooltip.configureGuestTraffic.guestEndIp=O range de endereços IP que estará disponível para alocação para os guests nesta zona. Caso uma NIC seja utilizada, estes IPs devem estar no mesmo CIDR que o CIDR do pod. +message.installWizard.tooltip.configureGuestTraffic.guestStartIp=O range de endereços IP que estará disponível para alocação para os guests nesta zona. Caso uma NIC seja utilizada, estes IPs devem estar no mesmo CIDR que o CIDR do pod. +message.installWizard.tooltip.configureGuestTraffic.guestNetmask=A máscara de rede da subrede que os guests devem usar +message.installWizard.tooltip.configureGuestTraffic.guestGateway=O gateway que os guests devem usar +message.installWizard.tooltip.configureGuestTraffic.description=Uma descrição da sua rede +message.installWizard.tooltip.configureGuestTraffic.name=Um nome para sua rede +message.installWizard.tooltip.addZone.internaldns2=Estes são os servidores DNS utilizados pelas VMs de sistema nesta zona. Estes servidores DNS serão acessados através da interface de rede privada das VMs de sistema. O endereço IP privado que você configurar para os pods deve possuir uma rota para os servidores DNS configurados aqui. +message.installWizard.tooltip.addZone.internaldns1=Estes são os servidores DNS utilizados pelas VMs de sistema nesta zona. Estes servidores DNS serão acessados através da interface de rede privada das VMs de sistema. O endereço IP privado que você configurar para os pods deve possuir uma rota para os servidores DNS configurados aqui. +message.installWizard.tooltip.addZone.dns2=Estes são os servidores DNS utilizados pelas VMs convidadas nesta zona. Estes servidores DNS serão acessados pela interface de rede pública que você irá adicionar posteriormente. O endereço IP público de uma zona deve possuir uma rota para os servidores DNS configurados aqui. +message.installWizard.tooltip.addZone.name=Um nome para a zona +message.installWizard.tooltip.addZone.dns1=Estes são os servidores DNS utilizados pelas guest VMs na zona. Estes servidores DNS serão acessados pela interface de rede pública que você irá adicionar posteriormente. O endereço IP público da zona deve possuir uma rota para os servidores DNS configurados aqui. +message.setup.successful=Cloud configurada com sucesso\! +label.may.continue=Você pode continuar agora +error.installWizard.message=Alguma coisa está errada; você pode voltar e corrigir quaisquer erros +message.installWizard.now.building=Construindo sua cloud agora... +message.installWizard.click.retry=Click no botão para tentar executar novamente. +label.launch=Executar +label.installWizard.click.launch=Click no botão executar. +label.congratulations=Parabéns\! +label.installWizard.addSecondaryStorageIntro.subtitle=Qual é o storage secundário ? +label.installWizard.addSecondaryStorageIntro.title=Vamos adicionar o storage secundário +label.installWizard.addPrimaryStorageIntro.subtitle=Qual é o storage primário ? +label.installWizard.addPrimaryStorageIntro.title=Vamos adicionar o storage primário +label.installWizard.addHostIntro.subtitle=O que é um Host ? +label.installWizard.addHostIntro.title=Vamos adicionar um host +label.installWizard.addClusterIntro.subtitle=O que é um cluster? +label.installWizard.addClusterIntro.title=Vamos adicionar um cluster +label.installWizard.addPodIntro.subtitle=O que é um pod ? +label.installWizard.addPodIntro.title=Vamos adicionar um pod +label.installWizard.addZone.title=Adicionar zona +label.installWizard.addZoneIntro.subtitle=O que é uma zona? +label.installWizard.addZoneIntro.title=Vamos adicionar uma zona +error.password.not.match=Os campos de senha não combinam +label.confirm.password=Confirme a senha +message.change.password=Por favor, troque sua senha. +label.save.and.continue=Salvar e continuar +label.skip.guide=Eu utilizei o CloudStack antes, pular este guia +label.continue.basic.install=Continuar com a instalação básica +label.introduction.to.cloudstack=Introdução ao CloudStack&\#8482 +label.what.is.cloudstack=O que é o CloudStack&\#8482? +label.hints=Dicas +label.installWizard.subtitle=Este tour vai auxiliar você na configuração da sua instalação de CloudStack&\#8482 +label.continue=Continuar +label.installWizard.title=Olá, seja bem vindo ao CloudStack&\#8482 +label.agree=Concordo +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 +label.networking.and.security=Rede e segurança +label.bandwidth=Bandwidth +label.virtual.machines=Máquinas virtuais +label.compute.and.storage=Processamento e Armazenamento +label.task.completed=Tarefa completa +label.update.project.resources=Atualizar recursos de projeto +label.remove.project.account=Remover conta de projeto +label.item.listing=Listar items +message.select.item=Por favor selecione um item. +label.removing=Removendo +label.invite=Convidar +label.add.by=Adicionado por +label.max.vms=Máx. VMs de usuário +label.max.public.ips=Máx. IPs públicos +label.max.volumes=Máx. volumes +label.max.snapshots=Max. snapshots +label.max.templates=Máx. templates +# label.max.vpcs=Max. VPCs +label.project.dashboard=Dashboard do Projeto +label.remind.later=Me lembre depois +label.invited.accounts=Contas convidadas +label.invite.to=Convidar para +label.add.accounts.to=Adicionar contas para +label.add.accounts=Adicionar contas +label.project.name=Nome de projeto +label.create.project=Criar um projeto +label.networks=Redes +label.launch.vm=Executar VM +label.new.vm=Nova VM +label.previous=Anterior +label.add.to.group=Adicionar ao grupo +message.vm.review.launch=Por favor revise a informação abaixo e confirme que sua instância virtual está correta antes de executa-la. +message.select.security.groups=Por favor selecione o(s) grupo(s) de segurança para sua nova VM +label.new=Novo +message.please.select.networks=Por favor selecione as redes para sua máquina virtual. +message.please.proceed=Por favor continue para o próximo passo. +message.zone.no.network.selection=A zona que você selecionou não possui nenhuma rede para ser escolhida. +label.no.thanks=Não obrigado +label.my.templates=Meus templates +message.select.template=Por favor selecione um template para sua nova instância virtual. +message.select.iso=Por favor selecione um ISO para sua nova instância virtual +message.template.desc=Imagem de SO que pode ser utilizada para bootar VMs +message.iso.desc=Imagem de disco contendo dados ou mídia de sistema operacional bootável +label.select.iso.or.template=Selecione ISO ou template +message.select.a.zone=A zone tipicamente corresponde a um único datacenter. Múltiplas zonas auxiliam a cloud a ser mais confiável provendo isolamento físico e redundância. +label.select.a.zone=Selecione uma zona +label.review=Revisar +label.select.a.template=Selecione um template +label.setup=Configuração +state.Allocated=Alocado +changed.item.properties=Alteradas propriedades do item +label.apply=Aplicar +label.default=Padrão +label.viewing=Visualizar +label.move.to.top=Mover para o topo +label.move.up.row=Mover uma célula para cima +label.move.down.row=Mover uma célula para baixo +# label.move.to.bottom=Move to bottom +label.drag.new.position=Arrastar para uma nova posição +label.order=Ordenar +label.no.data=Sem dados para mostrar +label.change.value=Alterar valor +label.clear.list=Limpar lista +label.full.path=Path completo +message.add.domain=Por favor especifique o subdomínio que você deseja criar neste domínio +message.delete.user=Por favor confirme que você deseja deletar este usuário. +message.enable.user=Por favor confirme que você deseja habilitar este usuário. +message.disable.user=Por favor confirme que você deseja desabilitar este usuário. +message.generate.keys=Por favor confirme que você deseja gerar novas chaves para este usuário. +message.update.resource.count=Por favor confirme que você quer atualizar a contagem de recursos para esta conta. +message.edit.account=Editar ("-1" indica que não haverá limites para a quantidade de recursos criado) +label.total.of.vm=Total de VM +label.total.of.ip=Total de endereços IP +state.enabled=Habilitado +message.action.download.iso=Por favor confirme que você deseja baixar esta ISO. +message.action.download.template=Por favor confirme que você deseja baixar este template. +label.destination.zone=Zona de Destino +label.keyboard.type=Tipo de Teclado +label.nic.adapter.type=Tipo de adaptador NIC +label.root.disk.controller=Controlador do disco Root +label.community=Comunidade +label.remove.egress.rule=Remover regra egress +label.add.egress.rule=Adicionar regra egress +label.egress.rule=Regra Egress +label.remove.ingress.rule=Remover regra ingress +label.delete.vpn.user=Deletar usuário VPN +label.add.vpn.user=Adicionar usuário VPN +label.remove.pf=Remover regra de redirecionamento de porta +label.remove.vm.from.lb=Remover VM da regra de balanceamento de carga +label.add.vms.to.lb=Add VM(s) na regra de balanceamento de carga +label.add.vm=Adicionar VM +label.remove.static.nat.rule=Remover regra de NAT estático +label.remove.rule=Remover regra +label.add.static.nat.rule=Adicionar regra de NAT estático +label.add.rule=Adicionar regra +label.configuration=Configuração +message.disable.vpn=Você tem certeza que deseja desabilitar a VPN? +label.disable.vpn=Desabilitar VPN +message.enable.vpn=Por favor confirme que você deseja acesso VPN habilitado para este endereço IP. +label.enable.vpn=Habilitar VPN +message.acquire.new.ip=Por favor confirme que você gostaria de adquirir um novo IP para esta rede. +label.elastic=Elástico +label.my.network=Minha rede +label.add.vms=Adicionar VMs +label.configure=Configurar +# label.stickiness=Stickiness +label.source=Origem +label.least.connections=Least connections +label.round.robin=Round-robin +label.restart.required=Reiniciar obrigatório +label.clean.up=Limpar +label.restart.network=Reiniciar rede +label.edit.network.details=Editar detalhes de rede +label.add.guest.network=Adicionar rede guest +label.guest.networks=Redes Guest +message.ip.address.changed=Seu endereço IP pode ter mudado; você gostaria de atualizar a listagem ? Note que neste caso o painel de detalhes irá fechar. +# state.BackingUp=Backing Up +# state.BackedUp=Backed Up +label.done=Pronto +label.vm.name=Nome da VM +message.migrate.volume=Por favor confirme que você deseja migrar o volume para outro storage primário. +label.migrate.volume=Migrar volume para outro storage primário +message.create.template=Você tem certeza que deseja criar um template ? +label.create.template=Criar template +message.download.volume.confirm=Por favor confirme que você quer baixar este volume +message.detach.disk=Você tem certeza que deseja desconectar este disco ? +state.ready=Pronto +state.Ready=Pronto +label.vm.display.name=Nome de exibição da VM +label.select-view=Selecionar visualização +label.local.storage=Storage Local +label.direct.ips=IPs Diretos +label.view.all=Visualizar tudo +label.zone.details=Detalhes de zona +message.alert.state.detected=Alerta de estado detectado +state.Starting=Iniciando +# state.Expunging=Expunging +state.Creating=Criando +message.decline.invitation=Você tem certeza que quer rejeitar este convite de projeto ? +label.decline.invitation=Rejeitar convite +message.confirm.join.project=Por favor confirme que você deseja entrar neste projeto +message.join.project=Você agora entrou em um projeto. Por favor troque para a visão de Projeto para visualizar o projeto. +label.accept.project.invitation=Aceitar convite de projeto. +label.token=Token +label.project.id=ID de Projeto +message.enter.token=Por favor entre o token que você recebeu no e-mail privado. +label.enter.token=Digite o token +state.Accepted=Aceito +state.Pending=Pendente +state.Completed=Completo +state.Declined=Recusado +label.project=Projeto +label.invitations=Convites +label.delete.project=Deletar projeto +message.delete.project=Você tem certeza que deseja deletar este projeto ? +message.activate.project=Você tem certeza que deseja ativar este projeto ? +label.activate.project=Ativar Projeto +label.suspend.project=Suspender Projeto +message.suspend.project=Você tem certeza que deseja suspender este projeto ? +state.Suspended=Suspendido +label.edit.project.details=Editar detalhes do projeto +label.new.project=Novo Projeto +state.Active=Ativo +state.Disabled=Desativado +label.projects=Projetos +label.make.project.owner=Criar proprietário de conta de projeto +label.remove.project.account=Remover conta de projeto +message.project.invite.sent=Convite enviado para o usuário; Eles serão adicionados ao projeto após aceitarem o convite +label.add.account.to.project=Adicionar conta ao projeto +label.revoke.project.invite=Revogar convite +label.project.invite=Convidar para o projeto +label.select.project=Selecionar Projeto +message.no.projects=Você não possui nenhum projeto.
Por favor crie um novo projeto à partir da seção Projetos. +message.no.projects.adminOnly=Você não possui nenhum projeto.
Por favor solicite ao seu administrador a criação de um novo projeto. +message.pending.projects.1=Você possui convites de projetos pendentes\: +message.pending.projects.2=Para visualizar, por favor acesse a seção de projetos, depois selecione os convites no menu drop-down. +message.instanceWizard.noTemplates=Você não possui nenhum template disponível; por favor adicione um template compatível e reinicie o wizard de instância. +label.view=Visualizar +instances.actions.reboot.label=Reiniciar instância +label.filterBy=Filtrar por +label.ok=OK +notification.reboot.instance=Reiniciar instância +notification.start.instance=Iniciar instãncia +notification.stop.instance=Parar instância +label.display.name=Nome de exibição +label.zone.name=Nome da zona +ui.listView.filters.all=Todos +ui.listView.filters.mine=Meus +state.Running=Executando +state.Stopped=Parado +state.Destroyed=Destruído +state.Error=Erro +message.reset.password.warning.notPasswordEnabled=O template desta instância foi criado sem senha habilitada +message.reset.password.warning.notStopped=Sua instância deve estar parada antes de tentar trocar sua senha atual +label.notifications=Notificações +label.default.view=Visão Padrão +label.project.view=Visão de Projeto + +message.add.system.service.offering=Por favor preencha os dados abaixo para adicionar uma nova oferta de serviço de sistema. +message.action.delete.system.service.offering=Por favor confirme que você deseja deletar esta oferta de serviço de sistema. +label.action.delete.system.service.offering=Deletar Oferta de Serviço de Sistema +label.hypervisor.capabilities=Recursos de Virtualizador +label.hypervisor.version=Versão de Virtualizador +label.max.guest.limit=Limite máx. de guest +label.add.network.offering=Adicionar oferta de rede +label.supported.services=Serviços Suportados +label.service.capabilities=Recursos de serviços +label.guest.type=Tipo de Guest +label.specify.IP.ranges=Especifique range de IP +# label.conserve.mode=Conserve mode +label.created.by.system=Criado pelo sistema +label.menu.system.service.offerings=Ofertas do Sistema +label.add.system.service.offering=Adicionar Plano para VM de Sistema +label.redundant.router.capability=Recurso de roteador redundante +label.supported.source.NAT.type=Tipo de Source NAT Suportado +label.elastic.LB=LB Elástico +label.LB.isolation=Isolamento de LB +label.elastic.IP=IP Elástico +label.network.label.display.for.blank.value=Utilizar gateway default +label.xen.traffic.label=Etiqueta de tráfego XenServer +label.kvm.traffic.label=Etiqueta de tráfego KVM +label.vmware.traffic.label=Etiqueta de tráfego VMware +label.start.IP=IP do início +label.end.IP=IP do fim +label.remove.ip.range=Remover range de IP +label.ip.ranges=Ranges de IP +label.start.vlan=Vlan do início +label.end.vlan=Vlan do fim +label.broadcast.domain.range=Range do domínio de Broadcast +# label.compute=Compute +message.add.guest.network=Por favor confirme que você gostaria de adicionar uma rede guest. +label.subdomain.access=Acesso ao subdomínio +label.guest.start.ip=IP de início do guest +label.guest.end.ip=IP do fim do guest +label.virtual.router=Roteador Virtual +label.physical.network.ID=ID da rede física +label.destination.physical.network.id=ID de destino da rede física +label.dhcp=DHCP +label.destroy.router=Destruir roteador +message.confirm.destroy.router=Por favor confirme que você gostaria de destruir este roteador +label.change.service.offering=Alterar oferta de serviço +label.view.console=Visualizar Console +# label.redundant.state=Redundant state +label.enable.provider=Habilitar provider +message.confirm.enable.provider=Por favor confirme que você gostaria de habilitar este provider +label.disable.provider=Desabilitar Provider +message.confirm.disable.provider=Por favor confirme que você gostaria de desabilitar este provider +# label.shutdown.provider=Shutdown provider +message.confirm.shutdown.provider=Por favor confirme que você deseja desligar este provider +label.netScaler=NetScaler +label.add.new.NetScaler=Adicionar um novo NetScaler +label.capacity=Capacidade +label.dedicated=Dedicado +label.f5=F5 +label.add.new.F5=Adicionar um novo F5 +label.srx=SRX +label.providers=Providers +label.add.new.SRX=Adicionar um novo SRX +label.timeout=Timeout +label.public.network=Rede Pública +label.private.network=Rede Privada +label.enable.swift=Habilitar Swift +confirm.enable.swift=Por favor preencha as informações abaixo para habilitar suporte ao Swift +message.after.enable.swift=Swift Configurado. Nota\: Após deixar esta página, você não será capaz de reconfigurar o Swift novamente. +label.key=Chave +label.delete.NetScaler=Remover NetScaler +message.confirm.delete.NetScaler=Por favor confirme que você deseja remover o NetScaler +label.delete.F5=Remover F5 +message.confirm.delete.F5=Por favor confirme que você deseja remover o F5 +label.delete.SRX=Remover SRX +message.confirm.delete.SRX=Por favor confirme que você deseja remover o SRX +label.pods=Pods +label.pod.name=Nome do Pod +label.reserved.system.gateway=Gateway de sistema reservado +label.reserved.system.netmask=Máscara de rede do sistema reservado +label.start.reserved.system.IP=Início dos IPs reservados para o sistema +label.end.reserved.system.IP=Fim dos IPs reservados para o sistema +label.clusters=Clusters +label.cluster.name=Nome do Cluster +label.host.MAC=Host MAC +label.agent.username=Usuário do Agente +label.agent.password=Senha do Agente +message.confirm.action.force.reconnect=Por favor confirme que você deseja forçar a reconexão com este host. +label.resource.state=Estado do Recurso +label.LUN.number=LUN \# +message.confirm.remove.IP.range=Por favor confirme que você deseja remover este range de IP. +message.tooltip.zone.name=Um nome para a zona. +# message.tooltip.dns.1=Name of a DNS server for use by VMs in the zone. The public IP addresses for the zone must have a route to this server. +message.tooltip.dns.2=Um servidor DNS secundário para ser utilizado pelas VMs nesta zona. Os endereços IP públicos nesta zona devem ter rota para este servidor. +message.tooltip.internal.dns.1=Nome de um servidor DNS que será utilizado pelas VMs internas de sistema do CloudStack nesta zona. Os endereços privados dos pods devem ter uma rota para este servidor. +message.tooltip.internal.dns.2=Nome de um servidor DNS que será utilizado pelas VMs internas de sistema do CloudStack nesta zona. Os endereços privados dos pods devem ter uma rota para este servidor. +message.tooltip.network.domain=Um sufixo DNS que irá criar um nome de domínio customizado para a rede que é acessada pelas guest VMs. +message.tooltip.pod.name=Um nome para este pod. +message.tooltip.reserved.system.gateway=O gateway para os hosts neste pod. +message.tooltip.reserved.system.netmask=O prefixo de rede que define a subrede deste pod. Utilize a notação CIDR. +message.creating.zone=Criando zona. +message.creating.physical.networks=Criando redes fisicas +message.configuring.physical.networks=Configurando redes físicas +message.adding.Netscaler.device=Adicionando dispositivo Nescaler +message.creating.pod=Criando pod +message.configuring.public.traffic=Configurando tráfego público +message.configuring.storage.traffic=Configurando tráfego de storage +message.configuring.guest.traffic=Configurando tráfego do guest +message.creating.cluster=Criando cluster +message.adding.host=Adicionando host +message.creating.primary.storage=Criando storage primário +message.creating.secondary.storage=Criando storage secundário +message.Zone.creation.complete=Criação de zona completa +message.enabling.zone=Habilitando zona +error.something.went.wrong.please.correct.the.following=Algo deu errado; por favor corrija abaixo +error.could.not.enable.zone=Não foi possível habilitar a zona +message.zone.creation.complete.would.you.like.to.enable.this.zone=Criação de zona completa. Você gostaria de habilitar esta zona? +message.please.add.at.lease.one.traffic.range=Por favor adicione pelo menos um range de tráfego. +message.you.must.have.at.least.one.physical.network=Você deve ter pelo menos uma rede física +message.please.select.a.different.public.and.management.network.before.removing=Por favor selecione uma rede pública e de gerenciamento diferente antes de remover + +label.zone.type=Tipo de Zona +label.setup.zone=Configurar Zona +label.setup.network=Configurar Rede +label.add.resources=Adicionar Recursos +label.launch=Executar +label.set.up.zone.type=Configurar tipo de zona +message.please.select.a.configuration.for.your.zone=Por favor selecione uma configuracao para sua zona. +# message.desc.basic.zone=Provide a single network where each VM instance is assigned an IP directly from the network. Guest isolation can be provided through layer-3 means such as security groups (IP address source filtering). +label.basic=Básico +# message.desc.advanced.zone=For more sophisticated network topologies. This network model provides the most flexibility in defining guest networks and providing custom network offerings such as firewall, VPN, or load balancer support. +label.advanced=Avançado +# message.desc.zone=A zone is the largest organizational unit in CloudStack, and it typically corresponds to a single datacenter. Zones provide physical isolation and redundancy. A zone consists of one or more pods (each of which contains hosts and primary storage servers) and a secondary storage server which is shared by all pods in the zone. +label.physical.network=Rede Física +label.public.traffic=Tráfego Público +label.guest.traffic=Tráfego do guest +label.storage.traffic=Tráfego do Storage +# message.setup.physical.network.during.zone.creation=When adding an advanced zone, you need to set up one or more physical networks. Each network corresponds to a NIC on the hypervisor. Each physical network can carry one or more types of traffic, with certain restrictions on how they may be combined.

Drag and drop one or more traffic types onto each physical network. +label.add.physical.network=Adicionar rede física +label.traffic.types=Tipos de Tráfego +label.management=Gerenciamento +label.guest=Guest +label.please.specify.netscaler.info=Por favor especifique as informações do Netscaler +# message.public.traffic.in.advanced.zone=Public traffic is generated when VMs in the cloud access the internet. Publicly-accessible IPs must be allocated for this purpose. End users can use the CloudStack UI to acquire these IPs to implement NAT between their guest network and their public network.

Provide at least one range of IP addresses for internet traffic. +# message.public.traffic.in.basic.zone=Public traffic is generated when VMs in the cloud access the Internet or provide services to clients over the Internet. Publicly accessible IPs must be allocated for this purpose. When a instance is created, an IP from this set of Public IPs will be allocated to the instance in addition to the guest IP address. Static 1-1 NAT will be set up automatically between the public IP and the guest IP. End users can also use the CloudStack UI to acquire additional IPs to implement static NAT between their instances and the public IP. +# message.add.pod.during.zone.creation=Each zone must contain in one or more pods, and we will add the first pod now. A pod contains hosts and primary storage servers, which you will add in a later step. First, configure a range of reserved IP addresses for CloudStack's internal management traffic. The reserved IP range must be unique for each zone in the cloud. +# message.guest.traffic.in.advanced.zone=Guest network traffic is communication between end-user virtual machines. Specify a range of VLAN IDs to carry guest traffic for each physical network. +# message.guest.traffic.in.basic.zone=Guest network traffic is communication between end-user virtual machines. Specify a range of IP addresses that CloudStack can assign to guest VMs. Make sure this range does not overlap the reserved system IP range. +# message.storage.traffic=Traffic between CloudStack's internal resources, including any components that communicate with the Management Server, such as hosts and CloudStack system VMs. Please configure storage traffic here. +# message.desc.cluster=Each pod must contain one or more clusters, and we will add the first cluster now. A cluster provides a way to group hosts. The hosts in a cluster all have identical hardware, run the same hypervisor, are on the same subnet, and access the same shared storage. Each cluster consists of one or more hosts and one or more primary storage servers. +# message.desc.host=Each cluster must contain at least one host (computer) for guest VMs to run on, and we will add the first host now. For a host to function in CloudStack, you must install hypervisor software on the host, assign an IP address to the host, and ensure the host is connected to the CloudStack management server.

Give the host's DNS or IP address, the user name (usually root) and password, and any labels you use to categorize hosts. +# message.desc.primary.storage=Each cluster must contain one or more primary storage servers, and we will add the first one now. Primary storage contains the disk volumes for all the VMs running on hosts in the cluster. Use any standards-compliant protocol that is supported by the underlying hypervisor. +# message.desc.secondary.storage=Each zone must have at least one NFS or secondary storage server, and we will add the first one now. Secondary storage stores VM templates, ISO images, and VM disk volume snapshots. This server must be available to all hosts in the zone.

Provide the IP address and exported path. +label.launch.zone=Executar zona. +message.please.wait.while.zone.is.being.created=Por favor, espere enquanto sua zona está sendo criada; isto pode demorar um pouco... + +label.load.balancing=Balanceamento de Carga +label.static.nat.enabled=NAT estático Habilitado +label.zones=Zonas +label.view.more=Ver mais +label.number.of.zones=Número de Zonas +label.number.of.pods=Número de Pods +label.number.of.clusters=Número de Clusters +label.number.of.hosts=Número de Hosts +label.total.hosts=Total de Hosts +label.total.CPU=CPU TOTAL +label.total.memory=Total de Memória +label.total.storage=Totam de Storage +label.purpose=Propósito + + + + +label.action.migrate.router=Migrar Roteador +label.action.migrate.router.processing=Migrando Roteador... +message.migrate.router.confirm=Por favor confirme o host que você deseja migrar o roteador para\: +label.migrate.router.to=Migrar Roteador para + +label.action.migrate.systemvm=Migrar VM de Sistema +label.action.migrate.systemvm.processing=Migrando VM de Sistema... +message.migrate.systemvm.confirm=Por favor confirme o host para o qual você deseja migrar a VM de sistema\: +label.migrate.systemvm.to=Migrar VM de sistema para + + +mode=Modo +side.by.side=Lado a Lado +# inline=Inline + +# extractable=Extractable + +label.ocfs2=OCFS2 + +label.action.edit.host=Editar Host + +network.rate=Taxa de Transferência + +ICMP.type=Tipo ICMP +ICMP.code=Código ICMP + +image.directory=Diretório da Imagem + +label.action.create.template.from.vm=Criar Template a partir da VM +label.action.create.template.from.volume=Criar Template a partir do Disco + +message.vm.create.template.confirm=Criar Template reiniciará a VM automaticamente. + +label.action.manage.cluster=Vincular Cluster +message.action.manage.cluster=Confirma a vinculação do cluster. +label.action.manage.cluster.processing=Vinculando o Cluster.... + +label.action.unmanage.cluster=Desvincular Cluster +message.action.unmanage.cluster=Confirma a desvinculação do cluster. +label.action.unmanage.cluster.processing=Desvinculando Cluster.... + +label.allocation.state=Status da Alocação +managed.state=Status do Gerenciamento + +label.default.use=Uso padrão +# label.host.tags=Host Tags + +label.cidr=CIDR +label.cidr.list=CIDR de Origem + +label.storage.tags=Tags de Storage + +label.redundant.router=Roteador Redundantee +label.is.redundant.router=Redundante + +force.delete=Forçar Exclusão +force.delete.domain.warning=Atenção\: Esta opção removerá todos os domínios, contas e recursos associados. + +force.remove=Forçar Remoção +force.remove.host.warning=Atenção\: O CloudStack desligará de maneira forçada todas as VMs antes de remover o host do cluster. + +force.stop=Forçar Parada +force.stop.instance.warning=Aviso\: Forçar o desligamento desta instância deve ser sua última opção. Isto pode levar a perda de dados, bem como comportamento inconsistênte do estado da máquina virtual. + +label.PreSetup=PreSetup +label.SR.name = SR Name-Label +label.SharedMountPoint=SharedMountPoint +label.clvm=CLVM +label.volgroup=Grupo de Volume +label.VMFS.datastore=VMFS datastore + +label.network.device=Dispositivo de Rede +label.add.network.device=Adicionar Dispositivo de Rede +label.network.device.type=Tipo de Dispositivo de Rede +label.DHCP.server.type=Tipo de Servidor DHCP +label.Pxe.server.type=Tipo de Servidor PXE +label.PING.storage.IP=Disparar PING para IP do Storage +label.PING.dir=PING Directory +label.TFTP.dir=TFTP Directory +label.PING.CIFS.username=PING CIFS username +label.PING.CIFS.password=PING CIFS password +label.CPU.cap=CPU Cap + + +label.action.enable.zone=Ativar Zona +label.action.enable.zone.processing=Ativando Zona.... +message.action.enable.zone=Confirma a ativação da zona. +label.action.disable.zone=Desativar Zona +label.action.disable.zone.processing=Desativando Zona.... +message.action.disable.zone=Confirma a desativação da zona. + +label.action.enable.pod=Ativar POD +label.action.enable.pod.processing=Ativando POD.... +message.action.enable.pod=Confirma a ativação do POD. +label.action.disable.pod=Desativar POD +label.action.disable.pod.processing=Desativando POD.... +message.action.disable.pod=Confirma a desativação do POD. + +label.action.enable.cluster=Ativar Cluster +label.action.enable.cluster.processing=Ativando Cluster.... +message.action.enable.cluster=Confirma a ativação do cluster. +label.action.disable.cluster=Desativar Cluster +label.action.disable.cluster.processing=Desativando Cluster.... +message.action.disable.cluster=Confirma a desativação do cluster. + +label.account.id=ID da Conta +label.account.name=Nome da Conta +# label.account.specific=Account-Specific +label.account=Conta +label.accounts=Contas +label.acquire.new.ip=Adquirir novo IP +label.show.ingress.rule=Mostrar Regra de Entrada +label.hide.ingress.rule=Ocultar Regra de Entrada +label.action.attach.disk.processing=Anexando Disco.... +label.action.attach.disk=Anexar Disco +label.action.attach.iso.processing=Anexando ISO.... +label.action.attach.iso=Anexar ISO +label.action.cancel.maintenance.mode.processing=Cancelando Modo de Manutenção.... +label.action.cancel.maintenance.mode=Cancelar Modo de Manutenção +label.action.change.password=Troca de Senha +label.action.change.service.processing=Trocando de Plano.... +label.action.change.service=Trocar Plano +label.action.copy.ISO.processing=Copiando ISO.... +label.action.copy.ISO=Copiar ISO +label.action.copy.template.processing=Copiando Template.... +label.action.copy.template=Copiar Template +label.action.create.template.processing=Criando Template.... +label.action.create.template=Criar Template +label.action.create.vm.processing=Criando VM.... +label.action.create.vm=Criar VM +label.action.create.volume.processing=Criando Disco.... +label.action.create.volume=Criar Disco +label.action.delete.IP.range.processing=Removendo Range de IP.... +label.action.delete.IP.range=Remover Range IP +label.action.delete.ISO.processing=Removendo ISO.... +label.action.delete.ISO=Removendo ISO +label.action.delete.account.processing=Removendo conta.... +label.action.delete.account=Remover conta +label.action.delete.cluster.processing=Removendo Cluster.... +label.action.delete.cluster=Remover Cluster +label.action.delete.disk.offering.processing=Removendo Oferta de Disco.... +label.action.delete.disk.offering=Remover Oferta de Disco + +label.action.update.resource.count=Atualiza Contador de Recursos +label.action.update.resource.count.processing=Atualizando Contador de Recursos.... + +label.action.delete.domain=Remover Domínio +label.action.delete.domain.processing=Removendo Domínio.... + +label.action.delete.firewall.processing=Removendo Firewall.... +label.action.delete.firewall=Remover regra de firewall +label.action.delete.ingress.rule.processing=Removendo Regra de Entrada.... +label.action.delete.ingress.rule=Remover Regra de Entrada +label.action.delete.load.balancer.processing=Removendo Load Balancer.... +label.action.delete.load.balancer=Remover regra de balanceador de carga +label.action.edit.network.processing=Editarando Rede.... +label.action.edit.network=Editar Rede +label.action.delete.network.processing=Removendo Rede.... +label.action.delete.network=Remover Rede +label.action.delete.pod.processing=Removendo POD.... +label.action.delete.pod=Remover POD +label.action.delete.primary.storage.processing=Removendo Storage Primário.... +label.action.delete.primary.storage=Remover Storage Primário +label.action.delete.secondary.storage.processing=Removendo Storage Secundário.... +label.action.delete.secondary.storage=Remover Storage Secundário +label.action.delete.security.group.processing=Removendo Security Group.... +label.action.delete.security.group=Remover Security Group +label.action.delete.service.offering.processing=Removendo Plano.... +label.action.delete.service.offering=Remover Plano +label.action.delete.snapshot.processing=Removendo Snapshot.... +label.action.delete.snapshot=Remover Snapshot +label.action.delete.template.processing=Removendo Template.... +label.action.delete.template=Remover Template +label.action.delete.user.processing=Removendo Usuário.... +label.action.delete.user=Remover Usuário +label.action.delete.volume.processing=Removendo Disco.... +label.action.delete.volume=Remover Disco +label.action.delete.zone.processing=Removendo Zona.... +label.action.delete.zone=Remover Zona +label.action.destroy.instance.processing=Apagando Cloud Server.... +label.action.destroy.instance=Apagar Cloud Server +label.action.destroy.systemvm.processing=Apagando VM de Sistema.... +label.action.destroy.systemvm=Apagar VM de Sistema +label.action.detach.disk.processing=Desplugando Disco.... +label.action.detach.disk=Desplugar Disco +label.action.detach.iso.processing=Desplugando ISO.... +label.action.detach.iso=Desplugar ISO +label.action.disable.account.processing=Desativando conta.... +label.action.disable.account=Desativar conta +label.action.disable.static.NAT.processing=Desativando NAT Estático.... +label.action.disable.static.NAT=Desativar NAT Estático +label.action.disable.user.processing=Desativando Usuário.... +label.action.disable.user=Desativar Usuário +label.action.download.ISO=Baixar ISO +label.action.download.template=Baixar Template +label.action.download.volume.processing=Baixando Disco.... +label.action.download.volume=Baixar Disco +label.action.edit.ISO=Editar ISO +label.action.edit.account=Editar conta +label.action.edit.disk.offering=Editar Oferta de Disco +label.action.edit.domain=Editar Domínio +label.action.edit.global.setting=Editar Configurações Globais +label.action.edit.instance=Editar Cloud Server +label.action.edit.network.offering=Editar Oferta de Rede +label.action.edit.pod=Editar Pod +label.action.edit.primary.storage=Editar Storage Primário +label.action.edit.resource.limits=Editar Limite de Recursos +label.action.edit.service.offering=Editar Plano +label.action.edit.template=Editar Template +label.action.edit.user=Editar Usuário +label.action.edit.zone=Editar Zona +label.action.enable.account.processing=Ativando conta.... +label.action.enable.account=Ativar conta +label.action.enable.maintenance.mode.processing=Ativando Modo de Manutenção.... +label.action.enable.maintenance.mode=Ativar Modo de Manutenção +label.action.enable.static.NAT.processing=Ativando NAT Estático.... +label.action.enable.static.NAT=Ativar NAT Estático +label.action.enable.user.processing=Habilitando Usuário... +label.action.enable.user=Habilitar usuário +label.action.force.reconnect.processing=Reconectando.... +label.action.force.reconnect=Force Reconnect +label.action.generate.keys.processing=Gerando Chaves.... +label.action.generate.keys=Gerar Chaves +label.action.lock.account.processing=Bloqueando conta.... +label.action.lock.account=Bloquear conta +label.action.migrate.instance=Migrar Cloud Server +label.action.migrate.instance.processing=Migrando Cloud Server... +label.action.reboot.instance.processing=Reiniciando Cloud Server... +label.action.reboot.instance=Reiniciar Cloud Server +label.action.reboot.router.processing=Reiniciando Roteador.... +label.action.reboot.router=Reiniciar Roteador +label.action.reboot.systemvm.processing=Reiniciando VM de Sistema.... +label.action.reboot.systemvm=Reiniciar VM de Sistema +# label.action.recurring.snapshot=Recurring Snapshots +label.action.release.ip.processing=Liberando IP.... +label.action.release.ip=Liberar IP +label.action.remove.host.processing=Removendo Host.... +label.action.remove.host=Remover Host +label.action.reset.password.processing=Recuperando a Senha.... +label.action.reset.password=Recuperar Senha +label.action.resource.limits=Limite de Recursos +label.action.restore.instance.processing=Restaurando Cloud Server... +label.action.restore.instance=Restaurar Cloud Server +label.action.start.instance.processing=Iniciando Cloud Server... +label.action.start.instance=Iniciar Cloud Server +label.action.start.router.processing=Iniciando Roteador.... +label.action.start.router=Iniciar Roteador +label.action.start.systemvm.processing=Iniciando VM de Sistema.... +label.action.start.systemvm=Iniciar VM de Sistema +label.action.stop.instance.processing=Parando Cloud Server... +label.action.stop.instance=Parar Cloud Server +label.action.stop.router.processing=Parando Roteador.... +label.action.stop.router=Parar Roteador +label.action.stop.systemvm.processing=Parando VM de Sistema.... +label.action.stop.systemvm=Parar VM de Sistema +label.action.take.snapshot.processing=Tirando Snapshot.... +label.action.take.snapshot=Tirar Snapshot +label.action.update.OS.preference.processing=Atualizando Preferência de SO.... +label.action.update.OS.preference=Atualizar Preferência de SO +label.actions=Ações +label.active.sessions=Sessões Ativas +label.add.account=Adicionar Conta +label.add.by.cidr=Adicionar por CIDR +label.add.by.group=Adicionar por Grupo +label.add.cluster=Adicionar Cluster +label.add.direct.iprange=Add Direct Ip Range +label.add.disk.offering=Adicionar Oferta de Disco +label.add.domain=Adicionar Domínio +label.add.firewall=Adicionar regra de Firewall +label.add.host=Adicionar Host +label.add.ingress.rule=Adicionar Regra de Entrada +label.add.ip.range=Adicionar Range de IP +label.add.load.balancer=Adicionar Load Balance +label.add.more=Adicionar Mais +label.add.network=Adicionar Rede +label.add.pod=Adicionar POD +label.add.primary.storage=Adicionar Storage Primário +label.add.secondary.storage=Adicionar Storage Secundário +label.add.security.group=Adicionar Security Group +label.add.service.offering=Adicionar Plano +label.add.template=Adicionar Template +label.add.user=Adicionar Usuário +label.add.vlan=Adicionar VLAN +label.add.volume=Adicionar Disco +label.add.zone=Adicionar Zona +label.add=Adicionar +label.adding.cluster=Adicionando Cluster +label.adding.failed=Falha ao Adicionar +label.adding.pod=Adicionando POD +label.adding.processing=Adicionando.... +label.adding.succeeded=Adicionado com Sucesso +label.adding.user=Adicionando Usuário +label.adding.zone=Adicionando Zona +label.adding=Adicionando +label.additional.networks=Redes Adicionais +label.admin.accounts=Contas Administrativas +label.admin=Administrador +label.advanced.mode=Modo Avançado +label.advanced.search=Busca Avançada +label.advanced=Avançado +label.alert=Alerta +label.algorithm=Algoritmo +label.allocated=Alocado +label.api.key=API Key +label.assign.to.load.balancer=Atribuindo o Cloud Server ao Load Balancer +label.assign=Atribuir +label.associated.network.id=ID de Rede Associado +label.attached.iso=Imagem ISO Plugada +label.availability.zone=Datacenter +label.availability=Availability +label.available.public.ips=IP Público Disponível +label.available=Disponível +label.back=Voltar +label.basic.mode=Modo Básico +label.bootable=Inicializável +label.broadcast.domain.type=Tipo de Domínio Broadcast +label.by.account=por Conta +label.by.availability=By Availability +label.by.domain=por Domínio +label.by.end.date=por Data Final +label.by.level=por Nível +label.by.pod=por Pod +label.by.role=por Função +label.by.start.date=por Data Inicial +label.by.state=por estado +label.by.traffic.type=por Tipo de Tráfego +label.by.type.id=por Tipo de ID +label.by.type=Por Tipo +label.by.zone=por Zona +label.bytes.received=Bytes Recebidos +label.bytes.sent=Bytes Enviados +label.cancel=Cancelar +label.certificate=Certificado +label.privatekey=PKCS\#8 Private Key +label.domain.suffix=Sufixo de Domínio DNS (ex. xyz.com) +label.character=Caracter +label.cidr.account=CIDR ou Conta/Security Group +label.close=Fechar +label.cloud.console=Console de Gerenciamento da Nuvem +label.cloud.managed=Cloud.com Managed +label.cluster.type=Tipo de Cluster +label.cluster=Cluster +label.code=Código +label.confirmation=Confirmação +label.cpu.allocated.for.VMs=CPU Alocada por VMs +label.cpu.allocated=CPU Alocada +label.cpu.utilized=CPU Utilizada +label.cpu=CPU +label.created=Criado +label.cross.zones=Inter Zonas +label.custom.disk.size=Tamanho Customizado +label.daily=Diário +label.data.disk.offering=Oferta de Disco Adicional +label.date=Data +label.day.of.month=Dia do Mês +label.day.of.week=Dia da Semana +label.delete=Remover +label.deleting.failed=Falha ao remover +label.deleting.processing=Removendo.... +label.description=Descrição +label.detaching.disk=Desplugando Disco +label.details=Detalhes +label.device.id=ID do Dispositivo +label.disabled=Desativado +label.disabling.vpn.access=Desativando Acesso VPN +label.disk.allocated=Disco Alocado +label.disk.offering=Oferta de Disco +label.disk.size.gb=Tamanho (em GB) +label.disk.size=Tamanho do Disco +label.disk.total=Disco Total +label.disk.volume=Disco +label.display.text=Descrição +label.dns.1=DNS 1 +label.dns.2=DNS 2 +label.domain.admin=Administrador de Domínio +label.domain.id=ID do Domínio +label.domain.name=Nome do Domínio +label.domain=Domínio +label.double.quotes.are.not.allowed=Aspas duplas não são permitidas +label.download.progress=Status do Download +label.edit=Editar +label.email=Email +label.enabling.vpn.access=Ativando Acesso VPN +label.enabling.vpn=Ativando VPN +label.end.port=Porta Final +label.endpoint.or.operation=Endpoint or Operation +label.error.code=Código de Erro +label.error=Erro +label.esx.host=ESX/ESXi Host +label.example=Examplo +label.failed=Falhou +label.featured=Featured +label.firewall=Firewall +label.first.name=Primeiro Nome +label.format=Formato +label.friday=Sexta-feira +label.full=Full +label.gateway=Gateway +label.general.alerts=Alertas Gerais +label.generating.url=Criando URL +label.go.step.2=Vá para passo 2 +label.go.step.3=Vá para passo 3 +label.go.step.4=Vá para passo 4 +label.go.step.5=Vá para passo 5 +label.group.optional=Grupo (Opcional) +label.group=Grupo +label.guest.cidr=CIDR de rede Convidado +label.guest.gateway=Gateway de rede Convidado +label.guest.ip.range=Intervalo de rede convidado +label.guest.ip=Endereço IP Convidado +label.guest.netmask=Máscara de rede Convidado +label.ha.enabled=HA Ativado +label.help=Ajuda +label.host.alerts=Alertas de Host +label.host.name=Host Name +label.host=Host +label.hosts=Hosts +label.hourly=A cada hora +label.hypervisor.type=Tipo do Hypervisor +label.hypervisor=Hypervisor +label.id=ID +label.info=Info +label.ingress.rule=Regra de Entrada +label.initiated.by=Iniciado por +label.instance.limits=Limites do Cloud Server +label.instance.name=Nome do Cloud Server +label.instance=Cloud Server +label.instances=Cloud Servers +label.internal.dns.1=DNS 1 Interno +label.internal.dns.2=DNS 2 Interno +label.interval.type=Tipo de Intervalo +label.invalid.integer=Invalid Integer +label.invalid.number=Número Inválido +label.ip.address=Endereço IP +label.ip.allocations=Alocações de IP +label.ip.limits=Limites de IP Público +label.ip.or.fqdn=IP ou FQDN +label.ip.range=Range de IP +label.ip=IP +label.ips=IPs +label.is.default=Ã\u0089 Padrão +label.is.shared=Ã\u0089 Compartilhado +label.is.system=é um sistema +label.iscsi=iSCSI +label.iso.boot=ISO de Boot +label.iso=ISO +label.isolation.mode=Modo Isolado +label.keep=Manter +label.lang.chinese=Chinese (Simplified) +label.lang.english=English +label.lang.japanese=Japanese +label.lang.spanish=Spanish +label.last.disconnected=Last Disconnected +label.last.name=Ã\u009altimo Nome +label.level=Nível +label.linklocal.ip=Endereço IP Link Local +label.load.balancer=Load Balancer +label.loading=Carregando +label.local=Local +# label.local.storage.enabled=Local storage enabled +label.login=Entrar +label.logout=Sair +label.lun=LUN +label.manage=Gerenciar +label.maximum=Máximo +label.memory.allocated=Memória Alocada +label.memory.total=Memória Total +label.memory.used=Memória Usada +label.memory=Memória (em MB) +label.menu.accounts=Contas +label.menu.alerts=Alertas +label.menu.all.accounts=Todas as Contas +label.menu.all.instances=Todos Cloud Servers +label.menu.community.isos=ISOs Públicas +label.menu.community.templates=Templates Públicos +label.menu.configuration=Configuração +label.menu.dashboard=Dashboard +label.menu.destroyed.instances=Cloud Servers Apagados +label.menu.disk.offerings=Oferta de Discos +label.menu.domains=Domínios +label.menu.events=Eventos +label.menu.featured.isos=ISOs Customizada +label.menu.featured.templates=Templates Customizados +label.menu.global.settings=Configurações Globais +label.menu.instances=Cloud Servers +label.menu.ipaddresses=Endereços IP +label.menu.isos=ISOs +label.menu.my.accounts=Minhas Contas +label.menu.my.instances=Meus Cloud Servers +label.menu.my.isos=Minhas ISOs +label.menu.my.templates=Meus Templates +label.menu.network.offerings=Oferta de Rede +label.menu.network=Rede +label.menu.physical.resources=Recursos Físicos +label.menu.running.instances=Cloud Servers Rodando +label.menu.security.groups=Security Groups +label.menu.service.offerings=Planos +label.menu.snapshots=Snapshots +label.menu.stopped.instances=Cloud Servers Parados +label.menu.storage=Storage +label.menu.system.vms=VM de Sistemas +label.menu.system=Sistema +label.menu.templates=Templates +label.menu.virtual.appliances=Appliances Virtuais +label.menu.virtual.resources=Recursos Virtuais +label.menu.volumes=Discos +label.migrate.instance.to=Migrar Cloud Server para +label.minimum=Mínimo +label.minute.past.hour=minuto(s) Última hora +label.monday=Segunda +label.monthly=Mensal +label.more.templates=Mais Templates +label.my.account=Minha Conta +label.name.optional=Nome (Opcional) +label.name=Nome +label.netmask=Másrca de Rede +label.network.desc=Descrição de Rede +label.network.domain=Domínio de Rede +label.network.id=ID de Rede +label.network.name=Nome da Rede +label.network.offering.display.text=Network Offering Display Text +label.network.offering.id=Network Offering ID +label.network.offering.name=Network Offering Name +label.network.offering=Network Offering +label.network.rate=Taxa de Transferência +label.network.read=Network Read +label.network.type=Tipo de Rede +label.network.write=Network Write +label.network=Rede +label.new.password=Nova Senha +label.next=Próximo +label.nfs.server=Servidor NFS +label.nfs.storage=Storage NFS +label.nfs=NFS +label.nics=REDE +label.no.actions=Sem Ações Disponíveis +label.no.alerts=Sem Alertas Recentes +label.no.errors=Sem Erros Recentes +label.no.isos=Sem ISO Disponível +label.no.items=Sem Ã\u008dtens Disponíveis +label.no.security.groups=Sem Security Groups Disponíveis +label.no.thanks=Não obrigado +label.no=Não +label.none=Nenhum +label.not.found=Não Encontrado +label.num.cpu.cores=\# de Core CPU +label.numretries=Número de Tentativas +label.offer.ha=Offer HA +label.optional=Opcional +label.os.preference=Preferência de SO +label.os.type=Tipo de SO +label.owned.public.ips=IP Público Utilizado +label.owner.account=Dono da Conta +label.owner.domain=Dono do Domínio +label.parent.domain=Domínio Principal +label.password.enabled=Senha Ativada +label.password=Senha +label.path=Caminho (Path) +label.please.wait=Por Favor Aguarde +label.pod=POD +label.port.forwarding=Encaminhamento de Porta +label.port.range=Range de Porta +label.prev=Prev +label.primary.allocated=Alocação do Storage Primário +label.primary.network=Rede Primária +label.primary.storage=Storage Primário +label.primary.used=Uso do Storage Primário +label.private.interface=Interface Privada +label.private.ip.range=Range de IP Privado +label.private.ip=Endereço IP Privado +label.private.ips=IPs Privados +label.private.port=Porta Privada +label.private.zone=Zona Privada +label.protocol=Protocolo +label.public.interface=Interface Pública +label.public.ip=Endereço IP Público +label.public.ips=IPs Públicos +label.public.port=Porta Pública +label.public.zone=Zona Pública +label.public=Público +label.recent.errors=Erros Recentes +label.refresh=Atualizar +label.related=Relacionado +label.remove.from.load.balancer=Removendo Cloud Server do Load Balancer +label.removing.user=Removendo Usuário +label.required=Obrigatório +label.reserved.system.ip=IP de Sistema Reservado +label.resource.limits=Limite de Recursos +label.resource=Recurso +label.resources=Recursos +label.role=Função +label.root.disk.offering=Oferta de Disco ROOT +label.running.vms=VMs Rodando +label.saturday=Sábado +label.save=Salvar +label.saving.processing=Salvando.... +label.scope=Escopo +label.search=Pesquisar +label.secondary.storage=Storage Secundário +label.secondary.used=Uso do Storage Secundário +label.secret.key=Chave Secreta +label.security.group.name=Nome do Security Group +label.security.group=Security Group +label.security.groups.enabled=Security Groups Ativado +label.security.groups=Security Groups +label.sent=Enviado +label.server=Servidor +label.service.offering=Plano +label.system.service.offering=System Service Offering +label.session.expired=Sessão Expirada +label.shared=Compatilhado +label.size=Tamanho +label.snapshot.limits=Limites de Snapshot +label.snapshot.name=Nome do Snapshot +label.snapshot.s=Snapshot (s) +# label.snapshot.schedule=Setup Recurring Snapshot +label.snapshot=Snapshot +label.snapshots=Snapshots +label.source.nat=Source NAT +label.specify.vlan=Especificar VLAN +label.start.port=Porta de Início +label.state=Estado +label.static.nat.to=NAT Estático para +label.static.nat=NAT Estático +label.statistics=Estatísticas +label.status=Estado +label.step.1.title=Passo 1\: Selecione o Template +label.step.1=Passo 1 +label.step.2.title=Passo 2\: Plano +label.step.2=Passo 2 +label.step.3.title=Passo 3\: Selecione o Disco Adicional +label.step.3=Passo 3 +label.step.4.title=Passo 4\: Rede +label.step.4=Passo 4 +label.step.5.title=Passo 5\: Revisar +label.step.5=Passo 5 +label.stopped.vms=VMs Paradas +label.storage.type=Tipo de Storage +label.storage=Storage +label.submit=Enviar +label.submitted.by=[Enviado por\: ] +label.succeeded=Sucedido +label.sunday=Domingo +label.system.capacity=Capacidade do Sistema +label.system.vm.type=Tipo de VM de Sistema +label.system.vm=VM de Sistema +label.system.vms=VM de Sistema +label.tagged=Tagged +label.tags=Tags +label.target.iqn=Target IQN +label.template.limits=Limites do Template +label.template=Template +label.theme.default=Tema Padrão +label.theme.grey=Custom - Grey +label.theme.lightblue=Custom - Light Blue +label.thursday=Quinta +label.time.zone=Fuso Horário +label.time=Time +label.timeout.in.second = Timeout(segundos) +label.timezone=Fuso Horário +label.total.cpu=CPU TOTAL +label.total.vms=Total VMs +label.traffic.type=Tipo de Tráfego +label.tuesday=Terça +label.type.id=Tipo do ID +label.type=Tipo +label.unavailable=Indisponível +label.unlimited=Ilimitado +label.untagged=Não Marcado +label.update.ssl.cert=Atualizar Certificado SSL +label.update.ssl=Atualizar Certificado SSL +label.updating=Atualizando +label.url=URL +label.usage.interface=Usage Interface +label.used=Usado +label.user=Usuário +label.username=Nome de Usuário +label.users=Usuários +label.value=Valor +label.vcenter.cluster=vCenter Cluster +label.vcenter.datacenter=vCenter Datacenter +label.vcenter.datastore=vCenter Datastore +label.vcenter.host=vCenter Host +label.vcenter.password=vCenter Password +label.vcenter.username=vCenter Username +label.version=Versão +label.virtual.appliance=Appliance Virtual +label.virtual.appliances=Appliance Virtual +label.virtual.network=Rede Virtual +label.vlan.id=VLAN ID +label.vlan.range=Intervalo de VLAN +label.vm.add=Adicionar Cloud Server +label.vm.destroy=Apagar +label.vm.reboot=Reiniciar +label.vm.start=Início +label.vm.stop=Parar +label.vmfs=VMFS +label.vms=VMs +label.volume.limits=Limites de Disco +label.volume.name=Nome do Disco +label.volume=Disco +label.volumes=Discos +label.vsphere.managed=vSphere Managed +label.waiting=Aguardando +label.warn=Avisar +label.wednesday=Quarta-Feira +label.weekly=Semanal +label.welcome.cloud.console=Painel de Controle +label.welcome=Bem-Vindo +label.yes=Sim +label.zone.id=ID da Zona +label.zone.step.1.title=Passo 1\: Selecionar a Rede +label.zone.step.2.title=Passo 2\: Adicionar a Zona +label.zone.step.3.title=Passo 3\: Adicionar o POD +label.zone.step.4.title=Passo 4\: Adicionar um Intervalo de IP +# label.zone.wide=Zone-Wide +label.zone=Zona + +#Messages +message.acquire.public.ip=Selecione a zona de onde você deseja adquirir o novo IP +message.action.cancel.maintenance.mode=Confirme que você deseja cancelar esta manutenção +message.action.cancel.maintenance=A manutenção do seu HOST foi cancelada com sucesso +message.action.delete.ISO.for.all.zones=Esta ISO é usada por todas as Zonas. Confirme se você deseja excluir a ISO de todas as Zonas +message.action.delete.ISO=Confirme que você deseja excluir esta ISO +message.action.delete.cluster=Confirme que você deseja excluir este HOST +message.action.delete.disk.offering=Confirme que você deseja excluir esta oferta de disco +message.action.delete.domain=Confirme que você deseja excluir este domínio +message.action.delete.external.firewall=Confirme que você gostaria de remover este Firewall externo. Aviso\: Se você está planejando adicionar novamente este mesmo Firewall, é necessário apagar os contadores do dispositivo. +message.action.delete.external.load.balancer=Confirme que você gostaria de remover este Load Balancer Externo. Aviso\: Se você está planejando adicionar novamente este mesmo Load Balancer, é necessário apagar os contadores do dispositivo. +message.action.delete.ingress.rule=Confirme que você deseja excluir esta regra de entrada. +message.action.delete.network=Confirme que você deseja remover esta rede. +message.action.delete.pod=Confirme que você deseja remover este POD. +message.action.delete.primary.storage=Confirme que você deseja remover este Storage Primário. +message.action.delete.secondary.storage=Confirme que você deseja remover este Storage Secundário. +message.action.delete.security.group=Confirme que você deseja remover este Security Group. +message.action.delete.service.offering=Confirme que você deseja remover este Plano. +message.action.delete.snapshot=Confirme que você deseja remover este Snapshot. +message.action.delete.template.for.all.zones=Este Template é usado por todas as zonas. Confirme que você deseja remover o Template de todas as zonas. +message.action.delete.template=Confirme que você deseja remover este Template. +message.action.delete.volume=Confirme que você deseja remover este Disco. +message.action.delete.zone=Confirme que você deseja remover esta Zona. +message.action.destroy.instance=Confirme que você deseja excluir este Cloud Server. +message.action.destroy.systemvm=Confirme que você deseja excluir esta VM de Sistema. +message.action.disable.static.NAT=Confirme que você deseja desativar o NAT estático. +message.action.enable.maintenance=O Host foi preparado com sucesso para manutenção. Este processo poderá levar alguns minutos ou mais dependendo do número de VMs hospedadas neste Host. +message.action.force.reconnect=O procedimento de reconexão forçada foi preparado com sucesso. Este processo poderá levar alguns minutos. +message.action.host.enable.maintenance.mode=Ativar o modo de manutenção irá causar o live migration de todos Cloud Server hospedados neste Host para o próximo disponível. +message.action.instance.reset.password=Por favor confirme que você deseja alterar a senha de ROOT para está máquina virtual. +message.action.primarystorage.enable.maintenance.mode=Aviso\: Colocar o Storage primário em modo de manutenção irá causar a parada de todas as VMs hospedadas nesta unidade. Deseja continuar? +message.action.reboot.instance=Confirme que você deseja reiniciar este Cloud Server. +message.action.reboot.systemvm=Confirme que você deseja reiniciar esta VM de sistema. +message.action.release.ip=Confirme que você deseja liberar este IP. +message.action.remove.host=Remover o único/último host do cluster e reinstalar o host irá provocar a perda do ambiente/banco do host tornando os Cloud Servers inutilizáveis. +message.action.restore.instance=Confirme que você deseja restaurar este Cloud Server. +message.action.start.instance=Confirme que você deseja iniciar este Cloud Server. +message.action.start.router=Confirme que você deseja inciar este roteador. +message.action.start.systemvm=Confirme que você deseja iniciar esta VM de sistema. +message.action.stop.instance=Confirme que você deseja parar este Cloud Server. +message.action.stop.systemvm=Confirme que você deseja parar esta VM de Sistema. +message.action.take.snapshot=Por favor confirme que você deseja criar um snapshot deste volume. +message.add.cluster.zone=Add a hypervisor managed cluster for zone +message.add.cluster=Add a hypervisor managed cluster for zone , pod +message.add.disk.offering=Especifique o seguintes parâmetros para adicionar uma nova oferta de disco. +message.add.firewall=Adicionar Firewall à zona. +message.add.host=Especifique os seguintes parâmetros para adicionar um novo host. +message.add.ip.range.direct.network=Add an IP range to direct network in zone +message.add.ip.range.to.pod=

Add an IP range to pod\:

+message.add.ip.range=Add an IP range to public network in zone +message.add.load.balancer=Add a load balancer to zone +message.add.network=Add a new network for zone\: +message.add.pod=Add a new pod for zone +message.add.primary.storage=Adicionar novo Storage primário à zona , pod +message.add.primary=Especifique os seguintes parâmetros para adicionar um novo Storage primário. +message.add.secondary.storage=Add a new storage for zone +message.add.service.offering=Por favor preencha os dados abaixo para adicionar uma nova oferta de computação. +message.add.template=Entre com os dados para criar um novo template. +message.add.volume=Entre com os dados para criar um novo disco. +message.additional.networks.desc=Selecione a(s) rede(s) adicionais que seu Cloud Server terá acesso. +message.advanced.mode.desc=Escolhe este modelo de rede se deseja ter habilitar o suporte a VLAN. Este modelo permite maior flexibilidade ao administrador ao permitir ofertas de rede customizada, firewall, vpn ou load balancer bem como acesso via rede virtual ou acesso direto. +message.advanced.security.group=Escolha esta opção se desejar utilizar Security Groups para isolamento das VMs guest. +message.advanced.virtual=Escolha esta opção se desejar utilizar VLANs para isolamento das VMs guest. +message.allow.vpn.access=Entre com nome de usuário e senha do usuário que terá acesso VPN. +message.attach.iso.confirm=Confirme que você deseja conectar a ISO ao Cloud Server. +message.attach.volume=Preencha os seguintes dados para conectar o novo disco. Se você está conectando um disco a um Cloud Server Windows, será necessário reiniciar o Cloud Server para visualizar o novo disco. +message.basic.mode.desc=Escolha este modelo de rede se você *não* quer suporte a VLAN. Todo Cloud Server criado neste modelo de rede estará ligado diretamente a um IP da rede e será usado Security Groups para prover segurança e separação. +message.change.offering.confirm=Confirme que você deseja mudar o plano deste Cloud Server. +message.copy.iso.confirm=Confirme se você deseja copiar a ISO para +message.copy.template=Copiar template XXX da zona para +message.create.template.vm=Criar VM do template +message.create.template.volume=Especifique as seguintes informações antes de criar o template a partir do disco\: . A criação de um template a partir de um disco pode levar alguns minutos ou mais dependendo do tamnho do disco. +message.delete.account=Confirme se você deseja excluir esta conta. +message.detach.iso.confirm=Confirme se você deseja desconectar a ISO do Cloud Server. +message.disable.account=Por favor confirme que você deseja desabilitar esta conta. Após desabilitar uma conta, todos os usuários desta conta não irão possuir mais acesso aos seus recursos da cloud. Todas as máquinas virtuais serão automaticamente desligadas. +message.disable.vpn.access=Confirme se você deseja desativar o acesso VPN. +message.download.ISO=Por favor clique 00000 para baixar o ISO +message.download.template=Por favor clique 00000 para baixar o template +message.download.volume=Clique 00000 para baixar o disco +message.edit.confirm=Por favor confirme suas alterações antes de clicar em "Salvar". +message.edit.limits=Especifique os limites para os seguintes recursos. "-1" indica sem limite para o total de recursos criados. +message.enable.account=Confirme se você deseja ativar a conta. +message.enable.vpn.access=VPN está desativada para este endereço IP. Gostaria de ativar o acesso VPN? +message.enabled.vpn.ip.sec=Sua chave IPSec (pre-shared) é +message.enabled.vpn=Seu acesso VPN está ativado e pode ser acessado através do IP +message.launch.vm.on.private.network=Você deseja executar sua instância na sua própria rede privada dedicada ? +message.lock.account=Confirme se você deseja bloquear esta conta. Bloqueando a conta, todos os usuários desta conta não estarão mais habilitados a gerenciar os recursos na nuvem. Os recursos existentes (Cloud Server) ainda poderão ser acessados. +message.migrate.instance.confirm=Confirme o host que você deseja migrar o Cloud Server. +message.new.user=Especifique abaixo para adicionar novos usuários para a conta +message.no.network.support.configuration.not.true=Você não possui nenhuma zona com grupos de segurança habilitado. Assim sendo, não possui recursos adicionais de rede. Por favor continue para o passo 5. +message.no.network.support=O hypervisor escolhido, vSphere, não possui nenhum recurso de rede adicional. Por favor, vá para o passo 5. +message.number.clusters=

Clusters

+message.number.hosts=

Hosts

+message.number.pods=

PODs

+message.number.storage=

Volumes do Storage Primário

+message.number.zones=

Zonas

+message.remove.vpn.access=Confirme se você deseja remover acesso VPN do seguinte usuário. +message.restart.mgmt.server=Reinicie o(s) servidor(es) de gerenciamento para que a nova configuração tenha efeito. +message.restart.mgmt.usage.server=Por favor reinicie seu servidor(es) de gerenciamento e seu servidor(es) de utilização para as mudanças entrarem em efeito. +message.security.group.usage=(Use Ctrl-clique para selecionar todos os Security Groups) +message.snapshot.schedule=Você pode configurar Snapshots recorrentes agendados selecionando as opções disponíveis abaixo +message.step.1.continue=Selecione o template ou ISO para continuar +message.step.1.desc=Selecione o template para o novo Cloud Server. +message.step.2.continue=Selecione o plano +message.step.2.desc= +message.step.3.continue=Seleciona a oferta de disco +message.step.3.desc= +message.step.4.continue=Selecione pelo menos uma rede para continuar +message.step.4.desc=Selecione a rede principal que seu Cloud Server será conectado. +message.update.os.preference=Escolha o SO de preferencia para este host. Todos Cloud Server com preferencias similares serão alocados neste host antes de tentar em outro. +message.update.ssl=Envie o novo certificado SSL X.509 para ser atualizado em cada console proxy\: +message.virtual.network.desc=Rede virtual dedicado para sua conta. O domínio de broadcast está na VLAN e todo acesso a internet é roteado através do virtual router. +message.volume.create.template.confirm=Confirme se você deseja criar um template a partir deste disco. A criação do template pode levar alguns minutos ou mais dependendo do tamanho do disco. +message.zone.step.1.desc=Seleciona o modelo de rede para a zona. +message.zone.step.2.desc=Entre a informação a seguir para adicionar uma nova zona +message.zone.step.3.desc=Entre a informação a seguir para adicionar um novo pod +message.apply.snapshot.policy=Você atualizou com sucesso sua política de Snapshot. +message.disable.snapshot.policy=Você desativou com sucesso sua política de Snapshot. +message.action.change.service.warning.for.instance=Para troca de plano é necessário parar o Cloud Server. +message.action.change.service.warning.for.router=O roteador precisa ser desligado antes de trocar o plano/tamanho. +message.action.reset.password.warning=Para recuperar a senha é necessário parar o Cloud Server. +message.action.reset.password.off=Seu Cloud Server não suporta esta funcionalidade. + +#Errors +error.login=Usuário ou senha inválido. +error.menu.select=Não foi possível realizar a ação pois nenhum item foi selecionado. +error.mgmt.server.inaccessible=O servidor de gerenciamento está inacessível. Tente novamente mais tarde. +error.session.expired=Sua sessão expirou. +error.unresolved.internet.name=Impossível resolver DNS diff --git a/client/WEB-INF/classes/resources/messages_ru_RU.properties b/client/WEB-INF/classes/resources/messages_ru_RU.properties new file mode 100644 index 00000000000..dd7e7460744 --- /dev/null +++ b/client/WEB-INF/classes/resources/messages_ru_RU.properties @@ -0,0 +1,1512 @@ +# 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. + + +#new labels (begin) ********************************************************************************************** +# label.isolation.uri=Isolation URI +# label.broadcast.uri=Broadcast URI +#new labels (end) ************************************************************************************************ + + +#modified labels (begin) ***************************************************************************************** +# message.zoneWizard.enable.local.storage=WARNING\: If you enable local storage for this zone, you must do the following, depending on where you would like your system VMs to launch\:

1. If system VMs need to be launched in primary storage, primary storage needs to be added to the zone after creation. You must also start the zone in a disabled state.

2. If system VMs need to be launched in local storage, system.vm.use.local.storage needs to be set to true before you enable the zone.


Would you like to continue? +#modified labels (end) ******************************************************************************************* + +# label.configure.network.ACLs=Configure Network ACLs +# label.network.ACLs=Network ACLs +# label.add.network.ACL=Add network ACL +# label.private.Gateway=Private Gateway +# label.VPC.router.details=VPC router details +# label.VMs.in.tier=VMs in tier +# label.local.storage.enabled=Local storage enabled +# label.tier.details=Tier details +# label.edit.tags=Edit tags +label.action.enable.physical.network=Включить физичеÑкую Ñеть +label.action.disable.physical.network=Отключить физичеÑкую Ñеть +message.action.enable.physical.network=Подтвердите, что вы дейÑтвительно хотите включить Ñту физичеÑкую Ñеть. +message.action.disable.physical.network=Подтвердите, что вы дейÑтвительно хотите выключить Ñту физичеÑкую Ñеть. + +# label.select.tier=Select Tier +# label.add.ACL=Add ACL +# label.remove.ACL=Remove ACL +# label.tier=Tier +# label.network.ACL=Network ACL +# label.network.ACL.total=Network ACL Total +# label.add.new.gateway=Add new gateway +# message.add.new.gateway.to.vpc=Please specify the information to add a new gateway to this VPC. +# label.delete.gateway=delete gateway +# message.delete.gateway=Please confirm you want to delete the gateway +# label.CIDR.of.destination.network=CIDR of destination network +# label.add.route=Add route +# label.add.static.route=Add static route +# label.remove.static.route=Remove static route +# label.site.to.site.VPN=site-to-site VPN +# label.add.VPN.gateway=Add VPN Gateway +# message.add.VPN.gateway=Please confirm that you want to add a VPN Gateway +# label.VPN.gateway=VPN Gateway +# label.delete.VPN.gateway=delete VPN Gateway +# message.delete.VPN.gateway=Please confirm that you want to delete this VPN Gateway +# label.VPN.connection=VPN Connection +# label.IPsec.preshared.key=IPsec Preshared-Key +# label.IKE.policy=IKE policy +# label.ESP.policy=ESP policy +# label.create.VPN.connection=Create VPN Connection +# label.VPN.customer.gateway=VPN Customer Gateway +# label.CIDR.list=CIDR list +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.reset.VPN.connection=Reset VPN connection +# message.reset.VPN.connection=Please confirm that you want to reset VPN connection +# label.delete.VPN.connection=delete VPN connection +# message.delete.VPN.connection=Please confirm that you want to delete VPN connection +# label.add.new.tier=Add new tier +# label.add.VM.to.tier=Add VM to tier +# label.remove.tier=Remove tier + +# label.local.storage.enabled=Local storage enabled +# label.associated.network=Associated Network +# label.add.port.forwarding.rule=Add port forwarding rule +# label.dns=DNS + +# label.vpc=VPC +# label.vpc.id=VPC ID +# label.tier=Tier +# label.add.vpc=Add VPC +# label.super.cidr.for.guest.networks=Super CIDR for Guest Networks +# label.DNS.domain.for.guest.networks=DNS domain for Guest Networks +# label.configure.vpc=Configure VPC +# label.edit.vpc=Edit VPC +# label.restart.vpc=restart VPC +# message.restart.vpc=Please confirm that you want to restart the VPC +# label.remove.vpc=remove VPC +# message.remove.vpc=Please confirm that you want to remove the VPC +# label.vpn.customer.gateway=VPN Customer Gateway +# label.add.vpn.customer.gateway=Add VPN Customer Gateway +# label.IKE.encryption=IKE Encryption +# label.IKE.hash=IKE Hash +# label.IKE.DH=IKE DH +# label.ESP.encryption=ESP Encryption +# label.ESP.hash=ESP Hash +# label.perfect.forward.secrecy=Perfect Forward Secrecy +# label.IKE.lifetime=IKE Lifetime (second) +# label.ESP.lifetime=ESP Lifetime(second) +# label.dead.peer.detection=Dead Peer Detection +# label.delete.VPN.customer.gateway=delete VPN Customer Gateway +# message.delete.VPN.customer.gateway=Please confirm that you want to delete this VPN Customer Gateway + +label.network.domain.text=ТекÑÑ‚ домена Ñети +label.memory.mb=ПамÑть (в МБ) +label.cpu.mhz=CPU (в Мгц) + +message.action.remove.host=Удаление поÑледнего/единÑтвенного Ñервера в клаÑтере и Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð°Ñ ÐµÐ³Ð¾ уÑтановка приведет уничтожению рабочего окружениÑ/базы данных на Ñервере и Ñделае гоÑтевые машины непригодными к иÑпользованию. + +message.action.reboot.router=Подтвердите, что вы дейÑтвительно хотите перезагрузить Ñтот роутер. +message.action.stop.router=Подтвердите, что вы дейÑтвительно хотите оÑтановить Ñтот роутер. +message.restart.network=Подтвердите, что вы дейÑтвительно хотите перезапуÑтить Ñеть. + + +label.ipaddress=IP адреÑÑа +label.vcdcname=Ð˜Ð¼Ñ vCenter DC +label.vcipaddress=vCenter IP ÐдреÑÑ +label.vsmctrlvlanid=Управление VLAN ID +label.vsmpktvlanid=Пакет VLAN ID +label.vsmstoragevlanid=Хранение VLAN ID +label.nexusVswitch=Nexus Vswitch +label.action.delete.nexusVswitch=Удалить NexusVswitch +label.action.enable.nexusVswitch=Включить NexusVswitch +label.action.disable.nexusVswitch=Отключить NexusVswitch +label.action.list.nexusVswitch=ЛиÑÑ‚ NexusVswitch +message.action.delete.nexusVswitch=ПожалуйÑта, подтвердите, что вы хотите удалить Ñто nexusVswitch. +message.action.enable.nexusVswitch=ПожалуйÑта, подтвердите, что вы хотите включить Ñто nexusVswitch. +message.action.disable.nexusVswitch=ПожалуйÑта, подтвердите, что вы хотите отключить Ñту nexusVswitch. +message.specify.url=ПожалуйÑта, укажите URL +label.select.instance.to.attach.volume.to=Выбирите Ñервер Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¾Ð±ÑŒÐµÐ¼Ð° +label.upload=Загрузить +label.upload.volume=Добавить объем +label.virtual.routers=Виртуальный роутер +label.primary.storage.count=Первичный архив Ð´Ð»Ñ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ +label.secondary.storage.count=Вторичный архив Ð´Ð»Ñ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ +label.number.of.system.vms=КоличеÑтво ÑиÑтемы виртуальных машин +label.number.of.virtual.routers=КоличеÑтво виртуальных маршрутизаторов +label.action.register.iso=РегиÑÑ‚Ñ€Ð°Ñ†Ð¸Ñ ISO +label.isolation.method=Метод изолÑции +label.action.register.template=РегиÑÑ‚Ñ€Ð°Ñ†Ð¸Ñ ÑˆÐ°Ð±Ð»Ð¾Ð½Ð° +label.checksum=Проверить MD5 Ñумму +label.vpn=VPN +label.vlan=VLAN + + +label.management.ips=Панель ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ IP адреÑÑами +label.devices=УÑтройÑтво +label.rules=Правила +label.traffic.label=Трафик +label.vm.state=Ð¡Ñ‚Ð°Ñ‚ÑƒÑ Ñервера +message.setup.physical.network.during.zone.creation.basic=При Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð² оÑновную зону, вы можите Ñоздать одну физичеÑкую Ñеть, ÐºÐ¾Ñ‚Ð¾Ñ€Ð°Ñ ÑоотвеÑтвует NIC на гипервизор. Сеть оÑущеÑтвлÑет неÑколько видов трафика.

Ð’Ñ‹ можете также перетаÑкивать drag and drop другие типы трафика на физичеÑкие Ñети. +label.domain.router=Машрутизатор +label.console.proxy=ПрокÑи +label.secondary.storage.vm=Вторичный файловый Ñервер +label.add.netScaler.device=Добавить Netscaler уÑтройÑтво +label.add.F5.device=Добавить F5 уÑтройво +label.add.SRX.device=Добавить SRX уÑтройÑтво +label.account.and.security.group=Ðккаунт, группы безопаÑноÑти +label.fetch.latest=Выборка поÑледних +label.system.offering=СиÑтема Ñ€Ð°Ð·Ð¼ÐµÑ‰ÐµÐ½Ð¸Ñ +message.validate.instance.name=Ð˜Ð¼Ñ Ñервера не может быть длинее 63 Ñимвола. Только ASCII, буквы a~z, A~Z, цыфры 0~9, Ð´ÐµÑ„Ð¸Ñ Ð½Ðµ допуÑкаетÑÑ. Должна начинатьÑÑ Ñ Ð±ÑƒÐºÐ²Ñ‹ и заканчиватьÑÑ Ð±ÑƒÐºÐ²Ð¾Ð¹ или цифрой. + + +label.isolated.networks=Изолированные Ñети +label.latest.events=ПоÑледнии ÑÐ¾Ð±Ñ‹Ñ‚Ð¸Ñ +state.Enabled=Включено +label.system.wide.capacity=ОбщеÑиÑтемного потенциала +label.network.service.providers=ПоÑтавщики Ñетевых Ñлужб +message.launch.zone=Зона готова к запуÑку, пожалуйÑта, перейдите к Ñледующему шагу. +error.unable.to.reach.management.server=Ðе удаетÑÑ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡Ð¸Ñ‚ÑŒÑÑ Ðº Ñерверу ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ +label.internal.name=Внутреннее Ð¸Ð¼Ñ +message.configure.all.traffic.types=У Ð²Ð°Ñ ÐµÑть неÑколько физичеÑких Ñетей, пожалуйÑта, наÑтроить метки Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ типа трафика, нажав на кнопку Изменить. +message.edit.traffic.type=ПожалуйÑта, укажите трафик метки вы хотите, ÑвÑзанных Ñ Ñтим типом трафика. +label.edit.traffic.type=Изменить тип трафика +label.label=Метка +label.max.networks=МакÑимум Ñетей +error.invalid.username.password=Ðеправильній логин или пароль +message.enabling.security.group.provider=Включение поÑтавщика заÑищеной Ñети +message.adding.Netscaler.provider=Добавить Netscaler +message.creating.guest.network=Создать гоÑтевую Ñеть +label.action.delete.physical.network=Удаление физичеÑкой Ñети +message.action.delete.physical.network=ПожалуйÑта, подтвердите, что вы хотите удалить Ñтот физичеÑкую Ñеть +message.installWizard.copy.whatIsAHost=Узел - Ñто отдельный компьютер. Узлы предоÑтавлÑÑŽÑ‚ вычиÑлительные реÑурÑÑ‹ Ð´Ð»Ñ Ð·Ð°Ð¿ÑƒÑка гоÑтевых виртуальных машин. Каждый узел Ñодержит гипервизор Ð´Ð»Ñ ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð’Ðœ (кроме узлов BareMetal, они ÑвлÑÑŽÑ‚ÑÑ Ð¸Ñключением из правил и раÑÑматриваетÑÑ Ð² раÑширенном руководÑтве по уÑтановке). Ðапример, Ñто Linux-Ñервер Ñ KVM, Ñервер Citrix XenServer или Ñервер ESXI. При проÑтой уÑтановке вы можете иÑпользовать один узел Ñ XenServer.

Узел - Ñто Ð½Ð°Ð¸Ð¼ÐµÐ½ÑŒÑˆÐ°Ñ ÐµÐ´Ð¸Ð½Ð¸Ñ†Ð° в платформе CloudStack&\#8482;, далее узлы раÑпологаютÑÑ Ð² клаÑтерах, клаÑтеры - в Ñтендах, Ñтенды - в зонах. + + +label.add.compute.offering=Добавить вычиÑÐ»ÐµÐ½Ð¸Ñ Ð¿Ñ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ðµ +label.compute.offering=ВычиÑлить предложение +label.compute.offerings=ВычиÑлить предложений +label.select.offering=Выберите предложение +label.menu.infrastructure=ИнфорÑтруктура +label.sticky.tablesize=Размер таблицы +label.sticky.expire=ИÑтекает +label.sticky.cookie-name=Cookie Ð¸Ð¼Ñ +label.sticky.mode=Режим +label.sticky.length=Длина +label.sticky.holdtime=Ð²Ñ€ÐµÐ¼Ñ ÑƒÐ´ÐµÑ€Ð¶Ð°Ð½Ð¸Ñ +label.sticky.request-learn=ТребуетÑÑ Ð¸Ð·ÑƒÑ‡ÐµÐ½Ð¸Ðµ. +label.sticky.prefix=ÐŸÑ€ÐµÑ„Ð¸ÐºÑ +label.sticky.nocache=Ðет кÑша +label.sticky.indirect=КоÑвенный +label.sticky.postonly=Сообщение только +label.sticky.domain=Домен +state.Allocating=Выделение +state.Migrating=Мигрирующий +error.please.specify.physical.network.tags=Сеть предложений не доÑтупна, пока вы указать теги Ð´Ð»Ñ Ñтого физичеÑкой Ñети. + + +state.Stopping=ОÑтановить +message.add.load.balancer.under.ip=Правило баланÑировки нагрузки был добавлен в IP\: +message.select.instance=ПожалуйÑта, выберите Ñервер. +label.select=Выбрать +label.select.vm.for.static.nat=Выбор VM Ð´Ð»Ñ NAT +label.select.instance=Выбирите Ñервер +label.nat.port.range=NAT диапазон портов +label.static.nat.vm.details=СтатиÑтика NAT виртуальных машин +label.edit.lb.rule=Редактировать LB правила +message.migrate.instance.to.host=Подтвердите, что вы дейÑтвительно хотите перенеÑти машину на другой узел. +label.migrate.instance.to.host=ÐŸÐµÑ€ÐµÐ½Ð¾Ñ Ð¼Ð°ÑˆÐ¸Ð½Ñ‹ на другой узел +message.migrate.instance.to.ps=Подтвердите, что вы дейÑтвительно хотите перенеÑти машину на другое оÑновное хранилище. +label.migrate.instance.to.ps=ÐŸÐµÑ€ÐµÐ½Ð¾Ñ Ð¼Ð°ÑˆÐ¸Ð½Ñ‹ на другое оÑновное хранилище +label.corrections.saved=Ð˜Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ñохранены +message.installWizard.copy.whatIsSecondaryStorage=Дополнительное хранилище привÑзано к зоне и Ñодержит Ñледующее\:
  • Шаблоны - образы ОС, которые можно иÑпользовать Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ ВМ и Ñодержащие дополнительную информацию, такую как уÑтановленные приложениÑ.
  • Образы ISO - Ñто загрузочные или незагрузочные образы ОС
  • Снимки диÑковых томов - Ñохраненные копии данных ВМ, которых можно иÑпользовать Ð´Ð»Ñ Ð²Ð¾ÑÑÑ‚Ð°Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ… или Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ шаблона
+message.installWizard.copy.whatIsPrimaryStorage=CloudStack&\#8482; - Ñто Ð¾Ð±Ð»Ð°Ñ‡Ð½Ð°Ñ Ð¿Ð»Ð°Ñ‚Ñ„Ð¾Ñ€Ð¼Ð°, иÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑŽÑ‰Ð°Ñ Ð´Ð²Ð° типа хранилища\: оÑновное и дополнительное. Ð’ качеÑтве хранилищ можно иÑпользовать iSCSI или NFS-Ñервер, а также локальный диÑк.

ОÑновное хранилище привÑзано к клаÑтеру и Ñодержит диÑковые тома каждой ВМ, запущенной в узлах Ñтого клаÑтера. Как правило, оÑновное хранилище размещаетÑÑ Ð² Ñамих узлах. +message.installWizard.copy.whatIsACluster=КлаÑтер предоÑтавлÑет группы узлов. Узлы в клаÑтере имеют одинаковое оборудование, запущены в одинаковом гипервизере, находÑÑ‚ÑÑ Ð² одной подÑети и имеют доÑтуп к одному и тому же общему хранилищу. Виртуальные машины могут быть перенеÑены "вживую" Ñ Ð¾Ð´Ð½Ð¾Ð³Ð¾ узла на другой в пределах клаÑтера, без оÑтановки Ñлужб пользователем. КлаÑтер - Ñ‚Ñ€ÐµÑ‚ÑŒÑ Ð¿Ð¾ размерноÑти единица в платформе CloudStack&\#8482;. КлаÑтеры раÑпоогаютÑÑ Ð² Ñтендах, а Ñтенды - в зонах.

CloudStack&\#8482; разрешает иÑпользовать неÑколько клаÑтеров, но при проÑтой уÑтановке Ñта возможноÑть отÑутÑтвует. +message.installWizard.copy.whatIsAPod=Стенд, как правило, предоÑтавлÑет одну Ñтойку Ñ Ð¼Ð°ÑˆÐ¸Ð½Ð°Ð¼Ð¸. Узлы в одном Ñтенде раÑположены в одной подÑети.

Стенд - Ð²Ñ‚Ð¾Ñ€Ð°Ñ Ð¿Ð¾ размерноÑти единица в платформе CloudStack&\#8482;. Стенды раÑпологаютÑÑ Ð² зонах. ÐšÐ°Ð¶Ð´Ð°Ñ Ð·Ð¾Ð½Ð° может Ñодержать неÑколько Ñтендов, но при проÑтой уÑтановке в зоне можно Ñоздать лишь один Ñтенд. +message.installWizard.copy.whatIsAZone=Зона - Ñто наиболее ÐºÑ€ÑƒÐ¿Ð½Ð°Ñ Ð¾Ñ€Ð³Ð°Ð½Ð¸Ð·Ð°Ñ†Ð¸Ð¾Ð½Ð½Ð°Ñ ÐµÐ´Ð¸Ð½Ð¸Ñ†Ð° в платформе CloudStack&\#8482;. Зона обычно ÑоответÑтвует единичному ЦОД, Ñ…Ð¾Ñ‚Ñ Ð¸Ð¼ÐµÐµÑ‚ÑÑ Ð²Ð¾Ð·Ð¼Ð¾Ð¶Ð½Ð¾Ñть иÑпользовать неÑколько зон в пределах одного ЦОД. ОÑновным преимущеÑтвом поÑÑ‚Ñ€Ð¾ÐµÐ½Ð¸Ñ Ð¸Ð½Ñ„Ñ€Ð°Ñтруктуры Ñ Ð¸Ñпользование зон ÑвлÑетÑÑ Ð¾Ð±ÐµÑпечение Ð¸Ð·Ð¾Ð»Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¸ избыточноÑти. Ðапример, ÐºÐ°Ð¶Ð´Ð°Ñ Ð·Ð¾Ð½Ð° может иметь Ñвой блок Ð¿Ð¸Ñ‚Ð°Ð½Ð¸Ñ Ð¸ Ñеть, а Ñами зоны могут широко раÑположены географичеÑки. +message.installWizard.copy.whatIsCloudStack=CloudStack&\#8482 - Ñто Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð½Ð°Ñ Ð¿Ð»Ð°Ñ„Ñ‚Ð¾Ñ€Ð¼Ð° Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð¿ÑƒÐ±Ð»Ð¸Ñ‡Ð½Ñ‹Ñ…, чаÑтных и гибридных облаков по Ñхеме «ИнфраÑтруктура как ÑервиÑ» (IaaS). CloudStack&\#8482 управлÑет Ñетью, хранилищем и вычиÑлительными узлами, входÑщие в облачную инфраÑтруктуру. Главным образом, CloudStack&\#8482 иÑпользуетÑÑ Ð´Ð»Ñ Ñ€Ð°Ð·Ð²ÐµÑ€Ñ‚Ñ‹Ð²Ð°Ð½Ð¸Ñ, ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¸ наÑтройкой Ñложных облачных решений.

CloudStack&\#8482 реализует предоÑтавление как уÑлуги целого центра обработки данных Ñ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ñ‹Ð¼Ð¸ компонентами Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ñложных инфраÑтруктур на оÑнове облака. Мы можете выбрать между Ñвободной и БезнеÑ-верÑиÑми, которые почти ничем не отличаютÑÑ. +message.installWizard.tooltip.addSecondaryStorage.path=Путь ÑкÑпорта, раÑположенный на вышеуказанном Ñервере. +message.installWizard.tooltip.addSecondaryStorage.nfsServer=IP-Ð°Ð´Ñ€ÐµÑ Ñервера NFS, где находитÑÑ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ðµ хранилище +message.installWizard.tooltip.addPrimaryStorage.path=(Ð´Ð»Ñ NFS) Ð’ NFS Ñто путь Ñкпорта Ñервера. Путь (Ð´Ð»Ñ ÐžÑ‚ÐºÑ€Ñ‹Ñ‚Ð¾Ð¹Ð¢Ð¾Ñ‡ÐºÐ¸Ð”Ð¾Ñтупа). Ð’ KVM Ñто путь Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð³Ð¾ узла, который указывает раÑположение оÑновного хранилища. Ðапример, "/mnt/primary". +message.installWizard.tooltip.addPrimaryStorage.server=(Ð´Ð»Ñ NFS, iSCSI или PreSetup) IP-Ð°Ð´Ñ€ÐµÑ Ð¸Ð»Ð¸ Ð¸Ð¼Ñ DNS уÑтройÑтва хранилища. +message.installWizard.tooltip.addPrimaryStorage.name=Ð˜Ð¼Ñ ÑƒÑтройÑтва хранилища. +message.installWizard.tooltip.addHost.password=Этот пароль Ð´Ð»Ñ Ð²Ñ‹ÑˆÐµÑƒÐºÐ°Ð·Ð°Ð½Ð½Ð¾Ð³Ð¾ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ (Ñ Ð²Ð°ÑˆÐµÐ³Ð¾ XenServer) +message.installWizard.tooltip.addHost.username=Обычно root. +message.installWizard.tooltip.addHost.hostname=Ð˜Ð¼Ñ DNS или IP-Ð°Ð´Ñ€ÐµÑ ÑƒÐ·Ð»Ð°. +message.installWizard.tooltip.addCluster.name=Ð˜Ð¼Ñ ÐºÐ»Ð°Ñтера. Ð’Ñ‹ можете Ñами выбрать имÑ, не иÑпользуемый Cloudstack. +message.installWizard.tooltip.addPod.reservedSystemEndIp=Это диапазон IP чаÑтной Ñети, который иÑпользуетÑÑ CloudStack Ð´Ð»Ñ Ð’Ðœ дополнительного хранилища и конÑольного прокÑи. Эти адреÑа получаютÑÑ Ð¸Ð· Ñети вычиÑлительных Ñерверов. +message.installWizard.tooltip.addPod.reservedSystemStartIp=Это диапазон IP чаÑтной Ñети, который иÑпользуетÑÑ CloudStack Ð´Ð»Ñ Ð’Ðœ дополнительного хранилища и конÑольного прокÑи. Эти адреÑа получаютÑÑ Ð¸Ð· Ñети вычиÑлительных Ñерверов. +message.installWizard.tooltip.addPod.reservedSystemNetmask=Ð¡ÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð°Ñка подÑети Ð´Ð»Ñ Ð³Ð¾Ñтей. +message.installWizard.tooltip.addPod.reservedSystemGateway=Шлюз Ð´Ð»Ñ ÑƒÐ·Ð»Ð¾Ð² Ñтого Ñтенда. +message.installWizard.tooltip.addPod.name=Ð˜Ð¼Ñ Ñтенда +message.installWizard.tooltip.configureGuestTraffic.guestEndIp=Диапазон IP-адреÑов, которые будут доÑтупны Ð´Ð»Ñ Ð³Ð¾Ñтей Ñтой зоны. При иÑпользовании одного Ñетевого уÑтройÑтва (NIC) Ñти адреÑа должны быть в подÑети (CIDR) Ñтенда. +message.installWizard.tooltip.configureGuestTraffic.guestStartIp=Диапазон IP-адреÑов, которые будут доÑтупны Ð´Ð»Ñ Ð³Ð¾Ñтей Ñтой зоны. При иÑпользовании одного Ñетевого уÑтройÑтва (NIC) Ñти адреÑа должны быть в подÑети (CIDR) Ñтенда. +message.installWizard.tooltip.configureGuestTraffic.guestNetmask=Ð¡ÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð°Ñка подÑети Ð´Ð»Ñ Ð³Ð¾Ñтей. +message.installWizard.tooltip.configureGuestTraffic.guestGateway=Шлюз Ð´Ð»Ñ Ð³Ð¾ÑÑ‚Ñми +message.installWizard.tooltip.configureGuestTraffic.description=ОпиÑание Ñтой Ñети +message.installWizard.tooltip.configureGuestTraffic.name=Ð˜Ð¼Ñ Ñтой Ñети +message.installWizard.tooltip.addZone.internaldns2=Это cерверы DNS Ð´Ð»Ñ ÑиÑтемных ВМ Ñтой зоны. Эти Ñерверы будут доÑтупны через чаÑтный Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ ÑиÑтемной ВМ. ЧаÑтный IP-адреÑ, предоÑтавленный в Ñтенде, должен иметь маршрут к Ñтим Ñерверам DNS. +message.installWizard.tooltip.addZone.internaldns1=Это cерверы DNS Ð´Ð»Ñ ÑиÑтемных ВМ Ñтой зоны. Эти Ñерверы будут доÑтупны через чаÑтный Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ ÑиÑтемной ВМ. ЧаÑтный IP-адреÑ, предоÑтавленный в Ñтенде, должен иметь маршрут к Ñтим Ñерверам DNS. +message.installWizard.tooltip.addZone.dns2=Это cерверы DNS Ð´Ð»Ñ Ð³Ð¾Ñтевых ВМ Ñтой зоны. Эти Ñерверы будут доÑтупны через публичный интерфейÑ, который вы добавите позже. Публичные IP-адреÑа, предоÑтавленные в зоне, должны иметь маршрут к Ñтим Ñерверам DNS. +message.installWizard.tooltip.addZone.name=Ð˜Ð¼Ñ Ð·Ð¾Ð½Ñ‹ +message.installWizard.tooltip.addZone.dns1=Это cерверы DNS Ð´Ð»Ñ Ð³Ð¾Ñтевых ВМ Ñтой зоны. Эти Ñерверы будут доÑтупны через публичный интерфейÑ, который вы добавите позже. Публичные IP-адреÑа, предоÑтавленные в зоне, должны иметь маршрут к Ñтим Ñерверам DNS. +message.setup.successful=ÐаÑтройка облака завершена\! +label.may.continue=Ð’Ñ‹ можете продолжить. +error.installWizard.message=Что-то не так. ВернитеÑÑŒ назад и иÑправьте ошибки. +message.installWizard.now.building=Ваше облако ÑоздаётÑÑ... +message.installWizard.click.retry=Кликните, чтобы повторить запуÑк. +label.launch=ЗапуÑк +label.installWizard.click.launch=Кликните на кнопку запуÑка +label.congratulations=ПоздравлÑем\! +label.installWizard.addSecondaryStorageIntro.subtitle=Что такое "Дополнительное хранилище"? +label.installWizard.addSecondaryStorageIntro.title=Давайте добавим допольнительное хранилище. +label.installWizard.addPrimaryStorageIntro.subtitle=Что такое "ОÑновное хранилище"? +label.installWizard.addPrimaryStorageIntro.title=Давайте добавим оÑновное хранилище +label.installWizard.addHostIntro.subtitle=Что такое "Узел"? +label.installWizard.addHostIntro.title=Давайте добавим узел +label.installWizard.addClusterIntro.subtitle=Что такое "КлаÑтер"? +label.installWizard.addClusterIntro.title=Давайте добавим клаÑтер +label.installWizard.addPodIntro.subtitle=Что такое "Стенд"? +label.installWizard.addPodIntro.title=Давайте добавим Ñтенд +label.installWizard.addZone.title=Добавить зону +label.installWizard.addZoneIntro.subtitle=Что такое "Зона"? +label.installWizard.addZoneIntro.title=Давайте добавим зону +error.password.not.match=Пароли не Ñовпадают +label.confirm.password=Подтвердите пароль +message.change.password=Измените ваш пароль. +label.save.and.continue=Сохранить и продолжить +label.skip.guide=Я уже великий маÑтер CloudStack, пропуÑтить Ñто руководÑтво +label.continue.basic.install=Продолжить проÑтую уÑтановку +label.introduction.to.cloudstack=Введение в CloudStack +label.what.is.cloudstack=Что такое CloudStack? +label.hints=ПодÑказки +label.installWizard.subtitle=Это руководÑтво наÑтроит ваш CloudStack. +label.continue=Продолжить +label.installWizard.title=ЗдравÑтвуйте и добро пожаловать в CloudStack\! +label.agree=СоглаÑен +label.manage.resources=Управление реÑурÑами +label.port.forwarding.policies=Политики проброÑа портов +label.load.balancing.policies=Политики баланÑировки нагрузки +label.networking.and.security=Сеть и безопаÑноÑть +label.bandwidth=ПропуÑÐºÐ½Ð°Ñ ÑпоÑобноÑть +label.virtual.machines=Виртуальные машины +label.compute.and.storage=ВычиÑÐ»ÐµÐ½Ð¸Ñ Ð¸ хранилище +label.task.completed=Задача выполнена +label.update.project.resources=Обновить реÑурÑÑ‹ проекта +label.remove.project.account=Удалить учетную запиÑÑŒ проекта +label.item.listing=СпиÑок Ñлементов +message.select.item=Выберите Ñлемент +label.removing=Удаление +label.invite=ПриглаÑить +label.add.by=Добавить +label.max.vms=МакÑ. количеÑтво пользовательÑких ВМ +label.max.public.ips=МакÑ. публичных IP +label.max.volumes=МакÑ. томов +label.max.snapshots=МакÑ. Ñнимков +label.max.templates=МакÑ. шаблонов +# label.max.vpcs=Max. VPCs +label.project.dashboard=Панель проекта +label.remind.later=Предупредить позже +label.invited.accounts=Приглашённые учетные запиÑи +label.invite.to=ПриглаÑить +label.add.accounts.to=Добавить учётные запиÑи +label.add.accounts=Добавить аккаунты +label.project.name=Ð˜Ð¼Ñ Ð¿Ñ€Ð¾ÐµÐºÑ‚Ð° +label.create.project=Создать проект +label.networks=Сети +label.launch.vm=ЗапуÑк ВМ +label.new.vm=ÐÐ¾Ð²Ð°Ñ Ð’Ðœ +label.previous=Предыдущий +label.add.to.group=Добавить в группу +message.vm.review.launch=Проверьте Ñледующую информацию и удоÑтоверьтеÑÑŒ в том, что ваша машина наÑтроена правильно. +message.select.security.groups=Выберите группу/группы безопаÑноÑти Ð´Ð»Ñ Ð½Ð¾Ð²Ð¾Ð¹ ВМ +label.new=Создать +message.please.select.networks=Выберите Ñети Ð´Ð»Ñ Ð²Ð¸Ñ€Ñ‚ÑƒÐ°Ð»ÑŒÐ½Ð¾Ð¹ машины +message.please.proceed=Перейдите к Ñледующему шагу +message.zone.no.network.selection=Ð’Ñ‹Ð±Ñ€Ð°Ð½Ð½Ð°Ñ Ð·Ð¾Ð½Ð° не имеет вариантов Ð´Ð»Ñ Ð²Ñ‹Ð±Ð¾Ñ€Ð° Ñети. +label.no.thanks=Ðет, ÑпаÑибо +label.my.templates=Мои шаблоны +message.select.template=Выберите шаблон Ð´Ð»Ñ Ð½Ð¾Ð²Ð¾Ð¹ ВМ +message.select.iso=Выберите образ ISO Ð´Ð»Ñ Ð½Ð¾Ð²Ð¾Ð¹ ВМ +message.template.desc=Образ ОС, который можно иÑпользовать в качеÑтве загрузочной в ВМ +message.iso.desc=Образ диÑка Ñодержит загрузочные или незагрузочные данные Ð´Ð»Ñ ÐžÐ¡. +label.select.iso.or.template=Выберите ISO или шаблон +message.select.a.zone=Зона обычно ÑоответÑтвует единичному центру обработки данных. ÐеÑколько зоныпомогают Ñоздавать более надежные облака, обеÑÐ¿ÐµÑ‡Ð¸Ð²Ð°Ñ Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑкую изолÑцию и избыточноÑть. +label.select.a.zone=Выберите зону +label.review=Обзор +label.select.a.template=Выберите шаблон +label.setup=ÐаÑтройка +state.Allocated=РаÑпределено +changed.item.properties=Параметры Ñлемента изменены +label.apply=Применить +label.default=По умолчанию +label.viewing=ПроÑмотр +label.move.to.top=ПеремеÑтить на Ñамый верх +label.move.up.row=ПеремеÑтить на одну Ñтроку выше +label.move.down.row=ПеремеÑтить на одну Ñтроку ниже +# label.move.to.bottom=Move to bottom +label.drag.new.position=ПеремеÑтить на новую позицию +label.order=Очередь +label.no.data=Ðет информации Ð´Ð»Ñ Ð¿Ð¾ÐºÐ°Ð·Ð° +label.change.value=Изменить значение +label.clear.list=ОчиÑтить ÑпиÑок +label.full.path=Полный путь +message.add.domain=Укажите поддомен, где вы хотите Ñоздать ваш домен +message.delete.user=Подтвердите, что вы дейÑтвительно хотите удалить Ñтого пользователÑ. +message.enable.user=Подтвердите, что вы дейÑтвительно хотите включить Ñтого пользователÑ. +message.disable.user=Подтвердите, что вы дейÑтвительно хотите выключить Ñтого пользователÑ. +message.generate.keys=Подтвердите, что вы дейÑтвительно хотите Ñоздать новые ключи Ð´Ð»Ñ Ñтого пользователÑ. +message.update.resource.count=Подтвердите, что вы дейÑтвительно хотите обновить Ñчетчик реÑурÑов Ð´Ð»Ñ Ñтого аккаунта. +message.edit.account=Редактировать (значение "-1" показывает отÑутÑтвие пределов Ð´Ð»Ñ Ñ€ÐµÑурÑа) +label.total.of.vm=Ð’Ñего ВМ +label.total.of.ip=Ð’Ñего IP-адреÑов +state.enabled=Включено +message.action.download.iso=Подтвердите, что вы дейÑтвительно хотите загрузить Ñтот ISO. +message.action.download.template=Подтвердите, что вы дейÑтвительно хотите загрузить Ñтот шаблон. +label.destination.zone=Ð¦ÐµÐ»ÐµÐ²Ð°Ñ Ð·Ð¾Ð½Ð° +label.keyboard.type=Тип клавиатуры +label.nic.adapter.type=Тип Ñетевой карты (NIC) +label.root.disk.controller=Контроллер корневого диÑка +label.community=СообщеÑтво +label.remove.egress.rule=Удалить выходное правило +label.add.egress.rule=Добавить выходное правило +label.egress.rule=Выходное правило +label.remove.ingress.rule=Удалить входное правило +label.delete.vpn.user=Удалить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ VPN +label.add.vpn.user=Добавить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ VPN +label.remove.pf=Удалить правило проброÑа порта +label.remove.vm.from.lb=Удалить ВМ Ñ Ð¿Ñ€Ð°Ð²Ð¸Ð»Ð° баланÑировки нагрузки +label.add.vms.to.lb=Добавить ВМ в правило баланÑировки нагрузки +label.add.vm=Добавить ВМ +label.remove.static.nat.rule=Удалить правило Ñтатичного NAT +label.remove.rule=Удалить правило +label.add.static.nat.rule=Добавить правило Ñтатичного NAT +label.add.rule=Добавить правило +label.configuration=ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð°Ñ†Ð¸Ñ +message.disable.vpn=Ð’Ñ‹ дейÑтвительно хотите выключить VPN? +label.disable.vpn=Выключить VPN +message.enable.vpn=Подтвердите, что вы дейÑтвительно хотите открыть доÑтуп к VPN Ð´Ð»Ñ Ñтого IP-адреÑа. +label.enable.vpn=Включить VPN +message.acquire.new.ip=Подтвердите, что вы дейÑтвительно хотите получить "белый" IP Ð´Ð»Ñ Ñтой Ñети. +label.elastic=Гибкий +label.my.network=ÐœÐ¾Ñ Ñеть +label.add.vms=Добавить ВМ +label.configure=ÐаÑтроить +label.stickiness=Липкий +label.source=ИÑточник +label.least.connections=Least connections +label.round.robin=Round-robin +label.restart.required=ТребуетÑÑ Ð¿ÐµÑ€ÐµÐ·Ð°Ð¿ÑƒÑк +label.clean.up=ОчиÑтить +label.restart.network=ПерезапуÑтить Ñеть +label.edit.network.details=Редактировать детали Ñети +label.add.guest.network=Добавить гоÑтевую Ñеть +label.guest.networks=ГоÑтевые Ñети +message.ip.address.changed=Ваши IP-адреÑа могли быть изменены, хотите обновить ÑпиÑок адреÑов? Помните, что в Ñтом Ñлучае облаÑть деталей будет закрыта. +state.BackingUp=Резервное копирование +state.BackedUp=Зарезервировано +label.done=Готово +label.vm.name=Ð˜Ð¼Ñ VM +message.migrate.volume=Подтвердите, что вы дейÑтвительно хотите перенеÑти том в другое оÑновное хранилище. +label.migrate.volume=ПеренеÑти том в другое оÑновное хранилище +message.create.template=Ð’Ñ‹ дейÑтвительно хотите Ñоздать шаблонн? +label.create.template=Создать шаблон +message.download.volume.confirm=Подтвердите, что вы дейÑтвительно загрузить Ñтот том +message.detach.disk=Ð’Ñ‹ дейÑтвительно хотите приÑоединить Ñтот диÑк? +state.ready=Готов +state.Ready=Готов +label.vm.display.name=Отображаемое Ð¸Ð¼Ñ Ð’Ðœ +label.select-view=Выберите вид +label.local.storage=Локальное хранилище +label.direct.ips=ПрÑмые IP-адреÑа +label.view.all=ПроÑмотреть вÑÑ‘ +label.zone.details=ПодробноÑти зоны +message.alert.state.detected=Обнаружен Ñигнал тревоги +state.Starting=ЗапуÑкаетÑÑ +state.Expunging=Удалён +state.Creating=СоздаетÑÑ +message.decline.invitation=Подтвердите, что вы хотите отменить приглашение на проект. +label.decline.invitation=Отменить приглашение +message.confirm.join.project=Подтвердите приÑоединение к проекту. +message.join.project=Теперь вы приÑоединены к проекту. Выберите "Проектный вид" Ð´Ð»Ñ Ð¿Ñ€Ð¾Ñмотра проекта. +label.accept.project.invitation=ПринÑть приглашение на проект +label.token=Талон +label.project.id=ID проекта +message.enter.token=Введите ключ, который вы получили в приглаÑительном пиÑьме +label.enter.token=Введите талон +state.Accepted=ПринÑто +state.Pending=ОжидаетÑÑ +state.Completed=Завершено +state.Declined=Отклонено +label.project=Проект +label.invitations=ÐŸÑ€Ð¸Ð³Ð»Ð°ÑˆÐµÐ½Ð¸Ñ +label.delete.project=Удалить проект +message.delete.project=Ð’Ñ‹ дейÑтвительно хотите удалить Ñтот проект? +message.activate.project=Ð’Ñ‹ дейÑтвительно хотите запуÑтить Ñтот проект? +label.activate.project=ЗапуÑтить проект +label.suspend.project=ПриоÑтановить проект +message.suspend.project=Ð’Ñ‹ дейÑтвительно хотите приоÑтановить проект? +state.Suspended=ПриоÑтановлено +label.edit.project.details=Редактировать детали проекта +label.new.project=Ðовый проект +state.Active=Включен +state.Disabled=Выключен +label.projects=Проекты +label.make.project.owner=Сделать аккаунт владельцем проекта +label.remove.project.account=Удалить учетную запиÑÑŒ проекта +message.project.invite.sent=Приглашение было отправлено пользователю; он будет добавлен в проект поÑле Ð¿Ð¾Ð´Ñ‚Ð²ÐµÑ€Ð¶Ð´ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¸Ð³Ð»Ð°ÑˆÐµÐ½Ð¸Ñ. +label.add.account.to.project=Добавить аккаунт в проект +label.revoke.project.invite=Отозвать приглашение +label.project.invite=ПриглаÑить в проект +label.select.project=Выберите проект +message.no.projects=У Ð²Ð°Ñ Ð½ÐµÑ‚ проектов.
Создайте новый проект в Ñекции "Проекты" +message.no.projects.adminOnly=У Ð²Ð°Ñ Ð½ÐµÑ‚ проектовю
ОбратитеÑÑŒ к вашему админиÑтратору Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ проекта. +message.pending.projects.1=Ð’ ожидании Ñледующие приглашениÑ\: +message.pending.projects.2=Ð”Ð»Ñ Ð¿Ñ€Ð¾Ñмотра перейдите к раздел проектов, далее выберите Ð¿Ñ€Ð¸Ð³Ð»Ð°ÑˆÐµÐ½Ð¸Ñ Ð¸Ð· выпадающего меню. +message.instanceWizard.noTemplates=Ð’Ñ‹ не имеете доÑтупных шаблонов; Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ·Ð°Ð¿ÑƒÑка машины добавьте ÑовмеÑтивый шаблон. +label.view=Вид +instances.actions.reboot.label=Перезагрузить машину +label.filterBy=Фильтровать +label.ok=OK +notification.reboot.instance=Перезагрузить машину +notification.start.instance=ЗапуÑтить машину +notification.stop.instance=ОÑтановить машину +label.display.name=Отображаемое Ð¸Ð¼Ñ +label.zone.name=Ð˜Ð¼Ñ Ð·Ð¾Ð½Ñ‹ +ui.listView.filters.all=Ð’Ñе +ui.listView.filters.mine=Mine +state.Running=Запущено +state.Stopped=ОÑтановлено +state.Destroyed=Уничтожено +state.Error=Ошибка +message.reset.password.warning.notPasswordEnabled=Шаблон Ð´Ð»Ñ Ñтой машины Ñоздан без иÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ Ð¿Ð°Ñ€Ð¾Ð»Ñ +message.reset.password.warning.notStopped=Ð”Ð»Ñ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð¿Ð°Ñ€Ð¾Ð»Ñ Ð½ÐµÐ¾Ð±Ñ…Ð¾Ð´Ð¸Ð¼Ð¾ оÑтановить машину +label.notifications=ÐžÐ¿Ð¾Ð²ÐµÑ‰ÐµÐ½Ð¸Ñ +label.default.view=Стандартный вид +label.project.view=Проектный вид + +message.add.system.service.offering=Дополните Ñледующую информацию Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ реÑурÑа Ð´Ð»Ñ ÑиÑтемных Ñлужб. +message.action.delete.system.service.offering=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот реÑÑƒÑ€Ñ Ð´Ð»Ñ ÑиÑтемных Ñлужб. +label.action.delete.system.service.offering=Удалить ÑиÑтемный реÑÑƒÑ€Ñ +label.hypervisor.capabilities=ВозможноÑти гипервизора +label.hypervisor.version=ВерÑÐ¸Ñ Ð³Ð¸Ð¿ÐµÑ€Ð²Ð¸Ð·Ð¾Ñ€Ð° +label.max.guest.limit=Предел количеÑтва гоÑтей +label.add.network.offering=Добавить Ñетевой реÑÑƒÑ€Ñ +label.supported.services=Поддерживаемые Ñлужбы +label.service.capabilities=ВозможноÑти Ñлужбы +label.guest.type=Тип гоÑÑ‚Ñ +label.specify.IP.ranges=Укажите диапазон IP-адреÑов +label.conserve.mode=Экономичный режим +label.created.by.system=Создано ÑиÑтемой +label.menu.system.service.offerings=СиÑтемные реÑурÑÑ‹ +label.add.system.service.offering=Добавить ÑиÑтемный реÑÑƒÑ€Ñ +label.redundant.router.capability=ВозможноÑти резервного роутера +label.supported.source.NAT.type=Поддерживаемые типы NAT-иÑточника +label.elastic.LB=Гибкий LB +label.LB.isolation=ИзолÑÑ†Ð¸Ñ LB +label.elastic.IP=Гибкий IP +label.network.label.display.for.blank.value=ИÑп. оÑновной шлюз +label.xen.traffic.label=Метка трафика XenServer +label.kvm.traffic.label=Метка трафика KVM +label.vmware.traffic.label=Метка трафика VMware +label.start.IP=Ðачальный IP +label.end.IP=Конечный IP +label.remove.ip.range=Удалить диапазон IP +label.ip.ranges=Диапазоны IP +label.start.vlan=Ðачальный VLAN +label.end.vlan=Конечный VLAN +label.broadcast.domain.range=Диапазон широковещательного домена +label.compute=ВычиÑление +message.add.guest.network=Подтвердите, что вы дейÑтвительно хотите добавить гоÑтевую Ñеть +label.subdomain.access=ДоÑтуп к поддомену +label.guest.start.ip=Ðачальный гоÑтевой IP +label.guest.end.ip=Конечный гоÑтевой IP. +label.virtual.router=Виртуальный роутер +label.physical.network.ID=ID физичеÑкой Ñети +label.destination.physical.network.id=ID целевой физичеÑкой Ñети +label.dhcp=DHCP +label.destroy.router=Удалить роутер +message.confirm.destroy.router=Подтвердите, что вы дейÑтвительно хотите удалить роутер +label.change.service.offering=Изменить Ñлужебный реÑÑƒÑ€Ñ +label.view.console=Показать конÑоль +label.redundant.state=СоÑтоÑние резерва +label.enable.provider=Включить поÑтавщика +message.confirm.enable.provider=Подтвердите, что вы дейÑтвительно хотите включить поÑтавщика +label.disable.provider=Выключить поÑтавщика +message.confirm.disable.provider=Подтвердите, что вы дейÑтвительно хотите выключить поÑтавщика +label.shutdown.provider=Отключить поÑтавщика +message.confirm.shutdown.provider=Подтвердите, что вы дейÑтвительно хотите отключить Ñтого поÑтавщика +label.netScaler=NetScaler +label.add.new.NetScaler=Добавить новый NetScaler +label.capacity=МощноÑть +label.dedicated=Выделенный +label.f5=F5 +label.add.new.F5=Добавить новый F5 +label.srx=SRX +label.providers=ПоÑтавщики +label.add.new.SRX=Добавить новый SRX +label.timeout=Ð’Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ +label.public.network=ÐŸÑƒÐ±Ð»Ð¸Ñ‡Ð½Ð°Ñ Ñеть +label.private.network=ЧаÑÑ‚Ð½Ð°Ñ Ñеть +label.enable.swift=Включить Swift +confirm.enable.swift=Заполните нижеÑледующую информацию Ð´Ð»Ñ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶Ð¸ Swift +message.after.enable.swift=Swift наÑтроен. Примечание\: ЕÑли вы покинете Ñту Ñтраницу, вам не придетÑÑ Ð½Ð°Ñтраивать Swift Ñнова +label.key=Ключ +label.delete.NetScaler=Удалить NetScaler +message.confirm.delete.NetScaler=Подтвердите, что вы дейÑтвительно хотите удалить NetScaler +label.delete.F5=Удалить F5 +message.confirm.delete.F5=Подтвердите, что вы дейÑтвительно хотите удалить F5 +label.delete.SRX=Удалить SRX +message.confirm.delete.SRX=Подтвердите, что вы дейÑтвительно хотите удалить SRX +label.pods=Стенды +label.pod.name=Ð˜Ð¼Ñ Ñтенда +label.reserved.system.gateway=Зарезервированный ÑиÑтемный шлюз +label.reserved.system.netmask=Ð—Ð°Ñ€ÐµÐ·ÐµÑ€Ð²Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð½Ð°Ñ ÑиÑÑ‚ÐµÐ¼Ð½Ð°Ñ Ð¼Ð°Ñка +label.start.reserved.system.IP=Ðачальный зарезервированный ÑиÑтемный IP-Ð°Ð´Ñ€ÐµÑ +label.end.reserved.system.IP=Конечный зарезервированный ÑиÑтемный IP-Ð°Ð´Ñ€ÐµÑ +label.clusters=КлаÑтеры +label.cluster.name=Ð˜Ð¼Ñ ÐºÐ»Ð°Ñтера +label.host.MAC=MAC узла +label.agent.username=Ð˜Ð¼Ñ Ð°Ð³ÐµÐ½Ñ‚Ð° +label.agent.password=Пароль агента +message.confirm.action.force.reconnect=Подтвердите, что вы дейÑтвительно хотите переподключитьÑÑ Ðº узлу +label.resource.state=СоÑтоÑние реÑурÑов +label.LUN.number=LUN \# +message.confirm.remove.IP.range=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот диапазон IP. +message.tooltip.zone.name=Ð˜Ð¼Ñ Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹ +message.tooltip.dns.1=Ð˜Ð¼Ñ Ñервера DNS Ð´Ð»Ñ Ð’Ðœ Ñтой зоны. Публичные IP-адреÑа Ñтой зоны должны иметь маршрут до Ñтого Ñервера. +message.tooltip.dns.2=Ð˜Ð¼Ñ Ð²Ñ‚Ð¾Ñ€Ð¾Ð³Ð¾ Ñервера DNS Ð´Ð»Ñ Ð’Ðœ Ñтой зоны. Публичные IP-адреÑа Ñтой зоны должны иметь маршрут до Ñтого Ñервера. +message.tooltip.internal.dns.1=Ð˜Ð¼Ñ Ñервера DNS Ð´Ð»Ñ Ð²Ð½ÑƒÑ‚Ñ€ÐµÐ½Ð½Ð¸Ñ… ВМ CloudStack Ñтой зоны. ЧаÑтные IP-адреÑа Ñтендов должны иметь маршрут до Ñтого Ñервера. +message.tooltip.internal.dns.2=Ð˜Ð¼Ñ Ñервера DNS Ð´Ð»Ñ Ð²Ð½ÑƒÑ‚Ñ€ÐµÐ½Ð½Ð¸Ñ… ВМ CloudStack Ñтой зоны. ЧаÑтные IP-адреÑа Ñтендов должны иметь маршрут до Ñтого Ñервера. +message.tooltip.network.domain=Ð¡ÑƒÑ„Ñ„Ð¸ÐºÑ DNS Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ ÑобÑтвенного доменного имени Ñети, доÑтупный гоÑтевыми ВМ. +message.tooltip.pod.name=Ð˜Ð¼Ñ Ð´Ð»Ñ Ñтенда +message.tooltip.reserved.system.gateway=Шлюз Ð´Ð»Ñ ÑƒÐ·Ð»Ð¾Ð² Ñтого Ñтенда +message.tooltip.reserved.system.netmask=ÐŸÑ€ÐµÑ„Ð¸ÐºÑ Ñети, определÑющий подÑеть Ñтенда. ИÑпользуетÑÑ Ð¾Ð±Ð¾Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ðµ CIDR. +message.creating.zone=Создание зоны +message.creating.physical.networks=Создание физичеÑких Ñетей +message.configuring.physical.networks=ÐаÑтройка физичеÑких Ñетей +message.adding.Netscaler.device=Добавление уÑтройÑтва NetScaler +message.creating.pod=Создание Ñтенда +message.configuring.public.traffic=ÐаÑтройка публичного трафика +message.configuring.storage.traffic=ÐаÑтройка трафика хранилища +message.configuring.guest.traffic=ÐаÑтройка гоÑтевого трафика +message.creating.cluster=Создание клаÑтера +message.adding.host=Добавление узла +message.creating.primary.storage=Создание оÑновного хранилища +message.creating.secondary.storage=Создание дополнительного хранилища +message.Zone.creation.complete=Создание зоны завершено +message.enabling.zone=Включить зону +error.something.went.wrong.please.correct.the.following=Что-то не так, иÑправьте ошибки +error.could.not.enable.zone=Ðе удалоÑÑŒ включить зону +message.zone.creation.complete.would.you.like.to.enable.this.zone=Создание зоны завершено. Хотите включить Ñту зону? +message.please.add.at.lease.one.traffic.range=Добавьте как минимум один диапазон Ð´Ð»Ñ Ñ‚Ñ€Ð°Ñ„Ð¸ÐºÐ° +message.you.must.have.at.least.one.physical.network=Добавьте как минимум одну физичеÑкую Ñеть +message.please.select.a.different.public.and.management.network.before.removing=Выберите другую публичную и обÑлуживающую Ñеть перед удалением + +label.zone.type=Тип зоны +label.setup.zone=ÐаÑтройка зоны +label.setup.network=ÐаÑтройка Ñети +label.add.resources=Добавить реÑурÑов +label.launch=ЗапуÑк +label.set.up.zone.type=ÐаÑтроить тип зоны +message.please.select.a.configuration.for.your.zone=Выберите конфигурацию вашей зоны +message.desc.basic.zone=ПредоÑтавлÑет едиÑтвенную Ñеть, где ÐºÐ°Ð¶Ð´Ð°Ñ Ð’Ðœ имеет «белый» IP-Ð°Ð´Ñ€ÐµÑ Ñети. ИзолÑции гоÑтей можно добитьÑÑ Ð¸Ñпользованием Ñети 3-го уровнÑ, например, группы безопаÑноÑти (Ñ„Ð¸Ð»ÑŒÑ‚Ñ€Ð°Ñ†Ð¸Ñ IP-вдреÑов) +label.basic=ПроÑтой +message.desc.advanced.zone=Ð”Ð»Ñ Ð±Ð¾Ð»ÐµÐµ Ñложных Ñетевых топологий. Эта ÑÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð¾Ð´ÐµÐ»ÑŒ обеÑпечивает макÑимальную гибкоÑть в определении гоÑтевой Ñети и предоÑтавление уÑлуг, таких как межÑетевой Ñкран, VPN, или поддержка баланÑировки нагрузки. +label.advanced=Продвинутый +message.desc.zone=layer 3 +label.physical.network=ФизичеÑкие Ñети +label.public.traffic=Публичный трафик +label.guest.traffic=ГоÑтевой трафик +label.storage.traffic=Трафик хранилища +message.setup.physical.network.during.zone.creation=Во Ð²Ñ€ÐµÐ¼Ñ Ñ€Ð°Ñширенной наÑтройки зоны, вам необходимо указать один или неÑколько физичеÑких Ñетей. ÐšÐ°Ð¶Ð´Ð°Ñ Ñеть ÑоответÑтвует Ñетевому интерфейÑу гипервизора. ÐšÐ°ÐºÐ¶Ð´Ð°Ñ Ñ„Ð¸Ð·Ð¸Ñ‡ÐµÑÐºÐ°Ñ Ñеть может иÑпользоватьÑÑ Ð´Ð»Ñ Ð¾Ð´Ð½Ð¾Ð³Ð¾ или неÑкольких видов трафика Ñ Ð½ÐµÐºÐ¾Ñ‚Ð¾Ñ€Ñ‹Ð¼Ð¸ ограничениÑми при объединении видов трафика.

Перетащите один или неÑколько видов трафика к каждой физичеÑкой Ñети. +label.add.physical.network=Добавить физичеÑкую Ñеть +label.traffic.types=Типы трафика +label.management=Управление +label.guest=ГоÑть +label.please.specify.netscaler.info=Укажите данные NetScaler +message.public.traffic.in.advanced.zone=Публичный трафик генерируетÑÑ Ð¿Ñ€Ð¸ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð’Ðœ доÑтупа к Интернету. Публично доÑтупные IP должны быть обÑзательно выделены. Пользователь может ииÑпользовать CloudStack UI Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ IP и ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ NAT, иÑпользуемый Ð´Ð»Ñ Ð¾Ð±Ñ‰ÐµÐ½Ð¸Ñ Ð¼ÐµÐ¶Ð´Ñƒ гоÑтевой и публичной Ñетью.

Укажите как минимум один диапазон адреÑов Ð´Ð»Ñ Ð¸Ð½Ñ‚ÐµÑ€Ð½ÐµÑ‚-трафика. +message.public.traffic.in.basic.zone=Публичный трафик генерируетÑÑ Ð¿Ñ€Ð¸ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð’Ðœ доÑтупа к Интернету или при предоÑтавлении клиентам Ñлужб через Интернет. Публично доÑтупные IP должны быть обÑзательно выделены. При Ñоздании ВМ, Ð°Ð´Ñ€ÐµÑ Ð¸Ð· диапазона публичных Ip привÑжетÑÑ Ðº машине в дополнение гоÑтевого адреÑа IP. СтатичеÑкий 1-1 NAT должен автоматичеÑки наÑтроитьÑÑ Ð½Ð° работу между публичной и гоÑтевой Ñетью. Пользователь также имеет возможноÑть иÑпользовать CloudStack UI Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ñ‹Ñ… адреÑов Ð´Ð»Ñ Ñ€ÐµÐ°Ð»Ð¸Ð·Ð°Ñ†Ð¸Ð¸ ÑтатичеÑкого NAT между машинами и публичной Ñетью. +message.add.pod.during.zone.creation=ÐšÐ°Ð¶Ð´Ð°Ñ Ð·Ð¾Ð½Ð° Ñодержит один или более Ñтендов, который вы ÑÐµÐ¹Ñ‡Ð°Ñ Ð´Ð¾Ð±Ð°Ð²Ð¸Ñ‚Ðµ первым. Стенд Ñодержит узлы и Ñерверы оÑновного хранилища, которые будут добавлены в поÑледнем шаге. Ð”Ð»Ñ Ð½Ð°Ñ‡Ð°Ð»Ð° необходимо наÑтроить диапазон резервных адреÑов IP Ð´Ð»Ñ Ð²Ð½ÑƒÑ‚Ñ€ÐµÐ½Ð½ÐµÐ¹ Ñети управлениÑ. Диапазон резервных IP должен быть уникальным Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ зоны облака. +message.guest.traffic.in.advanced.zone=ГоÑтевой трафик Ñети ÑвÑзи между конечными пользователÑми виртуальных машин. Укажите диапазон идентификаторов VLAN проводить гоÑÑ‚Ñ Ñ‚Ñ€Ð°Ñ„Ð¸Ðº Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ физичеÑкой Ñети. +message.guest.traffic.in.basic.zone=ГоÑтевой трафик генерируетÑÑ Ð¿Ñ€Ð¸ общении между виртуальными машинами. Укажите диапазон адреÑов IP, который CloudStack Ñможет выделить Ð´Ð»Ñ Ð’Ðœ. УбедитеÑÑŒ, что Ñтот диапазон не перекрещиваетÑÑ Ñ Ð´Ð¸Ð°Ð¿Ð°Ð·Ð¾Ð½Ð¾Ð¼ резервных адреÑов. +message.storage.traffic=Трафик между внутренними реÑурÑами CloudStack, Ð²ÐºÐ»ÑŽÑ‡Ð°Ñ Ð²Ñе компоненты, которые взаимодейÑтвуют Ñ Ñервером управлениÑ, такие как виртуальные хоÑты и CloudStack ÑиÑтемы. ÐаÑтройте трафик Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ð·Ð´ÐµÑÑŒ. +message.desc.cluster=Каждый Ñтенд должен иметь один или более клаÑтеров, первый из которых вы ÑÐµÐ¹Ñ‡Ð°Ñ Ð´Ð¾Ð±Ð°Ð²Ð¸Ñ‚Ðµ. КлаÑтер предоÑтавлÑет группу узлов. Узлы в клаÑтере имеют одинаковое оборудование, запуÑкаетÑÑ Ñ‡ÐµÑ€ÐµÐ· один гипервизор, находÑÑ‚ÑÑ Ð² одной Ñети и имеют доÑтуп к одному и тому же открытому хранилищу. Каждый клаÑтер Ñодержит один или более узлов, а также иеть один или неÑколько оÑновных хранилищ. +message.desc.host=Каждый клаÑтер должен Ñодержать как минимум один узел (компьютер) Ð´Ð»Ñ Ð·Ð°Ð¿ÑƒÑка ВМ, первый из клаÑтер вы добавите ÑейчаÑ. Ð”Ð»Ñ Ñ€Ð°Ð±Ð¾Ñ‚Ñ‹ узла в CloudStack важна уÑтановка гипервизора на узел, привÑзка IP к узлу и Ñоединение узла Ñ Ñервером ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ CloudStack.

Укажите Ð¸Ð¼Ñ DNS или Ð°Ð´Ñ€ÐµÑ IP, Ð¸Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸ пароль к ОС (обычно root), а также метки Ð´Ð»Ñ Ð³Ñ€ÑƒÐ¿Ð¿Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ ÑƒÐ·Ð»Ð¾Ð². +message.desc.primary.storage=ÐšÐ°Ð¶Ð´Ð°Ñ Ð³Ñ€ÑƒÐ¿Ð¿Ð° должна Ñодержать один или неÑколько первичных Ñерверов Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ…, и мы добавим первый ÑейчаÑ. ÐŸÐµÑ€Ð²Ð¸Ñ‡Ð½Ð°Ñ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ Ñодержит логичеÑкие разделы жеÑткого диÑка Ð´Ð»Ñ Ð²Ñех виртуальных машин, работающих на узлах клаÑтера. ИÑпользуйте любой ÑовмеÑтимый протокол, который поддерживает оÑновные гипервизора. +message.desc.secondary.storage=ÐšÐ°Ð¶Ð´Ð°Ñ Ð·Ð¾Ð½Ð° должна обладать Ñ…Ð¾Ñ‚Ñ Ð±Ñ‹ одним Ñервером NFS или дополнительным хранилищем и их надо добавить в первую очередь. Дополнительное хранилище предназначено Ð´Ð»Ñ Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ ÑˆÐ°Ð±Ð»Ð¾Ð½Ð¾Ð² ВМ, образов ISO и Ñнимков ВМ. Этот Ñервер должен быть доÑтупен Ð´Ð»Ñ Ð²Ñех узлов зоны.

ПредоÑтавить IP-Ð°Ð´Ñ€ÐµÑ Ð¸ путь. +label.launch.zone=ЗапуÑтить зону +message.please.wait.while.zone.is.being.created=Подождите, ÑоздаетÑÑ Ð·Ð¾Ð½Ð°. Это может занÑть некоторое времÑ... + +label.load.balancing=БаланÑировка нагрузки +label.static.nat.enabled=СтатичеÑкий NAT включен +label.zones=Зоны +label.view.more=ПроÑмотреть больше +label.number.of.zones=КоличеÑтво зон +label.number.of.pods=КоличеÑтво Ñтендов +label.number.of.clusters=КоличеÑтво клаÑтеров +label.number.of.hosts=КоличеÑтво узлов +label.total.hosts=Ð’Ñего узлов +label.total.CPU=Ð’Ñего процеÑÑоров +label.total.memory=Ð’Ñего памÑти +label.total.storage=Ð’Ñего хранилищ +label.purpose=Ðазначение + + + + +label.action.migrate.router=ПеренеÑти роутер +label.action.migrate.router.processing=ÐŸÐµÑ€ÐµÐ½Ð¾Ñ Ñ€Ð¾ÑƒÑ‚ÐµÑ€Ð°... +message.migrate.router.confirm=Подтвердите, что вы дейÑтвительно хотите перенеÑти роутер в узел +label.migrate.router.to=ПеренеÑти роутер в + +label.action.migrate.systemvm=ПеренеÑти ÑиÑтемную ВМ +label.action.migrate.systemvm.processing=ÐŸÐµÑ€ÐµÐ½Ð¾Ñ ÑиÑтемной ВМ... +message.migrate.systemvm.confirm=Подтвердите, что вы дейÑтвительно хотите перенеÑти роутер в узел +label.migrate.systemvm.to=ПеренеÑти ÑиÑтемную ВМ в + + +mode=Режим +side.by.side=Бок-о-Бок +inline=Ð’Ñтроенный + +extractable=Извлекаемый + +label.ocfs2=OCFS2 + +label.action.edit.host=Редактировать узел + +network.rate=СкороÑть Ñети + +ICMP.type=Тип ICMP +ICMP.code=Код ICMP + +image.directory=Каталог Ñ Ð¾Ð±Ñ€Ð°Ð·Ð°Ð¼Ð¸ + +label.action.create.template.from.vm=Создать шаблон из ВМ +label.action.create.template.from.volume=Создать шаблон из тома + +message.vm.create.template.confirm=Создание шаблона автоматичеÑки перезагрузит ВМ + +label.action.manage.cluster=Управление клаÑтером +message.action.manage.cluster=Подтвердите, что вы дейÑтвительно хотите перевеÑти клаÑтер в режим обÑлуживаниÑ. +label.action.manage.cluster.processing=Переход клаÑтера в режим обÑлуживаниÑ... + +label.action.unmanage.cluster=ПеревеÑти клаÑтер в обычный режим +message.action.unmanage.cluster=Подтвердите, что вы дейÑтвительно хотите перевеÑти клаÑтер в обычный режим. +label.action.unmanage.cluster.processing=Переход клаÑтера в обычный режим... + +label.allocation.state=СоÑтоÑние раÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ +managed.state=СоÑтоÑние обÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ + +label.default.use=По умолчанию +label.host.tags=Метки узла + +label.cidr=CIDR +label.cidr.list=CIDR иÑточника + +label.storage.tags=Метки хранилища + +label.redundant.router=Резервной роутер +label.is.redundant.router=Резервной + +force.delete=Принудительно удалить +force.delete.domain.warning=Внимание\: При выборе Ñтого варианта приведет к удалению вÑех дочерних доменов и вÑе ÑвÑзанные Ñ Ð½Ð¸Ð¼Ð¸ аккаунтов и их реÑурÑов. + +force.remove=Принудительно удалить +force.remove.host.warning=Внимание\: При выборе Ñтой опции будет вызыван CloudStack Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ оÑтановики вÑех виртуальных машин, прежде чем Ñнимать Ñтот узел из клаÑтера.. + +force.stop=Принудительно оÑтановить +force.stop.instance.warning=Внимание\: ÐŸÑ€Ð¸Ð½ÑƒÐ´Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ð¾Ñтановка должна применÑтьÑÑ Ð² ÑамуюпоÑледнюю очередь. Ð’Ñ‹ можете потерÑть данные или получить неожиданное поведение/ÑоÑтоÑние виртуальной машины. + +label.PreSetup=ÐŸÑ€ÐµÐ´Ð²Ð°Ñ€Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ Ð½Ð°Ñтройка +label.SR.name = SR Name-Label +label.SharedMountPoint=ОткрытаÑТочкаДоÑтупа +label.clvm=CLVM +label.volgroup=Группа тома +label.VMFS.datastore=Хранилище VMFS + +label.network.device=Сетевое уÑтройÑтво +label.add.network.device=Добавить Ñетевое уÑтройÑтво +label.network.device.type=Тип Ñетевого уÑтройÑтва +label.DHCP.server.type=Тип Ñервера DHCP +label.Pxe.server.type=Тип Ñервера PXE +label.PING.storage.IP=IP Ð°Ð´Ñ€ÐµÑ PING-хранилища +label.PING.dir=Каталог PING +label.TFTP.dir=Каталог TFTP +label.PING.CIFS.username=Ð˜Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ PING CIFS +label.PING.CIFS.password=Пароль PING CIFS +label.CPU.cap=CPU Cap + + +label.action.enable.zone=Включить зону +label.action.enable.zone.processing=Включение зоны... +message.action.enable.zone=Потдтвердите, что вы дейÑтвительно хотите включить Ñту зону +label.action.disable.zone=Выключить зону +label.action.disable.zone.processing=Выключение зоны... +message.action.disable.zone=Подтвердите, что вы дейÑтвительно хотите выключить Ñту зону + +label.action.enable.pod=Включить Ñтенд +label.action.enable.pod.processing=Включение Ñтенда.. +message.action.enable.pod=Подтвердите, что вы дейÑтвительно хотите включить Ñтот Ñтенд. +label.action.disable.pod=Выключить Ñтенд +label.action.disable.pod.processing=Выключение Ñтенда. +message.action.disable.pod=Подтвердите, что вы дейÑтвительно хотите выключить Ñту зону. + +label.action.enable.cluster=Включить клаÑтер +label.action.enable.cluster.processing=Включение клаÑтера... +message.action.enable.cluster=Подтвердите, что вы дейÑтвительно хотите включить Ñтот клаÑтер. +label.action.disable.cluster=Выключить клаÑтер +label.action.disable.cluster.processing=Выключение клаÑтера... +message.action.disable.cluster=Подтвердите, что вы дейÑтвительно хотите выключить Ñтот клаÑтер. + +label.account.id=ID учётной запиÑи +label.account.name=Ð˜Ð¼Ñ ÑƒÑ‡Ñ‘Ñ‚Ð½Ð¾Ð¹ запиÑи +label.account.specific=Специфика аккауннта +label.account=Ð£Ñ‡Ñ‘Ñ‚Ð½Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑŒ +label.accounts=Учётные запиÑи +label.acquire.new.ip=Получить новый IP +label.show.ingress.rule=Показать входное правило +label.hide.ingress.rule=Скрыть входное правило +label.action.attach.disk.processing=Прикрепление диÑка... +label.action.attach.disk=Прикрепить диÑк +label.action.attach.iso.processing=Прикрепление ISO... +label.action.attach.iso=Прикрепить ISO +label.action.cancel.maintenance.mode.processing=Отмена режима обÑлуживаниÑ... +label.action.cancel.maintenance.mode=Отменить режим обÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ +label.action.change.password=Изменить пароль +label.action.change.service.processing=Изменение Ñлужбы... +label.action.change.service=Изменить Ñлужбу +label.action.copy.ISO.processing=Копирование ISO... +label.action.copy.ISO=Копировать ISO +label.action.copy.template.processing=Копирование шаблона... +label.action.copy.template=Копировать шаблон +label.action.create.template.processing=Создание шаблона... +label.action.create.template=Создать шаблон +label.action.create.vm.processing=Создание ВМ... +label.action.create.vm=Создать ВМ +label.action.create.volume.processing=Создание тома... +label.action.create.volume=Создать том +label.action.delete.IP.range.processing=Удаление диапазона IP... +label.action.delete.IP.range=Удалить диапазон IP +label.action.delete.ISO.processing=Удаление ISO... +label.action.delete.ISO=Удалить ISO +label.action.delete.account.processing=Удаление учётной запиÑи... +label.action.delete.account=Удалить учётную запиÑÑŒ +label.action.delete.cluster.processing=Удаление клаÑтера... +label.action.delete.cluster=Удалить клаÑтер +label.action.delete.disk.offering.processing=Удаление диÑкового реÑурÑа... +label.action.delete.disk.offering=Удалить диÑковый реÑÑƒÑ€Ñ + +label.action.update.resource.count=Обновить Ñчётчик реÑурÑов +label.action.update.resource.count.processing=Обновление Ñчетчика реÑурÑов... + +label.action.delete.domain=Удалить домен +label.action.delete.domain.processing=Удаление домена... + +label.action.delete.firewall.processing=Удаление фаервола... +label.action.delete.firewall=Удалить правило фаервола +label.action.delete.ingress.rule.processing=Удаление входного правила... +label.action.delete.ingress.rule=Удалить входное правило +label.action.delete.load.balancer.processing=Удаление баланÑировки нагрузки... +label.action.delete.load.balancer=Удалить правило баланÑировки нагрузки +label.action.edit.network.processing=Редактирование Ñети... +label.action.edit.network=Редактировать Ñеть +label.action.delete.network.processing=Удаление Ñети... +label.action.delete.network=Удалить Ñеть +label.action.delete.pod.processing=Удаление Ñтенда... +label.action.delete.pod=Удалить Ñтенд +label.action.delete.primary.storage.processing=Удаление оÑновного хранилища... +label.action.delete.primary.storage=Удалить оÑновное хранилище +label.action.delete.secondary.storage.processing=Удаление дополнительного хранилища... +label.action.delete.secondary.storage=Удалить дополнительное хранилище +label.action.delete.security.group.processing=Удаление группы безопаÑноÑти... +label.action.delete.security.group=Удалить группу безопаÑноÑти +label.action.delete.service.offering.processing=Удаление Ñлужебного реÑурÑа... +label.action.delete.service.offering=Удалить Ñлужебный реÑÑƒÑ€Ñ +label.action.delete.snapshot.processing=Удаление Ñнимка... +label.action.delete.snapshot=Удалить Ñнимок +label.action.delete.template.processing=Удаление шаблона... +label.action.delete.template=Удалить шаблон +label.action.delete.user.processing=Удаление пользователÑ... +label.action.delete.user=Удалить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.action.delete.volume.processing=Удаление тома... +label.action.delete.volume=Удалить том +label.action.delete.zone.processing=Удаление зоны... +label.action.delete.zone=Удалить зону +label.action.destroy.instance.processing=Уничтожение машины... +label.action.destroy.instance=Уничтожить машину +label.action.destroy.systemvm.processing=Уничтожение ÑиÑтемного ВМ... +label.action.destroy.systemvm=Уничтожить ÑиÑтемный ВМ +label.action.detach.disk.processing=Открепление диÑка... +label.action.detach.disk=Открепить диÑк +label.action.detach.iso.processing=Открепление ISO +label.action.detach.iso=Открепить ISO +label.action.disable.account.processing=Выключение учётной запиÑи +label.action.disable.account=Выключить учётную запиÑÑŒ +label.action.disable.static.NAT.processing=Выключение Ñтатичного NAT... +label.action.disable.static.NAT=Выключить Ñтатичный NAT +label.action.disable.user.processing=Выключение Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.action.disable.user=Выключить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.action.download.ISO=Загрузить ISO +label.action.download.template=Загрузить шаблон +label.action.download.volume.processing=Загрузка тома... +label.action.download.volume=Загрузить том +label.action.edit.ISO=Редактировать ISO +label.action.edit.account=Редактировать учётную запиÑÑŒ +label.action.edit.disk.offering=Редактировать диÑковый реÑÑƒÑ€Ñ +label.action.edit.domain=Редактировать домен +label.action.edit.global.setting=Редактировать глобальные наÑтройки +label.action.edit.instance=Редактировать машину +label.action.edit.network.offering=Редактировать Ñетевой реÑÑƒÑ€Ñ +label.action.edit.pod=Редактировать Ñтенд +label.action.edit.primary.storage=Редактировать оÑновное хранилище +label.action.edit.resource.limits=Редактировать пределы реÑурÑов +label.action.edit.service.offering=Редактировать Ñлужебный реÑÑƒÑ€Ñ +label.action.edit.template=Редактировать шаблон +label.action.edit.user=Редактировать Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.action.edit.zone=Редактировать зону +label.action.enable.account.processing=Включение аккаунта... +label.action.enable.account=Включить учётную запиÑÑŒ +label.action.enable.maintenance.mode.processing=Включение режима обÑлуживаниÑ... +label.action.enable.maintenance.mode=Включить режим обÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ +label.action.enable.static.NAT.processing=Включение Ñтатичного NAT.. +label.action.enable.static.NAT=Включить Ñтатичный NAT +label.action.enable.user.processing=Включение пользователÑ... +label.action.enable.user=Включить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.action.force.reconnect.processing=Переподключение... +label.action.force.reconnect=Принудительно переподключить +label.action.generate.keys.processing=Создание ключей... +label.action.generate.keys=Создать ключи +label.action.lock.account.processing=Ð‘Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ ÑƒÑ‡Ñ‘Ñ‚Ð½Ð¾Ð¹ запиÑи +label.action.lock.account=Заблокировать учётную запиÑÑŒ +label.action.migrate.instance=ПеренеÑти машину +label.action.migrate.instance.processing=ÐŸÐµÑ€ÐµÐ½Ð¾Ñ Ð¼Ð°ÑˆÐ¸Ð½Ñ‹...... +label.action.reboot.instance.processing=Перезагрузка машины... +label.action.reboot.instance=Перезагрузить машину +label.action.reboot.router.processing=Перезагрузка роутера... +label.action.reboot.router=Перезагрузить роутер +label.action.reboot.systemvm.processing=Перезагрузка ÑиÑтемной ВМ +label.action.reboot.systemvm=ПерезапуÑтить ÑиÑтемную ВМ +label.action.recurring.snapshot=ПовторÑемые Ñнимки +label.action.release.ip.processing=ОÑвобождение IP... +label.action.release.ip=ОÑвободить IP +label.action.remove.host.processing=Удаление узла... +label.action.remove.host=Удалить узел +label.action.reset.password.processing=Ð¡Ð±Ñ€Ð¾Ñ Ð¿Ð°Ñ€Ð¾Ð»Ñ... +label.action.reset.password=СброÑить пароль +label.action.resource.limits=Пределы реÑурÑов +label.action.restore.instance.processing=ВоÑÑтановление машины... +label.action.restore.instance=ВоÑÑтановить машину +label.action.start.instance.processing=ЗапуÑк машины... +label.action.start.instance=ЗапуÑтить машину +label.action.start.router.processing=ЗапуÑк роутера +label.action.start.router=ЗапуÑтить роутер +label.action.start.systemvm.processing=ЗапуÑк ÑиÑтемной ВМ... +label.action.start.systemvm=ЗапуÑтить ÑиÑтемную ВМ +label.action.stop.instance.processing=ОÑтановка машины... +label.action.stop.instance=ОÑтановить машину +label.action.stop.router.processing=ОÑтановка роутера... +label.action.stop.router=ОÑтановить роутер +label.action.stop.systemvm.processing=ОÑтановка ÑиÑтемной ВМ... +label.action.stop.systemvm=ОÑтановить ÑиÑтемной ВМ +label.action.take.snapshot.processing=Получение Ñнимка... +label.action.take.snapshot=Получить Ñнимок... +label.action.update.OS.preference.processing=Обновление параметров ОС... +label.action.update.OS.preference=Обновить параметры ОС +label.actions=ДейÑÑ‚Ð²Ð¸Ñ +label.active.sessions=Ðктивные ÑеÑÑии +label.add.account=Добавить аккаунт +label.add.by.cidr=Добавить к CIDR +label.add.by.group=Добавить к группе +label.add.cluster=Добавить клаÑтер +label.add.direct.iprange=Добавить диапазон прÑмых IP +label.add.disk.offering=Ðовый диÑковый реÑÑƒÑ€Ñ +label.add.domain=Добавить домен +label.add.firewall=Добавить правило фаервола. +label.add.host=Добавить узел +label.add.ingress.rule=Ðовое входное правило +label.add.ip.range=Добавить диапазон IP +label.add.load.balancer=Добавить баланÑировку нагрузки +label.add.more=Добавить что-то еще +label.add.network=Добавить Ñеть +label.add.pod=Добавить Ñтенд +label.add.primary.storage=Добавить оÑновное хранилище +label.add.secondary.storage=Добавить дополнительное хранилище +label.add.security.group=Добавить группу безопаÑноÑти +label.add.service.offering=Ðовый ÑиÑтемный реÑÑƒÑ€Ñ +label.add.template=Добавить шаблон +label.add.user=Добавить Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.add.vlan=Добавить VLAN +label.add.volume=Добавить том +label.add.zone=Добавить зону +label.add=Добавить +label.adding.cluster=Добавление клаÑтера +label.adding.failed=Ðе удалоÑÑŒ добавить +label.adding.pod=Добавление Ñтенда +label.adding.processing=Добавление... +label.adding.succeeded=Добавление завершено уÑпешно +label.adding.user=Добавление Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.adding.zone=Добавление зоны +label.adding=Добавление зоны +label.additional.networks=Дополнительные Ñети +label.admin.accounts=ÐдминиÑтраторÑкие учётные запиÑи +label.admin=ÐдминиÑтратор +label.advanced.mode=Продвинутый режим +label.advanced.search=РаÑширенный поиÑк +label.advanced=Продвинутый +label.alert=Тревога +label.algorithm=Ðлгоритм +label.allocated=РаÑпределено +label.api.key=Ключ API +label.assign.to.load.balancer=Включение машины в ÑиÑтему баланÑировки нагрузки +label.assign=ПриÑвоить +label.associated.network.id=СвÑзанный ID Ñети +label.attached.iso=Прикрепленный ISO +label.availability.zone=ДоÑтупноÑть зоны +label.availability=ДоÑтупноÑть +label.available.public.ips=ДоÑтупные публичные IP-адреÑа +label.available=ДоÑтупно +label.back=Ðазад +label.basic.mode=ПроÑто режим +label.bootable=Загружаемый +label.broadcast.domain.type=Тип широковещательного домена +label.by.account=По учётной запиÑи +label.by.availability=По доÑтупноÑти +label.by.domain=До домену +label.by.end.date=По завершению +label.by.level=По уровню +label.by.pod=По Ñтенду +label.by.role=По роли +label.by.start.date=По началу +label.by.state=По ÑоÑтоÑнию +label.by.traffic.type=По типу трафика +label.by.type.id=По типу ID +label.by.type=По типу +label.by.zone=По зоне +label.bytes.received=Байт получен +label.bytes.sent=Байт отправлено +label.cancel=Отмена +label.certificate=Сертификат +label.privatekey=ЧаÑтный ключ PKCS\#8 +label.domain.suffix=Ð¡ÑƒÑ„Ñ„Ð¸ÐºÑ Ð´Ð¾Ð¼ÐµÐ½Ð° DNS (нпр. xyz.com) +label.character=Символов +label.cidr.account=CIDR или ÑƒÑ‡Ñ‘Ñ‚Ð½Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑŒ/группа безопаÑноÑти +label.close=Закрыть +label.cloud.console=КонÑоль ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¾Ð±Ð»Ð°ÐºÐ¾Ð¼ +label.cloud.managed=Панель ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ +label.cluster.type=Тип клаÑтера +label.cluster=КлаÑтер +label.code=Код +label.confirmation=Подтверждение +label.cpu.allocated.for.VMs=РаÑпределено ЦПУ Ð´Ð»Ñ Ð’Ðœ +label.cpu.allocated=РаÑпределено ЦПУ +label.cpu.utilized=ИÑпользование CPU +label.cpu=CPU +label.created=Создано +label.cross.zones=Общие Ð´Ð»Ñ Ð·Ð¾Ð½ +label.custom.disk.size=Свой размер диÑка +label.daily=Ежедневно +label.data.disk.offering=Данные диÑка +label.date=Дата +label.day.of.month=День меÑÑца +label.day.of.week=День недели +label.delete=Удалить +label.deleting.failed=Ðе удалоÑÑŒ удалить +label.deleting.processing=Удаление... +label.description=ОпиÑание +label.detaching.disk=Открепление диÑка +label.details=Детали +label.device.id=ID уÑтройÑтва +label.disabled=Выключено +label.disabling.vpn.access=Выключение доÑтупа к VPN +label.disk.allocated=РаÑпределено диÑкового проÑтранÑтва +label.disk.offering=ДиÑковый реÑÑƒÑ€Ñ +label.disk.size.gb=Размер диÑка (в ГБ) +label.disk.size=Размер диÑка +label.disk.total=Ð’Ñего в диÑках +label.disk.volume=Том диÑка +label.display.text=Отображаемый текÑÑ‚ +label.dns.1=DNS 1 +label.dns.2=DNS 2 +label.domain.admin=ÐдминиÑтратор домена +label.domain.id=ID домена +label.domain.name=Ð˜Ð¼Ñ Ð´Ð¾Ð¼ÐµÐ½Ð° +label.domain=Домен +label.double.quotes.are.not.allowed=Двойные кавычки запрещены +label.download.progress=Ð¡Ñ‚Ð°Ñ‚ÑƒÑ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ +label.edit=Редактировать +label.email=E-mail +label.enabling.vpn.access=Включение доÑтупа к VPN +label.enabling.vpn=Включение VPN +label.end.port=Конечный порт +label.endpoint.or.operation=ÐšÐ¾Ð½ÐµÑ‡Ð½Ð°Ñ Ñ‚Ð¾Ñ‡ÐºÐ° или Ð¾Ð¿ÐµÑ€Ð°Ñ†Ð¸Ñ +label.error.code=Код ошибки +label.error=Ошибка +label.esx.host=Узел ESX/ESXi +label.example=Пример +label.failed=Ðеудачно +label.featured=ПредÑтавленный +label.firewall=Фаервол +label.first.name=Ð˜Ð¼Ñ +label.format=Формат +label.friday=ПÑтница +label.full=Полный +label.gateway=Шлюз +label.general.alerts=Общие тревоги +label.generating.url=Создание URL +label.go.step.2=Перейти к шагу 2 +label.go.step.3=Перейти к шагу 3 +label.go.step.4=Перейти к шагу 4 +label.go.step.5=Перейти к шагу 5 +label.group.optional=Группа (опционально) +label.group=Группа +label.guest.cidr=ГоÑтевой CIDR +label.guest.gateway=Шлюз +label.guest.ip.range=Диапазон IP-адреÑов +label.guest.ip=ГоÑтевые IP-адреÑа +label.guest.netmask=ГоÑÑ‚ÐµÐ²Ð°Ñ ÑÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð°Ñка +label.ha.enabled=HA включен +label.help=Помощь +label.host.alerts=Тревоги узла +label.host.name=Ð˜Ð¼Ñ ÑƒÐ·Ð»Ð° +label.host=Узел +label.hosts=Узлы +label.hourly=ЧаÑÐ¾Ð²Ð°Ñ +label.hypervisor.type=Тип гипервизора +label.hypervisor=Гипервизор +label.id=ID +label.info=Ð˜Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ +label.ingress.rule=Внутринее правило +label.initiated.by=Пользователь +label.instance.limits=Пределы машины +label.instance.name=Ð˜Ð¼Ñ Ð¼Ð°ÑˆÐ¸Ð½Ñ‹ +label.instance=Машина +label.instances=Машины +label.internal.dns.1=Внутренний DNS 1 +label.internal.dns.2=Внутренний DNS 2 +label.interval.type=Тип диапазона +label.invalid.integer=Ðеправильное целое чиÑло +label.invalid.number=Ðеправильное чиÑло +label.ip.address=IP-Ð°Ð´Ñ€ÐµÑ +label.ip.allocations=РаÑÐ¿Ñ€ÐµÐ´ÐµÐ»ÐµÐ½Ð¸Ñ IP +label.ip.limits=Пределы публичных IP +label.ip.or.fqdn=IP или FQDN +label.ip.range=Диапазон IP +label.ip=IP +label.ips=IP +label.is.default=По умолчанию +label.is.shared=общие +label.is.system=ЕÑть ÑиÑтема +label.iscsi=iSCSI +label.iso.boot=Загрузка ISO +label.iso=ISO +label.isolation.mode=Режим изолÑции +label.keep=Хранить +label.lang.chinese=КитайÑкий (упрощённый) +label.lang.english=ÐнглийÑкий +label.lang.japanese=ЯпонÑкий +label.lang.spanish=ИÑпанÑкий +label.last.disconnected=ПоÑледнее Ñоединение +label.last.name=ПоÑледнее Ð¸Ð¼Ñ +label.level=Уровень +label.linklocal.ip=Локальный IP Ð°Ð´Ñ€ÐµÑ +label.load.balancer=БаланÑировка нагрузки +label.loading=Загрузка +label.local=Локальный +# label.local.storage.enabled=Local storage enabled +label.login=Вход +label.logout=Выход +label.lun=LUN +label.manage=Управление +label.maximum=МакÑимум +label.memory.allocated=РаÑпределено памÑти +label.memory.total=Ð’Ñего памÑти +label.memory.used=ИÑпользованной памÑти +label.memory=ПамÑть +label.menu.accounts=Учётные запиÑи +label.menu.alerts=Тревоги +label.menu.all.accounts=Ð’Ñе учётные запиÑи +label.menu.all.instances=Ð’Ñе машины +label.menu.community.isos=ISO-ÑообщеÑтва +label.menu.community.templates=Шаблоны ÑообщеÑтва +label.menu.configuration=ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð°Ñ†Ð¸Ñ +label.menu.dashboard=Ð“Ð»Ð°Ð²Ð½Ð°Ñ +label.menu.destroyed.instances=Уничтоженные машины +label.menu.disk.offerings=ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð´Ð¸Ñков +label.menu.domains=Домены +label.menu.events=Ð¡Ð¾Ð±Ñ‹Ñ‚Ð¸Ñ +label.menu.featured.isos=Рекомендуемые ISO +label.menu.featured.templates=Рекомендуемые шаблоны +label.menu.global.settings=Глобальные наÑтройки +label.menu.instances=Машины +label.menu.ipaddresses=IP-адреÑа +label.menu.isos=ISO +label.menu.my.accounts=Мои учётные запиÑи +label.menu.my.instances=Мои машины +label.menu.my.isos=Мои ISO +label.menu.my.templates=Мои шаблоны +label.menu.network.offerings=ÐŸÑ€ÐµÐ´Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ñети +label.menu.network=Сеть +label.menu.physical.resources=ФизичеÑкие реÑурÑÑ‹ +label.menu.running.instances=Запущенные машины +label.menu.security.groups=Группы безопаÑноÑти +label.menu.service.offerings=УÑлуги +label.menu.snapshots=Снимки +label.menu.stopped.instances=ОÑтановленные машины +label.menu.storage=Хранилище +label.menu.system.vms=СиÑтемные ВМ +label.menu.system=СиÑтема +label.menu.templates=Шаблоны +label.menu.virtual.appliances=Виртуальные уÑтройÑтва +label.menu.virtual.resources=Виртуальные реÑурÑÑ‹ +label.menu.volumes=Тома +label.migrate.instance.to=ПеренеÑти машину в +label.minimum=Минимум +label.minute.past.hour=Минута +label.monday=Понедельник +label.monthly=Каждый меÑÑц +label.more.templates=Больше шаблонов +label.my.account=ÐœÐ¾Ñ ÑƒÑ‡Ñ‘Ñ‚Ð½Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑŒ +label.name.optional=Ð˜Ð¼Ñ (необÑзательно) +label.name=Ð˜Ð¼Ñ +label.netmask=Ð¡ÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð°Ñка +label.network.desc=ОпиÑание Ñети +label.network.domain=Домен Ñети +label.network.id=ID Ñети +label.network.name=Ð˜Ð¼Ñ Ñети +label.network.offering.display.text=Ñеть, обеÑпечивающую Отображение текÑта +label.network.offering.id=Ñеть, обеÑпечивающую ID +label.network.offering.name=Ñеть, обеÑпечивающую Ð˜Ð¼Ñ +label.network.offering=Сетевой реÑÑƒÑ€Ñ +label.network.rate=СкороÑть Ñети +label.network.read=Прочитано через Ñеть +label.network.type=Тип Ñети +label.network.write=ЗапиÑано через Ñеть +label.network=Сеть +label.new.password=Ðовый пароль +label.next=Следующий +label.nfs.server=Сервер NFS +label.nfs.storage=Хранилище NFS +label.nfs=NFS +label.nics=Сетевые уÑтройÑтва (NIC) +label.no.actions=Ðет доÑтупных операций +label.no.alerts=Тревог не получено +label.no.errors=Ошибок не получено +label.no.isos=Ðет доÑтупных ISO +label.no.items=Ðет доÑтупных Ñлементов +label.no.security.groups=Ðет доÑтупных групп безопаÑноÑть +label.no.thanks=Ðет, ÑпаÑибо +label.no=Ðет +label.none=Ðет +label.not.found=Ðе найдено +label.num.cpu.cores=Кол. CPU +label.numretries=КоличеÑтво попыток +label.offer.ha=ПредоÑÑ‚. HA +label.optional=ÐеобÑзательно +label.os.preference=ÐŸÑ€ÐµÐ´Ð¿Ð¾Ñ‡Ñ‚Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð°Ñ ÐžÐ¡ +label.os.type=Тип ОС +label.owned.public.ips=СобÑтвенные публичные IP-адреÑа +label.owner.account=Ð£Ñ‡Ñ‘Ñ‚Ð½Ð°Ñ Ð·Ð°Ð¿Ð¸ÑÑŒ владельца +label.owner.domain=Домен владельца +label.parent.domain=РодительÑкий домен +label.password.enabled=Пароль включен +label.password=Пароль +label.path=Путь +label.please.wait=Подождите +label.pod=Стенд +label.port.forwarding=ÐŸÑ€Ð¾Ð±Ñ€Ð¾Ñ Ð¿Ð¾Ñ€Ñ‚Ð¾Ð² +label.port.range=Диапазон портов +label.prev=Предыдуший +label.primary.allocated=РаÑпределение оÑновного хранилища +label.primary.network=ОÑÐ½Ð¾Ð²Ð½Ð°Ñ Ñеть +label.primary.storage=ОÑновное хранилище +label.primary.used=ИÑпользование оÑновного хранилища +label.private.interface=ЧаÑтный Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ +label.private.ip.range=Диапазон чаÑтных IP +label.private.ip=ЧаÑтный IP-Ð°Ð´Ñ€ÐµÑ +label.private.ips=ЧаÑтные IP-адреÑа +label.private.port=ЧаÑтный порт +label.private.zone=ЧаÑÑ‚Ð½Ð°Ñ Ð·Ð¾Ð½Ð° +label.protocol=Протокол +label.public.interface=Публичный Ð¸Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ +label.public.ip=Публичный IP-Ð°Ð´Ñ€ÐµÑ +label.public.ips=Публичные IP-адреÑа +label.public.port=Публичный порт +label.public.zone=ÐŸÑƒÐ±Ð»Ð¸Ñ‡Ð½Ð°Ñ Ð·Ð¾Ð½Ð° +label.public=Публичный +label.recent.errors=Полученные ошибки +label.refresh=Обновить +label.related=СвÑзанный +label.remove.from.load.balancer=Удалить машину Ñ Ð±Ð°Ð»Ð°Ð½Ñировки нагрузки +label.removing.user=Удаление Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.required=ТребуетÑÑ +label.reserved.system.ip=Зарезервированный ÑиÑтемный IP +label.resource.limits=Пределы реÑурÑов +label.resource=РеÑÑƒÑ€Ñ +label.resources=РеÑурÑÑ‹ +label.role=Роль +label.root.disk.offering=РеÑÑƒÑ€Ñ ÐºÐ¾Ñ€Ð½ÐµÐ²Ð¾Ð³Ð¾ диÑка +label.running.vms=Запущенные ВМ +label.saturday=Суббота +label.save=Сохранить +label.saving.processing=Сохранение... +label.scope=Сфера +label.search=ПоиÑк +label.secondary.storage=Дополнительное хранилище +label.secondary.used=ИÑпользование дополнительного хранилища +label.secret.key=Секретный ключ +label.security.group.name=Ð˜Ð¼Ñ Ð³Ñ€ÑƒÐ¿Ð¿Ñ‹ безопаÑноÑти +label.security.group=Группа безопаÑноÑти +label.security.groups.enabled=Группы безопаÑноÑти включены +label.security.groups=Группы безопаÑноÑти +label.sent=Отправлено +label.server=Сервер +label.service.offering=Служебный реÑÑƒÑ€Ñ +label.system.service.offering=СиÑтемный реÑÑƒÑ€Ñ +label.session.expired=Ð’Ñ€ÐµÐ¼Ñ ÑеÑÑии вышло +label.shared=ОбщедоÑтупный +label.size=Размер +label.snapshot.limits=Пределы Ñнимков +label.snapshot.name=Ð˜Ð¼Ñ Ñнимка +label.snapshot.s=Снимок/Ñнимки +label.snapshot.schedule=ÐаÑтройка повторÑемых Ñнимков +label.snapshot=Снимок +label.snapshots=Снимки +label.source.nat=NAT-иÑточник +label.specify.vlan=Укажите VLAN +label.start.port=Ðачальный порт +label.state=СоÑтоÑние +label.static.nat.to=Статичный NAT к +label.static.nat=Статичный NAT +label.statistics=СтатиÑтика +label.status=Ð¡Ñ‚Ð°Ñ‚ÑƒÑ +label.step.1.title=Шаг 1\: Выберите шаблон +label.step.1=Шаг 1 +label.step.2.title=Шаг 2\: СиÑтемный реÑÑƒÑ€Ñ +label.step.2=Шаг 2 +label.step.3.title=Шаг 3\: Выберите диÑковый реÑÑƒÑ€Ñ +label.step.3=Шаг 3 +label.step.4.title=Step 4\: Сеть +label.step.4=Шаг 4 +label.step.5.title=Step 5\: Обзор +label.step.5=Шаг 5 +label.stopped.vms=ОÑтановленные ВМ +label.storage.type=Тип хранилища +label.storage=Хранилище +label.submit=Опубликовать +label.submitted.by=[Опубликовано\: ] +label.succeeded=УÑпешно +label.sunday=ВоÑкреÑенье +label.system.capacity=МощноÑть ÑиÑтемы +label.system.vm.type=Тип ÑиÑтемной ВМ +label.system.vm=СиÑÑ‚ÐµÐ¼Ð½Ð°Ñ Ð’Ðœ +label.system.vms=СиÑтемные ВМ +label.tagged=С меткой +label.tags=Метки +label.target.iqn=Целевой IQN +label.template.limits=Пределы шаблона +label.template=Шаблон +label.theme.default=Ð¡Ñ‚Ð°Ð½Ð´Ð°Ñ€Ñ‚Ð½Ð°Ñ Ñ‚ÐµÐ¼Ð° +label.theme.grey=Ð¡ÐµÑ€Ð°Ñ Ñ‚ÐµÐ¼Ð° +label.theme.lightblue=Ð“Ð¾Ð»ÑƒÐ±Ð°Ñ Ñ‚ÐµÐ¼Ð° +label.thursday=Четверг +label.time.zone=ЧаÑовой поÑÑ +label.time=Ð’Ñ€ÐµÐ¼Ñ +label.timeout.in.second = Ð’Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ðµ (Ñек.) +label.timezone=ЧаÑовой поÑÑ +label.total.cpu=Ð’Ñего CPU +label.total.vms=Ð’Ñего ВМ +label.traffic.type=Тип трафика +label.tuesday=Вторник +label.type.id=ID типа +label.type=Тип +label.unavailable=Ðе доÑтупно +label.unlimited=БеÑконечно +label.untagged=Без метки +label.update.ssl.cert=Обновить Ñертификаты SSL +label.update.ssl=Обновить Ñертификаты SSL +label.updating=Обновление +label.url=URL +label.usage.interface=Ð˜Ð½Ñ‚ÐµÑ€Ñ„ÐµÐ¹Ñ Ð¸ÑÐ¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ð½Ð¸Ñ +label.used=ИÑпользовано +label.user=Пользователь +label.username=Ð˜Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ +label.users=Пользователи +label.value=Значение +label.vcenter.cluster=КлаÑтер vCenter +label.vcenter.datacenter=ЦОД vCenter +label.vcenter.datastore=Хранилище vCenter +label.vcenter.host=Узел vCenter +label.vcenter.password=Пароль vCenter +label.vcenter.username=Ð˜Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ vCenter +label.version=ВерÑÐ¸Ñ +label.virtual.appliance=Виртуальное уÑтройÑтво +label.virtual.appliances=Виртуальное уÑтройÑтва +label.virtual.network=Ð’Ð¸Ñ€Ñ‚ÑƒÐ°Ð»ÑŒÐ½Ð°Ñ Ñеть +label.vlan.id=ID VLAN +label.vlan.range=Диапазон VLAN +label.vm.add=Добавить машины +label.vm.destroy=Уничтожить +label.vm.reboot=Перезагрузить +label.vm.start=ЗапуÑтить +label.vm.stop=ОÑтановить +label.vmfs=VMFS +label.vms=ВМ +label.volume.limits=Пределы томов +label.volume.name=Ð˜Ð¼Ñ Ñ‚Ð¾Ð¼Ð° +label.volume=Том +label.volumes=Томы +label.vsphere.managed=ОбÑлуживание vSphere +label.waiting=Ожидание +label.warn=Внимание +label.wednesday=Среда +label.weekly=Еженедельно +label.welcome.cloud.console=Добро пожаловать на панель ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ +label.welcome=Добро пожаловать +label.yes=Да +label.zone.id=ID зоны +label.zone.step.1.title=Шаг 1\: Выберите Ñеть +label.zone.step.2.title=Step 2\: Добавьте зону +label.zone.step.3.title=Step 3\: Добавьте Ñтенд +label.zone.step.4.title=Step 4\: Добавьте диапазон IP-адреÑов +label.zone.wide=Ð’Ñей зоны +label.zone=Зона + +#Messages +message.acquire.public.ip=ПожалуйÑта, выберите зону, из которой вы хотите приобреÑти новый IP. +message.action.cancel.maintenance.mode=Подтвердите, что вы дейÑтвительно хотите отменить режим обÑлуживаниÑ. +message.action.cancel.maintenance=Узел уÑпешно вышел из режима обÑлуживаниÑ. Этль процеÑÑ Ð¼Ð¾Ð¶ÐµÑ‚ длитьÑÑ Ð½ÐµÑколько минут. +message.action.delete.ISO.for.all.zones=Это ISO, иÑпользуемый вÑеми зонами. Подтвердите, что вы дейÑтвительно хотите удалить его Ñо вÑех зон. +message.action.delete.ISO=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот ISO. +message.action.delete.cluster=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот клаÑтер. +message.action.delete.disk.offering=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот диÑковый реÑурÑ. +message.action.delete.domain=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот домен. +message.action.delete.external.firewall=Подтвердите, что вы дейÑтвительно хотите удалить внешний фаервол. Внимание\: еÑли вы планируете вернутьÑÑ Ðº Ñтому внешнему фаерволу обратно, вам придетÑÑ ÑброÑить информацию об иÑпользовании в уÑтройÑтве. +message.action.delete.external.load.balancer=Подтвердите, что вы дейÑтвительно хотите удалить внешнюю баланÑировку нагрузки. Внимание\: еÑли вы планируете вернутьÑÑ Ðº Ñтой внешней баланÑировке, вам придетÑÑ ÑброÑить информацию об иÑпользовании в уÑтройÑтве. +message.action.delete.ingress.rule=Подтвердите, что вы дейÑтвительно хотите удалить Ñто входное правило. +message.action.delete.network=Подтвердите, что вы дейÑтвительно хотите удалить Ñту Ñеть. +message.action.delete.pod=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот Ñтенд. +message.action.delete.primary.storage=Подтвердите, что вы дейÑтвительно хотите удалить Ñто оÑновное хранилище. +message.action.delete.secondary.storage=Подтвердите, что вы дейÑтвительно хотите удалить Ñто дополнительное хранилище. +message.action.delete.security.group=Подтвердите, что вы дейÑтвительно хотите удалить Ñту группу безопаÑноÑти. +message.action.delete.service.offering=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот Ñлужебный реÑурÑ. +message.action.delete.snapshot=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот Ñнимок. +message.action.delete.template.for.all.zones=Шаблон иÑпользуетÑÑ Ð²Ð¾ вÑех зонах. Подтвердите, что вы хотите удалить его Ñо вÑех зон. +message.action.delete.template=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот шаблон. +message.action.delete.volume=Подтвердите, что вы дейÑтвительно хотите удалить Ñтот том. +message.action.delete.zone=Подтвердите, что вы дейÑтвительно хотите удалить Ñту зону. +message.action.destroy.instance=Подтвердите, что вы дейÑтвительно хотите уничтожить Ñту машину. +message.action.destroy.systemvm=Подтвердите, что вы дейÑтвительно хотите удалить Ñто оÑновное хранилище. +message.action.disable.static.NAT=Подтвердите, что вы дейÑтвительно хотите отключить Ñтатичный NAT. +message.action.enable.maintenance=Узел уÑпешно вошел в режим обÑлуживаниÑ. ДлительноÑть Ñтого процеÑÑа завиÑит от количеÑтва запущенных ВМ в Ñтом узле и обычно равна неÑкольким минутам. +message.action.force.reconnect=Узел уÑпешно переподключилÑÑ. Этот процеÑÑ Ð¼Ð¾Ð¶ÐµÑ‚ длитьÑÑ Ð½ÐµÑколько минут. +message.action.host.enable.maintenance.mode=Включение режима обÑÐ»ÑƒÐ¶Ð¸Ð²Ð°Ð½Ð¸Ñ Ð½Ð° узле приведет к переноÑу запущенных виртуальных машин на другие доÑтупные узлы. +message.action.instance.reset.password=Подтвердите, что вы дейÑтвительно хотите изменить пароль root Ñтой ВМ. +message.action.primarystorage.enable.maintenance.mode=Внимание\: при переходе оÑновного хранилища в режим обÑлуживаниÑ, вÑе ВМ будут оÑтановлены. Хотите продолжить? +message.action.reboot.instance=Подтвердите, что вы дейÑтвительно хотите перезагрузить Ñту машину. +message.action.reboot.systemvm=Подтвердите, что вы дейÑтвительно хотите перезагрузить Ñтот ÑиÑтемный ВМ. +message.action.release.ip=Подтвердите, что вы дейÑтвительно хотите оÑвободить Ñтот IP-адреÑ. +message.action.remove.host=Удаление поÑледнего/единÑтвенного Ñервера в клаÑтере и Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€Ð½Ð°Ñ ÐµÐ³Ð¾ уÑтановка приведет уничтожению рабочего окружениÑ/базы данных на Ñервере и Ñделае гоÑтевые машины непригодными к иÑпользованию. +message.action.restore.instance=Подтвердите, что вы дейÑтвительно хотите воÑÑтановить Ñту машину. +message.action.start.instance=Подтвердите, что вы дейÑтвительно хотите запуÑтить Ñту машину. +message.action.start.router=Подтвердите, что вы дейÑтвительно хотите запуÑтить Ñтот роутер. +message.action.start.systemvm=Подтвердите, что вы дейÑтвительно хотите запуÑтить Ñту ÑиÑтемную ВМ. +message.action.stop.instance=Подтвердите, что вы дейÑтвительно хотите оÑтановить Ñту машину. +message.action.stop.systemvm=Подтвердите, что вы дейÑтвительно хотите оÑтановить Ñту ÑиÑтемную ВМ. +message.action.take.snapshot=Подтвердите, что вы дейÑтвительно хотите получить Ñнимок Ñтого тома. +message.add.cluster.zone=Добавить гипервизора ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐºÐ»Ð°Ñтером Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹ +message.add.cluster=Добавить гипервизор ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ ÐºÐ»Ð°Ñтером Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹ , модуль +message.add.disk.offering=ПожалуйÑта, укажите Ñледующие параметры, чтобы добавить новое предложение диÑка +message.add.firewall=Добавить фаервол в зону +message.add.host=Укажите Ñледующие параметры Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ узла. +message.add.ip.range.direct.network=Добавить IP-диапазона Ñети в зоне +message.add.ip.range.to.pod=

Добавить диапазон IP-адреÑов в Ñтенд\:

+message.add.ip.range=Добавить диапазон IP-адреÑов в публичную Ñеть зоны +message.add.load.balancer=Добавить баланÑировку нагрузки в зону +message.add.network=Добавить новую Ñеть Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹\: +message.add.pod=Добавить новый Ñтенд Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹ +message.add.primary.storage=Добавить оÑновное хранилище Ð´Ð»Ñ Ð·Ð¾Ð½Ñ‹ , Ñтенда +message.add.primary=Укажите Ñледующие параметры Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ оÑновного хранилища +message.add.secondary.storage=Добавить хранилище в зону +message.add.service.offering=Укажите Ñледующие параметры Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ ÑиÑтемного реÑурÑа. +message.add.template=Укажите Ñледующие параметры Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ шаблона +message.add.volume=Укажите Ñледующие параметры Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ тома +message.additional.networks.desc=ПожалуйÑта, выберите дополнительные Ñети, куда вашы Ñервера будут подключены. +message.advanced.mode.desc=Выберите Ñту модель Ñети, еÑли вы хотите включить поддержку VLAN. Эта ÑÐµÑ‚ÐµÐ²Ð°Ñ Ð¼Ð¾Ð´ÐµÐ»ÑŒ обеÑпечивает макÑимальную гибкоÑть в предоÑтавлении админиÑтраторам Ð´Ð»Ñ Ð¿Ñ€ÐµÐ´Ð¾ÑÑ‚Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»ÑŒÑких предложений Ñети, такие как межÑетевой Ñкран, VPN, или поддержка баланÑировки нагрузки, а также позволÑет прÑмое против виртуальных Ñетей. +message.advanced.security.group=Выберите Ñтот параметр, еÑли вы хотите иÑпользовать группы безопаÑноÑти, обеÑпечить изолÑцию Ñервера. +message.advanced.virtual=Выберите Ñтот параметр, еÑли вы хотите иÑпользовать вÑей зоны Ñети VLAN, чтобы обеÑпечить изолÑцию Ñервера. +message.allow.vpn.access=ПожалуйÑта, введите Ð¸Ð¼Ñ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð¸ пароль пользователÑ, который вы хотите добавить Ð´Ð»Ñ VPN-доÑтупа. +message.attach.iso.confirm=ПожалуйÑта, подтвердите, что вы хотите прикрепить ISO в Ñтот Ñервер. +message.attach.volume=ПожалуйÑта, укажите Ñледующие данные, что бы увеличить меÑто. Ð”Ð»Ñ Windows, нужно перезагружать Ñервер +message.basic.mode.desc=Выберите Ñту модель Ñети, еÑли вы *not* хотите, чтобы была Ð»ÑŽÐ±Ð°Ñ Ð¿Ð¾Ð´Ð´ÐµÑ€Ð¶ÐºÐ° VLAN. Ð’Ñем виртуальным машинам, Ñозданные по Ñтой модели Ñети будет назначен IP напрÑмую из Ñети и группы безопаÑноÑти, которые иÑпользуютÑÑ Ð´Ð»Ñ Ð¾Ð±ÐµÑÐ¿ÐµÑ‡ÐµÐ½Ð¸Ñ Ð±ÐµÐ·Ð¾Ð¿Ð°ÑноÑти и Ñегрегации. +message.change.offering.confirm=ПожалуйÑта, подтвердите, что вы хотите изменить Ñлужбу Ñ€Ð°Ð·Ð¼ÐµÑ‰ÐµÐ½Ð¸Ñ Ñтого VM. +message.copy.iso.confirm=ПожалуйÑта, подтвердите, что вы хотите Ñкопировать ISO до +message.copy.template=Копировать шаблон XXX из зоны в +message.create.template.vm=Создать шаблон виртуальной машины +message.create.template.volume=ПожалуйÑта, укажите Ñледующую информацию, прежде чем Ñоздавать шаблон диÑка объемом\: . Создание шаблона может варьироватьÑÑ Ð¾Ñ‚ неÑкольких минут до дольше в завиÑимоÑти от размера тома. +message.delete.account=ПожалуйÑта, подтвердите, что вы хотите удалить Ñтот аккаунт. +message.detach.iso.confirm=ПожалуйÑта, подтвердите, что вы хотите отделить ISO от Ñтого виртуального Ñервера. +message.disable.account=ПожалуйÑта, подтвердите, что вы хотите отключить Ñту учетную запиÑÑŒ. При отключении аккаунта, вÑе пользователи Ð´Ð»Ñ Ñтой учетной запиÑи не будут иметь доÑтуп к Ñвоим реÑурÑам облака. Ð’Ñе виртуальные машины будут немедленно закрыты. +message.disable.vpn.access=ПожалуйÑта, подтвердите, что вы хотите отключить VPN доÑтуп +message.download.ISO=ПожалуйÑта, нажмите 00000 Ñкачать образ +message.download.template=Ðажмите 00000Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ +message.download.volume=Ðажмите 00000 Ð´Ð»Ñ Ð·Ð°Ð³Ñ€ÑƒÐ·ÐºÐ¸ тома +message.edit.confirm=ПожалуйÑта, подтвердите, прежде чем нажать "Сохранить". +message.edit.limits=Укажите пределы Ð´Ð»Ñ Ñ€ÐµÑурÑов. Значение "-1" означает отÑутÑтвие предела Ð¿Ð¾Ñ‚Ñ€ÐµÐ±Ð»ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ð¾Ð³Ð¾ реÑурÑа. +message.enable.account=Подтвердите, что вы дейÑтвительно хотите включить Ñту учётную запиÑÑŒ. +message.enable.vpn.access=Ð¡ÐµÐ¹Ñ‡Ð°Ñ VPN Ð´Ð»Ñ Ñтого IP-aдреÑа выключен. Желаете включить VPN-доÑтуп? +message.enabled.vpn.ip.sec=Ваш IPSec pre-shared ключ +message.enabled.vpn=Ваш VPN доÑтуп в наÑтоÑщее Ð²Ñ€ÐµÐ¼Ñ Ð²ÐºÐ»ÑŽÑ‡ÐµÐ½ и могут быть доÑтупны через IP +message.launch.vm.on.private.network=Хотите запуÑтить ВМ в вашей чаÑтной выделенной Ñети? +message.lock.account=Подтвердите, что вы дейÑтвительно хотите заблокировать Ñту учётную запиÑÑŒ. Ð’Ñе пользователи в таких учётных запиÑÑÑ… потерÑÑŽÑ‚ возможноÑть управлÑть Ñвоими облачными реÑурÑами. Эти реÑурÑÑ‹ оÑтанутÑÑ Ð´Ð¾Ñтупны Ð´Ð»Ñ Ð´Ñ€ÑƒÐ³Ð¸Ñ… учётных запиÑей. +message.migrate.instance.confirm=Подтвердите, что вы дейÑтвительно хотите перенеÑти виртуальную машину. +message.new.user=Введите информацию Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ Ð¿Ð¾Ð»ÑŒÐ·Ð¾Ð²Ð°Ñ‚ÐµÐ»Ñ Ð² учётную запиÑÑŒ. +message.no.network.support.configuration.not.true=Ðи в одной зоне нет групп безопаÑноÑти. ПоÑтому дополнительные Ñетевые возможноÑти недоÑтупны. Перейдите к шагу 5. +message.no.network.support=Выбранный гипервизор (vSphere) не обладает дополнительными Ñетевыми возмодноÑÑ‚Ñми. Перейдите к шагу 5. +message.number.clusters=

\# of КлаÑтеры

+message.number.hosts=

\# of Узлы

+message.number.pods=

\# of Стенды

+message.number.storage=

\# of Тома оÑновного хранилища

+message.number.zones=

\# of Зоны

+message.remove.vpn.access=Подтвердите, что вы дейÑтвительно хотите удалить доÑтуп к VPN Ð´Ð»Ñ Ñтого пользователÑ. +message.restart.mgmt.server=ПожалуйÑта, перезагрузите Ñервер(Ñ‹) ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð´Ð»Ñ Ð¿Ñ€Ð¸Ð½ÑÑ‚Ð¸Ñ Ð½Ð¾Ð²Ñ‹Ñ… наÑтроек. +message.restart.mgmt.usage.server=ПожалуйÑта, перезагрузите Ñервер Ð´Ð»Ñ Ð²ÑÑ‚ÑƒÐ¿Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ñ‹Ñ… параметров в Ñилу. +message.security.group.usage=(иÑпользуйте Ctrl-клик, чтобы выбрать вÑе ÑоответÑтвующие группы безопаÑноÑти) +message.snapshot.schedule=Ð’Ñ‹ можете наÑтроить повторÑющиеÑÑ Ñнимоки, Ð²Ñ‹Ð±Ð¸Ñ€Ð°Ñ Ð¸Ð· доÑтупных вариантов ниже и применив политику Ð¿Ñ€ÐµÐ´Ð¿Ð¾Ñ‡Ñ‚ÐµÐ½Ð¸Ñ +message.step.1.continue=Выберите шаблон или ISO Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ñ. +message.step.1.desc=ПожалуйÑта, выберите шаблон Ð´Ð»Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ Ñервера. Ð’Ñ‹ можете также выбрать пуÑтой шаблон, из которого образ ISO может быть уÑтановлен на. +message.step.2.continue=Выберите Ñлужебный реÑÑƒÑ€Ñ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ñ. +message.step.2.desc= +message.step.3.continue=Выберите диÑковый реÑÑƒÑ€Ñ Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ñ. +message.step.3.desc= +message.step.4.continue=Выберите Ñ…Ð¾Ñ‚Ñ Ð±Ñ‹ одну Ñеть Ð´Ð»Ñ Ð¿Ñ€Ð¾Ð´Ð¾Ð»Ð¶ÐµÐ½Ð¸Ñ. +message.step.4.desc=Выберите оÑновную Ñеть, к которой будет подключена машина. +message.update.os.preference=ПожалуйÑта, выберите ОС Ð´Ð»Ñ Ñтого хоÑта. Ð’Ñе виртуальные ÑкземплÑры Ñ Ð°Ð½Ð°Ð»Ð¾Ð³Ð¸Ñ‡Ð½Ñ‹Ð¼Ð¸ предпочтениÑми впервые будет выделено на Ñтот узел, прежде чем выбрать другую. +message.update.ssl=ПожалуйÑта, отправьте новый ÑовмеÑтимый X.509 SSL Ñертификат Ð´Ð»Ñ Ð¾Ð±Ð½Ð¾Ð²Ð»ÐµÐ½Ð¸Ñ Ð´Ð»Ñ ÐºÐ°Ð¶Ð´Ð¾Ð¹ конÑоли виртуальных прокÑи, например\: +message.virtual.network.desc=выделенной виртуальной Ñети Ð´Ð»Ñ Ð²Ð°ÑˆÐµÐ¹ учетной запиÑи. Широковещательный домен находитÑÑ Ð²Ð½ÑƒÑ‚Ñ€Ð¸ VLAN и веÑÑŒ внешний доÑтуп к Ñети направлÑетÑÑ Ð¿ÑƒÑ‚ÐµÐ¼ виртуального маршрутизатора. +message.volume.create.template.confirm=Подтвердите, что вы дейÑтвительно хотите Ñоздать шаблон Ñтого тома. Это процеÑÑ Ð¼Ð¾Ð¶ÐµÑ‚ продлитьÑÑ Ð½ÐµÑколько минут в завиÑимоÑти от размера тома. +message.zone.step.1.desc=Выберите тип Ñети Ñтой зоны. +message.zone.step.2.desc=Введите необходимую информацию Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð¹ зоны +message.zone.step.3.desc=Введите необходимую информацию Ð´Ð»Ñ Ð´Ð¾Ð±Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½Ð¾Ð²Ð¾Ð³Ð¾ Ñтенда +message.apply.snapshot.policy=Политики Ñтого Ñнимка были уÑпешно обновлены. +message.disable.snapshot.policy=Политики Ñтого Ñнимка были уÑпешно отключены. +message.action.change.service.warning.for.instance=Ð”Ð»Ñ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ñ‚ÐµÐºÑƒÑ‰ÐµÐ³Ð¾ Ñлужебного реÑурÑа ваша машина должна быть оÑтановлена. +message.action.change.service.warning.for.router=\n +message.action.reset.password.warning=Машина должна быть оÑтановлена Ð´Ð»Ñ Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ Ð¿Ð°Ñ€Ð¾Ð»Ñ +message.action.reset.password.off=Ðа данный момент машина не поддерживает данную функцию + +#Errors +error.login=Ваше имÑ/пароль не Ñовпадает Ñ Ð²Ð°ÑˆÐ¸Ð¼Ð¸ запиÑÑми. +error.menu.select=Ðе удаетÑÑ Ð²Ñ‹Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÑŒ дейÑтвие из-за отÑутÑÑ‚Ð²Ð¸Ñ Ð²Ñ‹Ð±Ñ€Ð°Ð½Ñ‹Ñ… пунктов. +error.mgmt.server.inaccessible=Сервер ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð½ÐµÐ´Ð¾Ñтупна. Попробуйте обратитьÑÑ Ðº нему позже. +error.session.expired=Ваша ÑеÑÑÐ¸Ñ Ð±Ñ‹Ð»Ð° завершена +error.unresolved.internet.name=Ваше интернет-Ð¸Ð¼Ñ Ð¾Ð¿Ñ€ÐµÐ´ÐµÐ»Ð¸Ñ‚ÑŒ не удалоÑÑŒ 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/pom.xml b/client/pom.xml index e4707c00180..74cebf050e2 100644 --- a/client/pom.xml +++ b/client/pom.xml @@ -1,22 +1,15 @@ - - + + 4.0.0 cloud-client-ui Apache CloudStack Client UI @@ -32,6 +25,11 @@ cloud-server ${project.version} + + org.apache.cloudstack + cloud-plugin-acl-static-role-based + ${project.version} + org.apache.cloudstack cloud-plugin-user-authenticator-ldap @@ -47,6 +45,11 @@ cloud-plugin-user-authenticator-plaintext ${project.version} + + org.apache.cloudstack + cloud-plugin-user-authenticator-sha256salted + ${project.version} + org.apache.cloudstack cloud-plugin-network-nvp @@ -76,6 +79,12 @@ org.apache.cloudstack cloud-plugin-hypervisor-kvm ${project.version} + + + org.mortbay.jetty + servlet-api + + org.apache.cloudstack @@ -100,7 +109,7 @@ mysql mysql-connector-java - 5.1.21 + ${cs.mysql.version} runtime @@ -182,7 +191,7 @@ org.apache.maven.plugins maven-war-plugin - 2.2 + 2.3 ./WEB-INF/web.xml ./target/generated-webapp @@ -201,16 +210,17 @@ -XX:MaxPermSize=512m -Xmx2g /client - ${basedir}/target/${project.artifactId}-${project.version}/WEB-INF/web.xml - ${basedir}/target/${project.artifactId}-${project.version} + ${basedir}/WEB-INF/web.xml + ${project.build.directory}/${project.build.finalName} org.apache.tomcat.maven tomcat7-maven-plugin + /client ${basedir}/WEB-INF/web.xml - ./target/generated-webapp + ${project.build.directory}/generated-webapp/ @@ -218,23 +228,47 @@ 1.7 + generate-resource generate-resources run - + - + + + + + + + + + + + + + + + + + + @@ -246,15 +280,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + process-nonoss + process-resources + + run + + + + test + + + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + + + copy + package + + copy + + + + + org.jasypt + jasypt + 1.9.0` + false + ${project.build.directory}/pythonlibs + + + org.jasypt + jasypt + 1.8` + false + ${project.build.directory}/pythonlibs + + + + - + org.eclipse.m2e lifecycle-mapping @@ -288,6 +404,21 @@
+ simulator + + + simulator + + + + + org.apache.cloudstack + cloud-plugin-hypervisor-simulator + ${project.version} + + + + netapp diff --git a/client/tomcatconf/cisconexusvsm_commands.properties.in b/client/tomcatconf/cisconexusvsm_commands.properties.in index f6db0d9a9f0..0427ba2d212 100644 --- a/client/tomcatconf/cisconexusvsm_commands.properties.in +++ b/client/tomcatconf/cisconexusvsm_commands.properties.in @@ -19,7 +19,7 @@ ### Please standardize naming conventions to camel-case (even for acronyms). #### Cisco Nexus 1000v Virtual Supervisor Module (VSM) commands -deleteCiscoNexusVSM = com.cloud.api.commands.DeleteCiscoNexusVSMCmd;1 -enableCiscoNexusVSM = com.cloud.api.commands.EnableCiscoNexusVSMCmd;1 -disableCiscoNexusVSM = com.cloud.api.commands.DisableCiscoNexusVSMCmd;1 -listCiscoNexusVSMs = com.cloud.api.commands.ListCiscoNexusVSMsCmd;1 +deleteCiscoNexusVSM=1 +enableCiscoNexusVSM=1 +disableCiscoNexusVSM=1 +listCiscoNexusVSMs=1 diff --git a/client/tomcatconf/commands-ext.properties.in b/client/tomcatconf/commands-ext.properties.in index f172067ede9..cd1d0eac066 100644 --- a/client/tomcatconf/commands-ext.properties.in +++ b/client/tomcatconf/commands-ext.properties.in @@ -20,13 +20,6 @@ generateUsageRecords=com.cloud.api.commands.GenerateUsageRecordsCmd;1 listUsageRecords=com.cloud.api.commands.GetUsageRecordsCmd;1 listUsageTypes=com.cloud.api.commands.ListUsageTypesCmd;1 - - -### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 - #### traffic monitor commands addTrafficMonitor=com.cloud.api.commands.AddTrafficMonitorCmd;1 deleteTrafficMonitor=com.cloud.api.commands.DeleteTrafficMonitorCmd;1 diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in old mode 100755 new mode 100644 index e2336946e27..3872f2a8783 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -19,385 +19,408 @@ ### Please standardize naming conventions to camel-case (even for acronyms). ### Account commands -createAccount=com.cloud.api.commands.CreateAccountCmd;3 -deleteAccount=com.cloud.api.commands.DeleteAccountCmd;3 -updateAccount=com.cloud.api.commands.UpdateAccountCmd;3 -disableAccount=com.cloud.api.commands.DisableAccountCmd;7 -enableAccount=com.cloud.api.commands.EnableAccountCmd;7 -###lockAccount=com.cloud.api.commands.LockAccountCmd;7 -listAccounts=com.cloud.api.commands.ListAccountsCmd;15 -markDefaultZoneForAccount=com.cloud.api.commands.MarkDefaultZoneForAccountCmd;1 +createAccount=3 +deleteAccount=3 +updateAccount=3 +disableAccount=7 +enableAccount=7 +lockAccount=7 +listAccounts=15 +markDefaultZoneForAccount=1 #### User commands -createUser=com.cloud.api.commands.CreateUserCmd;3 -deleteUser=com.cloud.api.commands.DeleteUserCmd;3 -updateUser=com.cloud.api.commands.UpdateUserCmd;3 -listUsers=com.cloud.api.commands.ListUsersCmd;7 -####lockUser=com.cloud.api.commands.LockUserCmd;7 -disableUser=com.cloud.api.commands.DisableUserCmd;7 -enableUser=com.cloud.api.commands.EnableUserCmd;7 -getUser=com.cloud.api.commands.GetUserCmd;1 +createUser=3 +deleteUser=3 +updateUser=15 +listUsers=7 +lockUser=7 +disableUser=7 +enableUser=7 +getUser=1 #### Domain commands -createDomain=com.cloud.api.commands.CreateDomainCmd;1 -updateDomain=com.cloud.api.commands.UpdateDomainCmd;1 -deleteDomain=com.cloud.api.commands.DeleteDomainCmd;1 -listDomains=com.cloud.api.commands.ListDomainsCmd;7 -listDomainChildren=com.cloud.api.commands.ListDomainChildrenCmd;7 +createDomain=1 +updateDomain=1 +deleteDomain=1 +listDomains=7 +listDomainChildren=7 ####Cloud Identifier commands -getCloudIdentifier=com.cloud.api.commands.GetCloudIdentifierCmd;15 +getCloudIdentifier=15 #### Limit commands -updateResourceLimit=com.cloud.api.commands.UpdateResourceLimitCmd;7 -updateResourceCount=com.cloud.api.commands.UpdateResourceCountCmd;7 -listResourceLimits=com.cloud.api.commands.ListResourceLimitsCmd;15 +updateResourceLimit=7 +updateResourceCount=7 +listResourceLimits=15 #### VM commands -deployVirtualMachine=com.cloud.api.commands.DeployVMCmd;15 -destroyVirtualMachine=com.cloud.api.commands.DestroyVMCmd;15 -rebootVirtualMachine=com.cloud.api.commands.RebootVMCmd;15 -startVirtualMachine=com.cloud.api.commands.StartVMCmd;15 -stopVirtualMachine=com.cloud.api.commands.StopVMCmd;15 -resetPasswordForVirtualMachine=com.cloud.api.commands.ResetVMPasswordCmd;15 -changeServiceForVirtualMachine=com.cloud.api.commands.UpgradeVMCmd;15 -updateVirtualMachine=com.cloud.api.commands.UpdateVMCmd;15 -recoverVirtualMachine=com.cloud.api.commands.RecoverVMCmd;7 -listVirtualMachines=com.cloud.api.commands.ListVMsCmd;15 -getVMPassword=com.cloud.api.commands.GetVMPasswordCmd;15 -migrateVirtualMachine=com.cloud.api.commands.MigrateVMCmd;1 -assignVirtualMachine=com.cloud.api.commands.AssignVMCmd;1 -restoreVirtualMachine=com.cloud.api.commands.RestoreVMCmd;15 +deployVirtualMachine=15 +destroyVirtualMachine=15 +rebootVirtualMachine=15 +startVirtualMachine=15 +stopVirtualMachine=15 +resetPasswordForVirtualMachine=15 +updateVirtualMachine=15 +listVirtualMachines=15 +getVMPassword=15 +restoreVirtualMachine=15 +changeServiceForVirtualMachine=15 +assignVirtualMachine=1 +migrateVirtualMachine=1 +recoverVirtualMachine=7 #### snapshot commands -createSnapshot=com.cloud.api.commands.CreateSnapshotCmd;15 -listSnapshots=com.cloud.api.commands.ListSnapshotsCmd;15 -deleteSnapshot=com.cloud.api.commands.DeleteSnapshotCmd;15 -createSnapshotPolicy=com.cloud.api.commands.CreateSnapshotPolicyCmd;15 -deleteSnapshotPolicies=com.cloud.api.commands.DeleteSnapshotPoliciesCmd;15 -listSnapshotPolicies=com.cloud.api.commands.ListSnapshotPoliciesCmd;15 +createSnapshot=15 +listSnapshots=15 +deleteSnapshot=15 +createSnapshotPolicy=15 +deleteSnapshotPolicies=15 +listSnapshotPolicies=15 #### template commands -createTemplate=com.cloud.api.commands.CreateTemplateCmd;15 -registerTemplate=com.cloud.api.commands.RegisterTemplateCmd;15 -updateTemplate=com.cloud.api.commands.UpdateTemplateCmd;15 -copyTemplate=com.cloud.api.commands.CopyTemplateCmd;15 -deleteTemplate=com.cloud.api.commands.DeleteTemplateCmd;15 -listTemplates=com.cloud.api.commands.ListTemplatesCmd;15 -updateTemplatePermissions=com.cloud.api.commands.UpdateTemplatePermissionsCmd;15 -listTemplatePermissions=com.cloud.api.commands.ListTemplatePermissionsCmd;15 -extractTemplate=com.cloud.api.commands.ExtractTemplateCmd;15 -prepareTemplate=com.cloud.api.commands.PrepareTemplateCmd;1 +createTemplate=15 +registerTemplate=15 +updateTemplate=15 +copyTemplate=15 +deleteTemplate=15 +listTemplates=15 +updateTemplatePermissions=15 +listTemplatePermissions=15 +extractTemplate=15 +prepareTemplate=1 #### iso commands -attachIso=com.cloud.api.commands.AttachIsoCmd;15 -detachIso=com.cloud.api.commands.DetachIsoCmd;15 -listIsos=com.cloud.api.commands.ListIsosCmd;15 -registerIso=com.cloud.api.commands.RegisterIsoCmd;15 -updateIso=com.cloud.api.commands.UpdateIsoCmd;15 -deleteIso=com.cloud.api.commands.DeleteIsoCmd;15 -copyIso=com.cloud.api.commands.CopyTemplateCmd;15 -updateIsoPermissions=com.cloud.api.commands.UpdateIsoPermissionsCmd;15 -listIsoPermissions=com.cloud.api.commands.ListIsoPermissionsCmd;15 -extractIso=com.cloud.api.commands.ExtractIsoCmd;15 +attachIso=15 +detachIso=15 +listIsos=15 +registerIso=15 +updateIso=15 +deleteIso=15 +copyIso=15 +updateIsoPermissions=15 +listIsoPermissions=15 +extractIso=15 #### guest OS commands -listOsTypes=com.cloud.api.commands.ListGuestOsCmd;15 -listOsCategories=com.cloud.api.commands.ListGuestOsCategoriesCmd;15 +listOsTypes=15 +listOsCategories=15 #### service offering commands -createServiceOffering=com.cloud.api.commands.CreateServiceOfferingCmd;1 -deleteServiceOffering=com.cloud.api.commands.DeleteServiceOfferingCmd;1 -updateServiceOffering=com.cloud.api.commands.UpdateServiceOfferingCmd;1 -listServiceOfferings=com.cloud.api.commands.ListServiceOfferingsCmd;15 +createServiceOffering=1 +deleteServiceOffering=1 +updateServiceOffering=1 +listServiceOfferings=15 #### disk offering commands -createDiskOffering=com.cloud.api.commands.CreateDiskOfferingCmd;1 -updateDiskOffering=com.cloud.api.commands.UpdateDiskOfferingCmd;1 -deleteDiskOffering=com.cloud.api.commands.DeleteDiskOfferingCmd;1 -listDiskOfferings=com.cloud.api.commands.ListDiskOfferingsCmd;15 +createDiskOffering=1 +updateDiskOffering=1 +deleteDiskOffering=1 +listDiskOfferings=15 #### vlan commands -createVlanIpRange=com.cloud.api.commands.CreateVlanIpRangeCmd;1 -deleteVlanIpRange=com.cloud.api.commands.DeleteVlanIpRangeCmd;1 -listVlanIpRanges=com.cloud.api.commands.ListVlanIpRangesCmd;1 +createVlanIpRange=1 +deleteVlanIpRange=1 +listVlanIpRanges=1 #### address commands -associateIpAddress=com.cloud.api.commands.AssociateIPAddrCmd;15 -disassociateIpAddress=com.cloud.api.commands.DisassociateIPAddrCmd;15 -listPublicIpAddresses=com.cloud.api.commands.ListPublicIpAddressesCmd;15 +associateIpAddress=15 +disassociateIpAddress=15 +listPublicIpAddresses=15 #### firewall commands -listPortForwardingRules=com.cloud.api.commands.ListPortForwardingRulesCmd;15 -createPortForwardingRule=com.cloud.api.commands.CreatePortForwardingRuleCmd;15 -deletePortForwardingRule=com.cloud.api.commands.DeletePortForwardingRuleCmd;15 -#### updatePortForwardingRule=com.cloud.api.commands.UpdatePortForwardingRuleCmd;15 +listPortForwardingRules=15 +createPortForwardingRule=15 +deletePortForwardingRule=15 +updatePortForwardingRule=15 #### NAT commands -enableStaticNat=com.cloud.api.commands.EnableStaticNatCmd;15 -createIpForwardingRule=com.cloud.api.commands.CreateIpForwardingRuleCmd;15 -deleteIpForwardingRule=com.cloud.api.commands.DeleteIpForwardingRuleCmd;15 -listIpForwardingRules=com.cloud.api.commands.ListIpForwardingRulesCmd;15 -disableStaticNat=com.cloud.api.commands.DisableStaticNatCmd;15 +enableStaticNat=15 +createIpForwardingRule=15 +deleteIpForwardingRule=15 +listIpForwardingRules=15 +disableStaticNat=15 #### load balancer commands -createLoadBalancerRule=com.cloud.api.commands.CreateLoadBalancerRuleCmd;15 -deleteLoadBalancerRule=com.cloud.api.commands.DeleteLoadBalancerRuleCmd;15 -removeFromLoadBalancerRule=com.cloud.api.commands.RemoveFromLoadBalancerRuleCmd;15 -assignToLoadBalancerRule=com.cloud.api.commands.AssignToLoadBalancerRuleCmd;15 -createLBStickinessPolicy=com.cloud.api.commands.CreateLBStickinessPolicyCmd;15 -deleteLBStickinessPolicy=com.cloud.api.commands.DeleteLBStickinessPolicyCmd;15 -listLoadBalancerRules=com.cloud.api.commands.ListLoadBalancerRulesCmd;15 -listLBStickinessPolicies=com.cloud.api.commands.ListLBStickinessPoliciesCmd;15 -listLoadBalancerRuleInstances=com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd;15 -updateLoadBalancerRule=com.cloud.api.commands.UpdateLoadBalancerRuleCmd;15 +createLoadBalancerRule=15 +deleteLoadBalancerRule=15 +removeFromLoadBalancerRule=15 +assignToLoadBalancerRule=15 +createLBStickinessPolicy=15 +deleteLBStickinessPolicy=15 +listLoadBalancerRules=15 +listLBStickinessPolicies=15 +listLoadBalancerRuleInstances=15 +updateLoadBalancerRule=15 + +#### autoscale commands +createCounter=1 +createCondition=15 +createAutoScalePolicy=15 +createAutoScaleVmProfile=15 +createAutoScaleVmGroup=15 +deleteCounter=1 +deleteCondition=15 +deleteAutoScalePolicy=15 +deleteAutoScaleVmProfile=15 +deleteAutoScaleVmGroup=15 +listCounters=15 +listConditions=15 +listAutoScalePolicies=15 +listAutoScaleVmProfiles=15 +listAutoScaleVmGroups=15 +enableAutoScaleVmGroup=15 +disableAutoScaleVmGroup=15 +updateAutoScalePolicy=15 +updateAutoScaleVmProfile=15 +updateAutoScaleVmGroup=15 #### router commands -startRouter=com.cloud.api.commands.StartRouterCmd;7 -rebootRouter=com.cloud.api.commands.RebootRouterCmd;7 -stopRouter=com.cloud.api.commands.StopRouterCmd;7 -destroyRouter=com.cloud.api.commands.DestroyRouterCmd;7 -changeServiceForRouter=com.cloud.api.commands.UpgradeRouterCmd;7 -listRouters=com.cloud.api.commands.ListRoutersCmd;7 +startRouter=7 +rebootRouter=7 +stopRouter=7 +destroyRouter=7 +changeServiceForRouter=7 +listRouters=7 +listVirtualRouterElements=7 +configureVirtualRouterElement=7 +createVirtualRouterElement=7 #### system vm commands -startSystemVm=com.cloud.api.commands.StartSystemVMCmd;1 -rebootSystemVm=com.cloud.api.commands.RebootSystemVmCmd;1 -stopSystemVm=com.cloud.api.commands.StopSystemVmCmd;1 -destroySystemVm=com.cloud.api.commands.DestroySystemVmCmd;1 -listSystemVms=com.cloud.api.commands.ListSystemVMsCmd;3 -migrateSystemVm=com.cloud.api.commands.MigrateSystemVMCmd;1 -changeServiceForSystemVm=com.cloud.api.commands.UpgradeSystemVMCmd;1 +startSystemVm=1 +rebootSystemVm=1 +stopSystemVm=1 +destroySystemVm=1 +listSystemVms=3 +migrateSystemVm=1 +changeServiceForSystemVm=1 #### configuration commands -updateConfiguration=com.cloud.api.commands.UpdateCfgCmd;1 -listConfigurations=com.cloud.api.commands.ListCfgsByCmd;1 -ldapConfig=com.cloud.api.commands.LDAPConfigCmd;1 -ldapRemove=com.cloud.api.commands.LDAPRemoveCmd;1 -listCapabilities=com.cloud.api.commands.ListCapabilitiesCmd;15 +updateConfiguration=1 +listConfigurations=1 +ldapConfig=1 +ldapRemove=1 +listCapabilities=15 #### pod commands -createPod=com.cloud.api.commands.CreatePodCmd;1 -updatePod=com.cloud.api.commands.UpdatePodCmd;1 -deletePod=com.cloud.api.commands.DeletePodCmd;1 -listPods=com.cloud.api.commands.ListPodsByCmd;3 +createPod=1 +updatePod=1 +deletePod=1 +listPods=3 #### zone commands -createZone=com.cloud.api.commands.CreateZoneCmd;1 -updateZone=com.cloud.api.commands.UpdateZoneCmd;1 -deleteZone=com.cloud.api.commands.DeleteZoneCmd;1 -listZones=com.cloud.api.commands.ListZonesByCmd;15 +createZone=1 +updateZone=1 +deleteZone=1 +listZones=15 #### events commands -listEvents=com.cloud.api.commands.ListEventsCmd;15 -listEventTypes=com.cloud.api.commands.ListEventTypesCmd;15 +listEvents=15 +listEventTypes=15 #### alerts commands -listAlerts=com.cloud.api.commands.ListAlertsCmd;3 +listAlerts=3 #### system capacity commands -listCapacity=com.cloud.api.commands.ListCapacityCmd;3 +listCapacity=3 -#### swift commands^M -addSwift=com.cloud.api.commands.AddSwiftCmd;1 -listSwifts=com.cloud.api.commands.ListSwiftsCmd;1 +#### swift commands +addSwift=1 +listSwifts=1 +#### s3 commands +addS3=1 +listS3s=1 #### host commands -addHost=com.cloud.api.commands.AddHostCmd;3 -addCluster=com.cloud.api.commands.AddClusterCmd;1 -deleteCluster=com.cloud.api.commands.DeleteClusterCmd;1 -updateCluster=com.cloud.api.commands.UpdateClusterCmd;1 -reconnectHost=com.cloud.api.commands.ReconnectHostCmd;1 -updateHost=com.cloud.api.commands.UpdateHostCmd;1 -deleteHost=com.cloud.api.commands.DeleteHostCmd;3 -prepareHostForMaintenance=com.cloud.api.commands.PrepareForMaintenanceCmd;1 -cancelHostMaintenance=com.cloud.api.commands.CancelMaintenanceCmd;1 -listHosts=com.cloud.api.commands.ListHostsCmd;3 -addSecondaryStorage=com.cloud.api.commands.AddSecondaryStorageCmd;1 -updateHostPassword=com.cloud.api.commands.UpdateHostPasswordCmd;1 +addHost=3 +addCluster=1 +deleteCluster=1 +updateCluster=1 +reconnectHost=1 +updateHost=1 +deleteHost=3 +prepareHostForMaintenance=1 +cancelHostMaintenance=1 +listHosts=3 +addSecondaryStorage=1 +updateHostPassword=1 #### volume commands -attachVolume=com.cloud.api.commands.AttachVolumeCmd;15 -uploadVolume=com.cloud.api.commands.UploadVolumeCmd;15 -detachVolume=com.cloud.api.commands.DetachVolumeCmd;15 -createVolume=com.cloud.api.commands.CreateVolumeCmd;15 -deleteVolume=com.cloud.api.commands.DeleteVolumeCmd;15 -listVolumes=com.cloud.api.commands.ListVolumesCmd;15 -extractVolume=com.cloud.api.commands.ExtractVolumeCmd;15 -migrateVolume=com.cloud.api.commands.MigrateVolumeCmd;15 +attachVolume=15 +uploadVolume=15 +detachVolume=15 +createVolume=15 +deleteVolume=15 +listVolumes=15 +extractVolume=15 +migrateVolume=15 #### registration command: FIXME -- this really should be something in management server that #### generates a new key for the user and they just have to #### use that key...the key is stored in the db associated w/ #### the userId...every request to the developer API should be #### checked against the key -registerUserKeys=com.cloud.api.commands.RegisterCmd;1 +registerUserKeys=15 ### async-query command -queryAsyncJobResult=com.cloud.api.commands.QueryAsyncJobResultCmd;15 -listAsyncJobs=com.cloud.api.commands.ListAsyncJobsCmd;15 +queryAsyncJobResult=15 +listAsyncJobs=15 #### storage pools commands -listStoragePools=com.cloud.api.commands.ListStoragePoolsCmd;3 -createStoragePool=com.cloud.api.commands.CreateStoragePoolCmd;1 -updateStoragePool=com.cloud.api.commands.UpdateStoragePoolCmd;1 -deleteStoragePool=com.cloud.api.commands.DeletePoolCmd;1 -listClusters=com.cloud.api.commands.ListClustersCmd;3 -enableStorageMaintenance=com.cloud.api.commands.PreparePrimaryStorageForMaintenanceCmd;1 -cancelStorageMaintenance=com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd;1 +listStoragePools=3 +createStoragePool=1 +updateStoragePool=1 +deleteStoragePool=1 +listClusters=3 +enableStorageMaintenance=1 +cancelStorageMaintenance=1 #### security group commands -createSecurityGroup=com.cloud.api.commands.CreateSecurityGroupCmd;15 -deleteSecurityGroup=com.cloud.api.commands.DeleteSecurityGroupCmd;15 -authorizeSecurityGroupIngress=com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd;15 -revokeSecurityGroupIngress=com.cloud.api.commands.RevokeSecurityGroupIngressCmd;15 -authorizeSecurityGroupEgress=com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd;15 -revokeSecurityGroupEgress=com.cloud.api.commands.RevokeSecurityGroupEgressCmd;15 -listSecurityGroups=com.cloud.api.commands.ListSecurityGroupsCmd;15 +createSecurityGroup=15 +deleteSecurityGroup=15 +authorizeSecurityGroupIngress=15 +revokeSecurityGroupIngress=15 +authorizeSecurityGroupEgress=15 +revokeSecurityGroupEgress=15 +listSecurityGroups=15 #### vm group commands -createInstanceGroup=com.cloud.api.commands.CreateVMGroupCmd;15 -deleteInstanceGroup=com.cloud.api.commands.DeleteVMGroupCmd;15 -updateInstanceGroup=com.cloud.api.commands.UpdateVMGroupCmd;15 -listInstanceGroups=com.cloud.api.commands.ListVMGroupsCmd;15 +createInstanceGroup=15 +deleteInstanceGroup=15 +updateInstanceGroup=15 +listInstanceGroups=15 ### Certificate commands -uploadCustomCertificate=com.cloud.api.commands.UploadCustomCertificateCmd;1 +uploadCustomCertificate=1 ### other commands -listHypervisors=com.cloud.api.commands.ListHypervisorsCmd;15 +listHypervisors=15 ### VPN -createRemoteAccessVpn=com.cloud.api.commands.CreateRemoteAccessVpnCmd;15 -deleteRemoteAccessVpn=com.cloud.api.commands.DeleteRemoteAccessVpnCmd;15 -listRemoteAccessVpns=com.cloud.api.commands.ListRemoteAccessVpnsCmd;15 +createRemoteAccessVpn=15 +deleteRemoteAccessVpn=15 +listRemoteAccessVpns=15 -addVpnUser=com.cloud.api.commands.AddVpnUserCmd;15 -removeVpnUser=com.cloud.api.commands.RemoveVpnUserCmd;15 -listVpnUsers=com.cloud.api.commands.ListVpnUsersCmd;15 +addVpnUser=15 +removeVpnUser=15 +listVpnUsers=15 #### network offering commands -createNetworkOffering=com.cloud.api.commands.CreateNetworkOfferingCmd;1 -updateNetworkOffering=com.cloud.api.commands.UpdateNetworkOfferingCmd;1 -deleteNetworkOffering=com.cloud.api.commands.DeleteNetworkOfferingCmd;1 -listNetworkOfferings=com.cloud.api.commands.ListNetworkOfferingsCmd;15 +createNetworkOffering=1 +updateNetworkOffering=1 +deleteNetworkOffering=1 +listNetworkOfferings=15 #### network commands -createNetwork=com.cloud.api.commands.CreateNetworkCmd;15 -deleteNetwork=com.cloud.api.commands.DeleteNetworkCmd;15 -listNetworks=com.cloud.api.commands.ListNetworksCmd;15 -restartNetwork=com.cloud.api.commands.RestartNetworkCmd;15 -updateNetwork=com.cloud.api.commands.UpdateNetworkCmd;15 +createNetwork=15 +deleteNetwork=15 +listNetworks=15 +restartNetwork=15 +updateNetwork=15 #### SSH key pair commands -registerSSHKeyPair=com.cloud.api.commands.RegisterSSHKeyPairCmd;15 -createSSHKeyPair=com.cloud.api.commands.CreateSSHKeyPairCmd;15 -deleteSSHKeyPair=com.cloud.api.commands.DeleteSSHKeyPairCmd;15 -listSSHKeyPairs=com.cloud.api.commands.ListSSHKeyPairsCmd;15 +registerSSHKeyPair=15 +createSSHKeyPair=15 +deleteSSHKeyPair=15 +listSSHKeyPairs=15 #### Projects commands -createProject=com.cloud.api.commands.CreateProjectCmd;15 -deleteProject=com.cloud.api.commands.DeleteProjectCmd;15 -updateProject=com.cloud.api.commands.UpdateProjectCmd;15 -activateProject=com.cloud.api.commands.ActivateProjectCmd;15 -suspendProject=com.cloud.api.commands.SuspendProjectCmd;15 -listProjects=com.cloud.api.commands.ListProjectsCmd;15 -addAccountToProject=com.cloud.api.commands.AddAccountToProjectCmd;15 -deleteAccountFromProject=com.cloud.api.commands.DeleteAccountFromProjectCmd;15 -listProjectAccounts=com.cloud.api.commands.ListProjectAccountsCmd;15 -listProjectInvitations=com.cloud.api.commands.ListProjectInvitationsCmd;15 -updateProjectInvitation=com.cloud.api.commands.UpdateProjectInvitationCmd;15 -deleteProjectInvitation=com.cloud.api.commands.DeleteProjectInvitationCmd;15 +createProject=15 +deleteProject=15 +updateProject=15 +activateProject=15 +suspendProject=15 +listProjects=15 +addAccountToProject=15 +deleteAccountFromProject=15 +listProjectAccounts=15 +listProjectInvitations=15 +updateProjectInvitation=15 +deleteProjectInvitation=15 #### -createFirewallRule=com.cloud.api.commands.CreateFirewallRuleCmd;15 -deleteFirewallRule=com.cloud.api.commands.DeleteFirewallRuleCmd;15 -listFirewallRules=com.cloud.api.commands.ListFirewallRulesCmd;15 +createFirewallRule=15 +deleteFirewallRule=15 +listFirewallRules=15 #### hypervisor capabilities commands -updateHypervisorCapabilities=com.cloud.api.commands.UpdateHypervisorCapabilitiesCmd;1 -listHypervisorCapabilities=com.cloud.api.commands.ListHypervisorCapabilitiesCmd;1 +updateHypervisorCapabilities=1 +listHypervisorCapabilities=1 #### Physical Network commands -createPhysicalNetwork=com.cloud.api.commands.CreatePhysicalNetworkCmd;1 -deletePhysicalNetwork=com.cloud.api.commands.DeletePhysicalNetworkCmd;1 -listPhysicalNetworks=com.cloud.api.commands.ListPhysicalNetworksCmd;1 -updatePhysicalNetwork=com.cloud.api.commands.UpdatePhysicalNetworkCmd;1 +createPhysicalNetwork=1 +deletePhysicalNetwork=1 +listPhysicalNetworks=1 +updatePhysicalNetwork=1 #### Physical Network Service Provider commands -listSupportedNetworkServices=com.cloud.api.commands.ListSupportedNetworkServicesCmd;1 -addNetworkServiceProvider=com.cloud.api.commands.AddNetworkServiceProviderCmd;1 -deleteNetworkServiceProvider=com.cloud.api.commands.DeleteNetworkServiceProviderCmd;1 -listNetworkServiceProviders=com.cloud.api.commands.ListNetworkServiceProvidersCmd;1 -updateNetworkServiceProvider=com.cloud.api.commands.UpdateNetworkServiceProviderCmd;1 +listSupportedNetworkServices=1 +addNetworkServiceProvider=1 +deleteNetworkServiceProvider=1 +listNetworkServiceProviders=1 +updateNetworkServiceProvider=1 #### Physical Network Traffic Type commands -addTrafficType=com.cloud.api.commands.AddTrafficTypeCmd;1 -deleteTrafficType=com.cloud.api.commands.DeleteTrafficTypeCmd;1 -listTrafficTypes=com.cloud.api.commands.ListTrafficTypesCmd;1 -updateTrafficType=com.cloud.api.commands.UpdateTrafficTypeCmd;1 -listTrafficTypeImplementors=com.cloud.api.commands.ListTrafficTypeImplementorsCmd;1 +addTrafficType=1 +deleteTrafficType=1 +listTrafficTypes=1 +updateTrafficType=1 +listTrafficTypeImplementors=1 #### Storage Network commands -createStorageNetworkIpRange=com.cloud.api.commands.CreateStorageNetworkIpRangeCmd;1 -deleteStorageNetworkIpRange=com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd;1 -listStorageNetworkIpRange=com.cloud.api.commands.listStorageNetworkIpRangeCmd;1 -updateStorageNetworkIpRange=com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd;1 +createStorageNetworkIpRange=1 +deleteStorageNetworkIpRange=1 +listStorageNetworkIpRange=1 +updateStorageNetworkIpRange=1 ### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 - -### Network Devices commands -addNetworkDevice=com.cloud.api.commands.AddNetworkDeviceCmd;1 -listNetworkDevice=com.cloud.api.commands.ListNetworkDeviceCmd;1 -deleteNetworkDevice=com.cloud.api.commands.DeleteNetworkDeviceCmd;1 +addNetworkDevice=1 +listNetworkDevice=1 +deleteNetworkDevice=1 ### VPC commands -createVPC=com.cloud.api.commands.CreateVPCCmd;15 -listVPCs=com.cloud.api.commands.ListVPCsCmd;15 -deleteVPC=com.cloud.api.commands.DeleteVPCCmd;15 -updateVPC=com.cloud.api.commands.UpdateVPCCmd;15 -restartVPC=com.cloud.api.commands.RestartVPCCmd;15 +createVPC=15 +listVPCs=15 +deleteVPC=15 +updateVPC=15 +restartVPC=15 #### VPC offering commands -createVPCOffering=com.cloud.api.commands.CreateVPCOfferingCmd;1 -updateVPCOffering=com.cloud.api.commands.UpdateVPCOfferingCmd;1 -deleteVPCOffering=com.cloud.api.commands.DeleteVPCOfferingCmd;1 -listVPCOfferings=com.cloud.api.commands.ListVPCOfferingsCmd;15 +createVPCOffering=1 +updateVPCOffering=1 +deleteVPCOffering=1 +listVPCOfferings=15 #### Private gateway commands -createPrivateGateway=com.cloud.api.commands.CreatePrivateGatewayCmd;1 -listPrivateGateways=com.cloud.api.commands.ListPrivateGatewaysCmd;15 -deletePrivateGateway=com.cloud.api.commands.DeletePrivateGatewayCmd;1 +createPrivateGateway=1 +listPrivateGateways=15 +deletePrivateGateway=1 #### Network ACL commands -createNetworkACL=com.cloud.api.commands.CreateNetworkACLCmd;15 -deleteNetworkACL=com.cloud.api.commands.DeleteNetworkACLCmd;15 -listNetworkACLs=com.cloud.api.commands.ListNetworkACLsCmd;15 +createNetworkACL=15 +deleteNetworkACL=15 +listNetworkACLs=15 #### Static route commands -createStaticRoute=com.cloud.api.commands.CreateStaticRouteCmd;15 -deleteStaticRoute=com.cloud.api.commands.DeleteStaticRouteCmd;15 -listStaticRoutes=com.cloud.api.commands.ListStaticRoutesCmd;15 +createStaticRoute=15 +deleteStaticRoute=15 +listStaticRoutes=15 #### Tags commands -createTags=com.cloud.api.commands.CreateTagsCmd;15 -deleteTags=com.cloud.api.commands.DeleteTagsCmd;15 -listTags=com.cloud.api.commands.ListTagsCmd;15 +createTags=15 +deleteTags=15 +listTags=15 ### Site-to-site VPN commands -createVpnCustomerGateway=com.cloud.api.commands.CreateVpnCustomerGatewayCmd;15 -createVpnGateway=com.cloud.api.commands.CreateVpnGatewayCmd;15 -createVpnConnection=com.cloud.api.commands.CreateVpnConnectionCmd;15 -deleteVpnCustomerGateway=com.cloud.api.commands.DeleteVpnCustomerGatewayCmd;15 -deleteVpnGateway=com.cloud.api.commands.DeleteVpnGatewayCmd;15 -deleteVpnConnection=com.cloud.api.commands.DeleteVpnConnectionCmd;15 -updateVpnCustomerGateway=com.cloud.api.commands.UpdateVpnCustomerGatewayCmd;15 -resetVpnConnection=com.cloud.api.commands.ResetVpnConnectionCmd;15 -listVpnCustomerGateways=com.cloud.api.commands.ListVpnCustomerGatewaysCmd;15 -listVpnGateways=com.cloud.api.commands.ListVpnGatewaysCmd;15 -listVpnConnections=com.cloud.api.commands.ListVpnConnectionsCmd;15 +createVpnCustomerGateway=15 +createVpnGateway=15 +createVpnConnection=15 +deleteVpnCustomerGateway=15 +deleteVpnGateway=15 +deleteVpnConnection=15 +updateVpnCustomerGateway=15 +resetVpnConnection=15 +listVpnCustomerGateways=15 +listVpnGateways=15 +listVpnConnections=15 diff --git a/client/tomcatconf/components-nonoss.xml.in b/client/tomcatconf/components-nonoss.xml.in new file mode 100755 index 00000000000..fbfc5cc2726 --- /dev/null +++ b/client/tomcatconf/components-nonoss.xml.in @@ -0,0 +1,97 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + true + + + + + + diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index 5730b832075..a7378bd9f49 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -53,6 +53,9 @@ under the License. true + + + @@ -109,6 +112,7 @@ under the License. + @@ -146,7 +150,7 @@ under the License. - + @@ -179,6 +183,7 @@ under the License. + 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/client/tomcatconf/f5bigip_commands.properties.in b/client/tomcatconf/f5bigip_commands.properties.in index e48bd482d20..8c3cc2a145a 100644 --- a/client/tomcatconf/f5bigip_commands.properties.in +++ b/client/tomcatconf/f5bigip_commands.properties.in @@ -21,12 +21,12 @@ #### f5 big ip load balancer commands #Deprecated commands -addExternalLoadBalancer = com.cloud.api.commands.AddExternalLoadBalancerCmd;1 -deleteExternalLoadBalancer = com.cloud.api.commands.DeleteExternalLoadBalancerCmd;1 -listExternalLoadBalancers = com.cloud.api.commands.ListExternalLoadBalancersCmd;1 +addExternalLoadBalancer=1 +deleteExternalLoadBalancer=1 +listExternalLoadBalancers=1 -addF5LoadBalancer = com.cloud.api.commands.AddF5LoadBalancerCmd;1 -configureF5LoadBalancer = com.cloud.api.commands.ConfigureF5LoadBalancerCmd;1 -deleteF5LoadBalancer = com.cloud.api.commands.DeleteF5LoadBalancerCmd;1 -listF5LoadBalancers = com.cloud.api.commands.ListF5LoadBalancersCmd;1 -listF5LoadBalancerNetworks = com.cloud.api.commands.ListF5LoadBalancerNetworksCmd;1 +addF5LoadBalancer=1 +configureF5LoadBalancer=1 +deleteF5LoadBalancer=1 +listF5LoadBalancers=1 +listF5LoadBalancerNetworks=1 diff --git a/client/tomcatconf/junipersrx_commands.properties.in b/client/tomcatconf/junipersrx_commands.properties.in index 57fd0893ce0..2cadc62c57e 100644 --- a/client/tomcatconf/junipersrx_commands.properties.in +++ b/client/tomcatconf/junipersrx_commands.properties.in @@ -19,12 +19,12 @@ ### Please standardize naming conventions to camel-case (even for acronyms). #### juniper srx firewall commands -addExternalFirewall = com.cloud.api.commands.AddExternalFirewallCmd;1 -deleteExternalFirewall = com.cloud.api.commands.DeleteExternalFirewallCmd;1 -listExternalFirewalls = com.cloud.api.commands.ListExternalFirewallsCmd;1 +addExternalFirewall=1 +deleteExternalFirewall=1 +listExternalFirewalls=1 -addSrxFirewall = com.cloud.api.commands.AddSrxFirewallCmd;1 -deleteSrxFirewall = com.cloud.api.commands.DeleteSrxFirewallCmd;1 -configureSrxFirewall = com.cloud.api.commands.ConfigureSrxFirewallCmd;1 -listSrxFirewalls = com.cloud.api.commands.ListSrxFirewallsCmd;1 -listSrxFirewallNetworks = com.cloud.api.commands.ListSrxFirewallNetworksCmd;1 +addSrxFirewall=1 +deleteSrxFirewall=1 +configureSrxFirewall=1 +listSrxFirewalls=1 +listSrxFirewallNetworks=1 diff --git a/client/tomcatconf/log4j-cloud.xml.in b/client/tomcatconf/log4j-cloud.xml.in index 6c7f29d0162..02f70998d53 100755 --- a/client/tomcatconf/log4j-cloud.xml.in +++ b/client/tomcatconf/log4j-cloud.xml.in @@ -104,6 +104,10 @@ under the License. + + + + diff --git a/client/tomcatconf/netapp_commands.properties.in b/client/tomcatconf/netapp_commands.properties.in index 21844035592..ea17ac0560b 100644 --- a/client/tomcatconf/netapp_commands.properties.in +++ b/client/tomcatconf/netapp_commands.properties.in @@ -19,15 +19,15 @@ ### Please standardize naming conventions to camel-case (even for acronyms). ####Netapp integration commands -createVolumeOnFiler=com.cloud.api.commands.netapp.CreateVolumeOnFilerCmd;15 -destroyVolumeOnFiler=com.cloud.api.commands.netapp.DestroyVolumeOnFilerCmd;15 -listVolumesOnFiler=com.cloud.api.commands.netapp.ListVolumesOnFilerCmd;15 -createLunOnFiler=com.cloud.api.commands.netapp.CreateLunCmd;15 -destroyLunOnFiler=com.cloud.api.commands.netapp.DestroyLunCmd;15 -listLunsOnFiler=com.cloud.api.commands.netapp.ListLunsCmd;15 -associateLun=com.cloud.api.commands.netapp.AssociateLunCmd;15 -dissociateLun=com.cloud.api.commands.netapp.DissociateLunCmd;15 -createPool=com.cloud.api.commands.netapp.CreateVolumePoolCmd;15 -deletePool=com.cloud.api.commands.netapp.DeleteVolumePoolCmd;15 -modifyPool=com.cloud.api.commands.netapp.ModifyVolumePoolCmd;15 -listPools=com.cloud.api.commands.netapp.ListVolumePoolsCmd;15 +createVolumeOnFiler=15 +destroyVolumeOnFiler=15 +listVolumesOnFiler=15 +createLunOnFiler=15 +destroyLunOnFiler=15 +listLunsOnFiler=15 +associateLun=15 +dissociateLun=15 +createPool=15 +deletePool=15 +modifyPool=15 +listPools=15 diff --git a/client/tomcatconf/netscalerloadbalancer_commands.properties.in b/client/tomcatconf/netscalerloadbalancer_commands.properties.in index 114e7d37cca..9eeb8da9987 100644 --- a/client/tomcatconf/netscalerloadbalancer_commands.properties.in +++ b/client/tomcatconf/netscalerloadbalancer_commands.properties.in @@ -19,8 +19,8 @@ ### Please standardize naming conventions to camel-case (even for acronyms). #### netscaler load balancer commands -addNetscalerLoadBalancer = com.cloud.api.commands.AddNetscalerLoadBalancerCmd;1 -deleteNetscalerLoadBalancer = com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd;1 -configureNetscalerLoadBalancer = com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd;1 -listNetscalerLoadBalancers = com.cloud.api.commands.ListNetscalerLoadBalancersCmd;1 -listNetscalerLoadBalancerNetworks = com.cloud.api.commands.ListNetscalerLoadBalancerNetworksCmd;1 +addNetscalerLoadBalancer=1 +deleteNetscalerLoadBalancer=1 +configureNetscalerLoadBalancer=1 +listNetscalerLoadBalancers=1 +listNetscalerLoadBalancerNetworks=1 diff --git a/client/tomcatconf/nicira-nvp_commands.properties.in b/client/tomcatconf/nicira-nvp_commands.properties.in index 3a934adef67..1b2b5253394 100644 --- a/client/tomcatconf/nicira-nvp_commands.properties.in +++ b/client/tomcatconf/nicira-nvp_commands.properties.in @@ -20,10 +20,10 @@ #### nicira nvp commands -addNiciraNvpDevice = com.cloud.api.commands.AddNiciraNvpDeviceCmd;1 -deleteNiciraNvpDevice = com.cloud.api.commands.DeleteNiciraNvpDeviceCmd;1 -listNiciraNvpDevices = com.cloud.api.commands.ListNiciraNvpDevicesCmd;1 -listNiciraNvpDeviceNetworks = com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd;1 +addNiciraNvpDevice=1 +deleteNiciraNvpDevice=1 +listNiciraNvpDevices=1 +listNiciraNvpDeviceNetworks=1 # Not implemented (yet) -#configureNiciraNvpDevice = com.cloud.api.commands.ConfigureNiciraNvpDeviceCmd;1 +#configureNiciraNvpDevice=1 diff --git a/client/tomcatconf/server-nonssl.xml b/client/tomcatconf/server-nonssl.xml.in similarity index 98% rename from client/tomcatconf/server-nonssl.xml rename to client/tomcatconf/server-nonssl.xml.in index 607b0b3b8d6..847197cbae0 100755 --- a/client/tomcatconf/server-nonssl.xml +++ b/client/tomcatconf/server-nonssl.xml.in @@ -68,7 +68,7 @@ redirectPort="8443" /> --> - - --> - - = 17 +BuildRequires: java-1.7.0-openjdk-devel +%else BuildRequires: java-1.6.0-openjdk-devel +%endif BuildRequires: tomcat6 BuildRequires: ws-commons-util BuildRequires: jpackage-utils @@ -220,6 +224,7 @@ Requires: jna Requires: ebtables Requires: jsvc Requires: jakarta-commons-daemon +Requires: bridge-utils Group: System Environment/Libraries Requires: kvm @@ -286,6 +291,7 @@ Summary: CloudStack CloudBridge Group: System Environment/Libraries Requires: java >= 1.6.0 Requires: tomcat6 +Requires: %{name}-deps = %{version} %if 0%{?fedora} > 15 Requires: apache-commons-lang %endif @@ -331,15 +337,10 @@ if [ "$1" == "0" ] ; then /sbin/service %{name}-management stop > /dev/null 2>&1 || true fi -%pre client +%pre aws-api id %{name} > /dev/null 2>&1 || /usr/sbin/useradd -M -c "CloudStack unprivileged user" \ -r -s /bin/sh -d %{_sharedstatedir}/%{name}/management %{name}|| true -# set max file descriptors for cloud user to 4096 -sed -i /"cloud hard nofile"/d /etc/security/limits.conf -sed -i /"cloud soft nofile"/d /etc/security/limits.conf -echo "cloud hard nofile 4096" >> /etc/security/limits.conf -echo "cloud soft nofile 4096" >> /etc/security/limits.conf rm -rf %{_localstatedir}/cache/%{name} # user harcoded here, also hardcoded on wscript @@ -397,18 +398,18 @@ fi /sbin/chkconfig --level 345 %{name}-management on > /dev/null 2>&1 || true root=/usr/share/cloud/bridge - target=/usr/share/cloud/management/ + target=/usr/share/cloud/management mkdir -p $target/webapps7080 - if [ ! -e $target/webapps7080/awsapi ]; then - ln -s $root/webapps/awsapi $target/webapps7080/awsapi + if [ ! -h $target/webapps7080/awsapi ]; then + ln -sf $root/webapps7080/awsapi $target/webapps7080/awsapi fi - jars=`ls $root/lib` - for j in $jars - do - cp -f $root/lib/$j $root/webapps/awsapi/WEB-INF/lib/ - done +# jars=`ls $root/lib` +# for j in $jars +# do +# cp -f $root/lib/$j $root/webapps/awsapi/WEB-INF/lib/ +# done confs="cloud-bridge.properties ec2-service.properties" for c in $confs @@ -423,8 +424,6 @@ fi %attr(0755,root,root) %{_bindir}/cloud-sccs %attr(0755,root,root) %{_bindir}/cloud-gitrevs %doc %{_docdir}/%{name}-%{version}/version-info -%doc %{_docdir}/%{name}-%{version}/sccs-info -%doc %{_docdir}/%{name}-%{version}/configure-info %doc LICENSE %doc NOTICE @@ -464,6 +463,18 @@ fi %files deps %defattr(0644,root,root,0755) +%{_javadir}/axiom-*.jar +%{_javadir}/axis2-*.jar +%{_javadir}/antlr*.jar +%{_javadir}/XmlSchema-*.jar +%{_javadir}/json-simple*.jar +%{_javadir}/neethi*.jar +%{_javadir}/woden*.jar +%{_javadir}/xercesImpl*.jar +%{_javadir}/xml-apis*.jar +%{_javadir}/dom4j*.jar +%{_javadir}/javassist*.jar +%{_javadir}/commons-fileupload*.jar %{_javadir}/commons-codec-1.6.jar %{_javadir}/commons-dbcp-1.4.jar %{_javadir}/commons-pool-1.6.jar @@ -565,6 +576,7 @@ fi %config(noreplace) %{_sysconfdir}/%{name}/agent/log4j-%{name}.xml %attr(0755,root,root) %{_initrddir}/%{name}-agent %attr(0755,root,root) %{_bindir}/%{name}-setup-agent +%attr(0755,root,root) %{_bindir}/%{name}-ssh %dir %attr(0770,root,root) %{_localstatedir}/log/%{name}/agent %doc LICENSE %doc NOTICE @@ -607,6 +619,9 @@ fi %doc NOTICE %changelog +* Mon Nov 19 2012 Satoshi Kobayashi 4.0.1 +- adding dependency bridge-utils to fix a system requirement + * Fri Sep 14 2012 Marcus Sorensen 4.0.1 - adding dependency jakarta-commons-daemon to fix "cannot find daemon loader" diff --git a/console-proxy/js/ajaxkeys.js b/console-proxy/js/ajaxkeys.js new file mode 100644 index 00000000000..2ecf5b561e0 --- /dev/null +++ b/console-proxy/js/ajaxkeys.js @@ -0,0 +1,77 @@ +/* +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. +*/ + +/* + * This var contains the limited keyboard translation tables. + * This is the table that users can modify to make special keyboard to work properly. + * They are used by the ajaxviewer.js + */ + +//client event type. corresponds to events in ajaxviewer. +X11_KEY_CIRCUMFLEX_ACCENT = 0x5e; // ^ +X11_KEY_YEN_MARK = 0xa5; +X11_KEY_OPEN_BRACKET = 0x5b; +X11_KEY_CLOSE_BRACKET = 0x5d; +X11_KEY_COLON = 0x3a; +X11_KEY_REVERSE_SOLIUS = 0x5c; // another back slash (back slash on JP keyboard) +X11_KEY_CAPSLOCK = 0xffe5; +X11_KEY_SEMI_COLON = 0x3b; +X11_KEY_SHIFT = 0xffe1; +X11_KEY_ADD = 0x2b; + +KEY_DOWN = 5; +KEY_UP = 6; + +//JP keyboard type +// +var keyboardTables = [ + {tindex: 0, keyboardType: "EN-Cooked", mappingTable: + {X11: [ {keycode: 222, entry: X11_KEY_CIRCUMFLEX_ACCENT}, + {keycode: 220, entry: X11_KEY_YEN_MARK}, + {keycode: 219, entry: X11_KEY_OPEN_BRACKET}, + {keycode: 221, entry: X11_KEY_CLOSE_BRACKET}, + {keycode: 59, entry: X11_KEY_COLON, browser: "Firefox"}, + {keycode: 186, entry: X11_KEY_COLON, browser: "Chrome"}, + {keycode: 9, entry: 9, guestos: "XenServer"}, + {keycode: 226, entry: X11_KEY_REVERSE_SOLIUS}, + {keycode: 240, entry: [ + {type: KEY_DOWN, code: X11_KEY_CAPSLOCK, modifiers: 0 }, + {type: KEY_UP, code: X11_KEY_CAPSLOCK, modifiers: 0 }, + ] + }, + ], + keyPress: [ + {keycode: 59, entry: [ + {type: KEY_DOWN, code: X11_KEY_SEMI_COLON, modifiers: 0 }, + {type: KEY_UP, code: X11_KEY_SEMI_COLON, modifiers: 0 }, + ] + }, + {keycode: 43, entry: [ + {type: KEY_DOWN, code: X11_KEY_SHIFT, modifiers: 0, shift: false }, + {type: KEY_DOWN, code: X11_KEY_ADD, modifiers: 0, shift: false }, + {type: KEY_UP, code: X11_KEY_ADD, modifiers: 0, shift: false }, + {type: KEY_UP, code: X11_KEY_SHIFT, modifiers: 0, shift: false }, + {type: KEY_DOWN, code: X11_KEY_ADD, modifiers: 0, shift: true }, + {type: KEY_UP, code: X11_KEY_ADD, modifiers: 0, shift: true }, + ] + }, + ] + } + } ] + diff --git a/console-proxy/js/ajaxviewer.js b/console-proxy/js/ajaxviewer.js index 6ac56be6641..e95615d8946 100644 --- a/console-proxy/js/ajaxviewer.js +++ b/console-proxy/js/ajaxviewer.js @@ -109,17 +109,17 @@ KeyboardMapper.prototype = { // intialize keyboard mapping for RAW keyboard this.jsX11KeysymMap[AjaxViewer.JS_KEY_CAPSLOCK] = AjaxViewer.X11_KEY_CAPSLOCK; this.jsX11KeysymMap[AjaxViewer.JS_KEY_BACKSPACE] = AjaxViewer.X11_KEY_BACKSPACE; - this.jsX11KeysymMap[AjaxViewer.JS_KEY_TAB] = AjaxViewer.X11_KEY_TAB; + this.jsX11KeysymMap[AjaxViewer.JS_KEY_TAB] = AjaxViewer.X11_KEY_TAB; this.jsX11KeysymMap[AjaxViewer.JS_KEY_ENTER] = AjaxViewer.X11_KEY_ENTER; this.jsX11KeysymMap[AjaxViewer.JS_KEY_ESCAPE] = AjaxViewer.X11_KEY_ESCAPE; this.jsX11KeysymMap[AjaxViewer.JS_KEY_INSERT] = AjaxViewer.X11_KEY_INSERT; this.jsX11KeysymMap[AjaxViewer.JS_KEY_DELETE] = AjaxViewer.X11_KEY_DELETE; this.jsX11KeysymMap[AjaxViewer.JS_KEY_HOME] = AjaxViewer.X11_KEY_HOME; - this.jsX11KeysymMap[AjaxViewer.JS_KEY_END] = AjaxViewer.X11_KEY_END; + this.jsX11KeysymMap[AjaxViewer.JS_KEY_END] = AjaxViewer.X11_KEY_END; this.jsX11KeysymMap[AjaxViewer.JS_KEY_PAGEUP] = AjaxViewer.X11_KEY_PAGEUP; this.jsX11KeysymMap[AjaxViewer.JS_KEY_PAGEDOWN] = AjaxViewer.X11_KEY_PAGEDOWN; this.jsX11KeysymMap[AjaxViewer.JS_KEY_LEFT] = AjaxViewer.X11_KEY_LEFT; - this.jsX11KeysymMap[AjaxViewer.JS_KEY_UP] = AjaxViewer.X11_KEY_UP; + this.jsX11KeysymMap[AjaxViewer.JS_KEY_UP] = AjaxViewer.X11_KEY_UP; this.jsX11KeysymMap[AjaxViewer.JS_KEY_RIGHT] = AjaxViewer.X11_KEY_RIGHT; this.jsX11KeysymMap[AjaxViewer.JS_KEY_DOWN] = AjaxViewer.X11_KEY_DOWN; this.jsX11KeysymMap[AjaxViewer.JS_KEY_F1] = AjaxViewer.X11_KEY_F1; @@ -218,7 +218,6 @@ KeyboardMapper.prototype = { this.jsX11KeysymMap[AjaxViewer.JS_KEY_ALT] = AjaxViewer.X11_KEY_ALT; } }, - RawkeyboardInputHandler : function(eventType, code, modifiers, guestos, browser, browserVersion) { if(eventType == AjaxViewer.KEY_DOWN || eventType == AjaxViewer.KEY_UP) { @@ -237,6 +236,7 @@ KeyboardMapper.prototype = { return; } else if($.isArray(X11Keysym)) { for(var i = 0; i < X11Keysym.length; i++) { + // How to set the guestos, browser, version value??? add later if(this.isConditionalEntryMatched(eventType, code, modifiers, X11Keysym[i], guestos, browser, browserVersion)) { this.mappedInput.push(X11Keysym[i]); } @@ -442,8 +442,8 @@ function AjaxViewer(panelId, imageUrl, updateUrl, tileMap, width, height, tileWi window.onStatusNotify = function(status) {}; this.panel = this.generateCanvas(panelId, width, height, tileWidth, tileHeight); - - this.setupKeyboardTranslationTable(); +// this.setupKeyboardTranslationle(); + this.setupKeyboardTranslationTable(this.keyboardMappers); this.setupUIController(); } @@ -726,18 +726,20 @@ AjaxViewer.prototype = { }); this.checkEventQueue(); }, - +//NEW insert the keyboard tables file here +// ajaxKeys.js + setupKeyboardTranslationTable : function() { this.keyboardMappers = []; var mapper = new KeyboardMapper(); this.keyboardMappers[AjaxViewer.KEYBOARD_TYPE_ENGLISH] = mapper; mapper.setKeyboardType(KeyboardMapper.KEYBOARD_TYPE_COOKED); - + mapper = new KeyboardMapper(); this.keyboardMappers[AjaxViewer.KEYBOARD_TYPE_JAPANESE] = mapper; mapper.setKeyboardType(KeyboardMapper.KEYBOARD_TYPE_RAW); - + // JP keyboard plugged in a English host OS /* mapper.jsX11KeysymMap[AjaxViewer.JS_KEY_JP_COLON] = AjaxViewer.X11_KEY_COLON; @@ -759,8 +761,9 @@ AjaxViewer.prototype = { {type: AjaxViewer.KEY_DOWN, code: AjaxViewer.X11_KEY_TILDE, modifiers: 0, shift: true }, {type: AjaxViewer.KEY_UP, code: AjaxViewer.X11_KEY_TILDE, modifiers: 0, shift: true } ]; -*/ - +*/ + +/* Old // JP keyboard plugged in a Japanese host OS mapper.jsX11KeysymMap[222] = AjaxViewer.X11_KEY_CIRCUMFLEX_ACCENT; mapper.jsX11KeysymMap[220] = AjaxViewer.X11_KEY_YEN_MARK; @@ -789,7 +792,31 @@ AjaxViewer.prototype = { {type: AjaxViewer.KEY_DOWN, code: AjaxViewer.X11_KEY_ADD, modifiers: 0, shift: true }, {type: AjaxViewer.KEY_UP, code: AjaxViewer.X11_KEY_ADD, modifiers: 0, shift: true }, ]; - }, + +*/ + // create the mapping table based on the tables input + if (keyboardTables != undefined ) { + + for(var i = 0; i < keyboardTables.length; i++) { + var mappingTbl = keyboardTables[i]; + var mappings = mappingTbl.mappingTable; + var x11Maps = mappings.X11; + for (var j = 0; j < x11Maps.length; j++) { + var code = x11Maps[j].keycode; + var mappedEntry = x11Maps[j].entry; + mapper.jsX11KeysymMap[code] = mappedEntry; + } + var keyPressMaps = mappings.keyPress; + for (var j = 0; j < keyPressMaps.length; j++) { + var code = keyPressMaps[j].keycode; + var mappedEntry = keyPressMaps[j].entry; + mapper.jsKeyPressX11KeysymMap[code] = mappedEntry; + } + + } + } + + }, // end of the setupKeyboardTranslationTable function getCurrentKeyboardMapper : function() { return this.keyboardMappers[this.currentKeyboard]; diff --git a/console-proxy/pom.xml b/console-proxy/pom.xml index d3f983e7d80..929eb005808 100644 --- a/console-proxy/pom.xml +++ b/console-proxy/pom.xml @@ -42,30 +42,16 @@ ${cs.codec.version} - - org.apache.cloudstack - cloud-core - ${project.version} - org.apache.cloudstack cloud-agent ${project.version} - org.apache.cloudstack - cloud-api - ${project.version} - - - org.apache.cloudstack - cloud-utils - ${project.version} - - @@ -121,12 +107,6 @@ systemvm.zip - - ../patches/target/ - - cloud-scripts.tar.gz - - ../patches/systemvm/debian/config/root/.ssh @@ -138,6 +118,53 @@ + + maven-antrun-plugin + 1.7 + + + generate-resource + generate-resources + + run + + + + + + + + + + @@ -191,7 +218,7 @@ -o systemvm.iso systemvm.zip - cloud-scripts.tar.gz + cloud-scripts.tgz authorized_keys diff --git a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java index e4f47270e4e..289bdab2f8a 100644 --- a/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java +++ b/console-proxy/src/com/cloud/consoleproxy/ConsoleProxyClientBase.java @@ -302,6 +302,7 @@ public abstract class ConsoleProxyClientBase implements ConsoleProxyClient, Cons "", "", "", + "", "", "", "", diff --git a/console-proxy/systemvm-descriptor.xml b/console-proxy/systemvm-descriptor.xml index 44ce2ebe782..7efe7fdfcb0 100644 --- a/console-proxy/systemvm-descriptor.xml +++ b/console-proxy/systemvm-descriptor.xml @@ -56,6 +56,7 @@ log4j-cloud.xml consoleproxy.properties + agent.properties diff --git a/console-proxy/ui/viewer.ftl b/console-proxy/ui/viewer.ftl index d1b2b56d02d..62de193cf7b 100644 --- a/console-proxy/ui/viewer.ftl +++ b/console-proxy/ui/viewer.ftl @@ -20,6 +20,7 @@ under the License. + ${title} 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/agent/resource/virtualnetwork/VirtualRoutingResource.java b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java index 2bb1145f1dd..2dc7950b2b7 100755 --- a/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java +++ b/core/src/com/cloud/agent/resource/virtualnetwork/VirtualRoutingResource.java @@ -80,6 +80,7 @@ import com.cloud.utils.component.Manager; import com.cloud.utils.net.NetUtils; import com.cloud.utils.script.OutputInterpreter; import com.cloud.utils.script.Script; +import com.cloud.utils.ssh.SshHelper; /** * VirtualNetworkResource controls and configures virtual networking @@ -263,8 +264,35 @@ public class VirtualRoutingResource implements Manager { return new SetPortForwardingRulesAnswer(cmd, results, endResult); } + + protected Answer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + String[] results = new String[cmd.getRules().length]; + int i = 0; + boolean endResult = true; + + for (StaticNatRuleTO rule : cmd.getRules()) { + String args = rule.revoked() ? " -D" : " -A"; + args += " -l " + rule.getSrcIp(); + args += " -r " + rule.getDstIp(); + + String result = routerProxy("vpc_staticnat.sh", routerIp, args); + + if(result == null) { + results[i++] = null; + } else { + results[i++] = "Failed"; + endResult = false; + } + } + return new SetStaticNatRulesAnswer(cmd, results, endResult); + + } private Answer execute(SetStaticNatRulesCommand cmd) { + if ( cmd.getVpcId() != null ) { + return SetVPCStaticNatRules(cmd); + } String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String[] results = new String[cmd.getRules().length]; int i = 0; @@ -298,8 +326,77 @@ public class VirtualRoutingResource implements Manager { return new SetStaticNatRulesAnswer(cmd, results, endResult); } + protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); + + if (routerIp == null) { + return new Answer(cmd); + } + + LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); + String[] config = cfgtr.generateConfiguration(cmd); + String tmpCfgFileContents = ""; + for (int i = 0; i < config.length; i++) { + tmpCfgFileContents += config[i]; + tmpCfgFileContents += "\n"; + } + File permKey = new File("/root/.ssh/id_rsa.cloud"); + + try { + SshHelper.scpTo(routerIp, 3922, "root", permKey, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); + + String[][] rules = cfgtr.generateFwRules(cmd); + + String[] addRules = rules[LoadBalancerConfigurator.ADD]; + String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; + String[] statRules = rules[LoadBalancerConfigurator.STATS]; + + String ip = cmd.getNic().getIp(); + String args = " -i " + ip; + StringBuilder sb = new StringBuilder(); + if (addRules.length > 0) { + for (int i = 0; i < addRules.length; i++) { + sb.append(addRules[i]).append(','); + } + + args += " -a " + sb.toString(); + } + + sb = new StringBuilder(); + if (removeRules.length > 0) { + for (int i = 0; i < removeRules.length; i++) { + sb.append(removeRules[i]).append(','); + } + + args += " -d " + sb.toString(); + } + + sb = new StringBuilder(); + if (statRules.length > 0) { + for (int i = 0; i < statRules.length; i++) { + sb.append(statRules[i]).append(','); + } + + args += " -s " + sb.toString(); + } + + String result = routerProxy("vpc_loadbalancer.sh", routerIp, args); + + if (result != null) { + return new Answer(cmd, false, "LoadBalancerConfigCommand failed"); + } + return new Answer(cmd); + + } catch (Exception e) { + return new Answer(cmd, e); + } + } private Answer execute(LoadBalancerConfigCommand cmd) { + if ( cmd.getVpcId() != null ) { + return VPCLoadBalancerConfig(cmd); + } + String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); File tmpCfgFile = null; try { @@ -520,7 +617,7 @@ public class VirtualRoutingResource implements Manager { } final String result = routerProxy("checkbatchs2svpn.sh", routerIP, args); - if (result == null || result.isEmpty()) { + if (result != null) { return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); } return new CheckS2SVpnConnectionsAnswer(cmd, true, result); diff --git a/core/src/com/cloud/alert/AlertVO.java b/core/src/com/cloud/alert/AlertVO.java index 2399e7fd8ea..f6089d65043 100755 --- a/core/src/com/cloud/alert/AlertVO.java +++ b/core/src/com/cloud/alert/AlertVO.java @@ -28,12 +28,13 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="alert") -public class AlertVO implements Alert, Identity { +public class AlertVO implements Alert { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/async/AsyncJobVO.java b/core/src/com/cloud/async/AsyncJobVO.java index fc2cf5bccdf..ad482b03a9d 100644 --- a/core/src/com/cloud/async/AsyncJobVO.java +++ b/core/src/com/cloud/async/AsyncJobVO.java @@ -32,6 +32,7 @@ import javax.persistence.TemporalType; import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="async_job") @@ -119,30 +120,33 @@ public class AsyncJobVO implements AsyncJob { @Transient private boolean fromPreviousSession = false; - public AsyncJobVO() { - this.uuid = UUID.randomUUID().toString(); - } - public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo) { - this.userId = userId; - this.accountId = accountId; - this.cmd = cmd; - this.cmdInfo = cmdInfo; + public AsyncJobVO() { + this.uuid = UUID.randomUUID().toString(); + } + + public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo, Long instanceId, Type instanceType) { + this.userId = userId; + this.accountId = accountId; + this.cmd = cmd; + this.cmdInfo = cmdInfo; this.callbackType = CALLBACK_POLLING; this.uuid = UUID.randomUUID().toString(); + this.instanceId = instanceId; } - + public AsyncJobVO(long userId, long accountId, String cmd, String cmdInfo, - int callbackType, String callbackAddress) { - - this(userId, accountId, cmd, cmdInfo); - this.callbackType = callbackType; - this.callbackAddress = callbackAddress; + int callbackType, String callbackAddress, Long instanceId, Type instanceType) { + + this(userId, accountId, cmd, cmdInfo, instanceId, instanceType); + this.callbackType = callbackType; + this.callbackAddress = callbackAddress; this.uuid = UUID.randomUUID().toString(); } - + + @Override - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/async/SyncQueueItemVO.java b/core/src/com/cloud/async/SyncQueueItemVO.java index f70ff852b5b..b0546a72141 100644 --- a/core/src/com/cloud/async/SyncQueueItemVO.java +++ b/core/src/com/cloud/async/SyncQueueItemVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.async; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -24,24 +26,26 @@ import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; @Entity @Table(name="sync_queue_item") -public class SyncQueueItemVO implements SyncQueueItem{ +public class SyncQueueItemVO implements SyncQueueItem, InternalIdentity { - @Id + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Long id = null; - + @Column(name="queue_id") - private Long queueId; - + private Long queueId; + @Column(name="content_type") - private String contentType; - + private String contentType; + @Column(name="content_id") - private Long contentId; + private Long contentId; @Column(name="queue_proc_msid") private Long lastProcessMsid; @@ -49,76 +53,89 @@ public class SyncQueueItemVO implements SyncQueueItem{ @Column(name="queue_proc_number") private Long lastProcessNumber; - @Column(name="created") - private Date created; + @Column(name="queue_proc_time") + @Temporal(TemporalType.TIMESTAMP) + private Date lastProcessTime; - public Long getId() { - return id; - } + @Column(name="created") + private Date created; + + public long getId() { + return id; + } - public void setId(Long id) { - this.id = id; - } + public void setId(Long id) { + this.id = id; + } - public Long getQueueId() { - return queueId; - } + public Long getQueueId() { + return queueId; + } - public void setQueueId(Long queueId) { - this.queueId = queueId; - } + public void setQueueId(Long queueId) { + this.queueId = queueId; + } - @Override - public String getContentType() { - return contentType; - } + @Override + public String getContentType() { + return contentType; + } - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @Override - public Long getContentId() { - return contentId; - } + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @Override + public Long getContentId() { + return contentId; + } - public void setContentId(Long contentId) { - this.contentId = contentId; - } + public void setContentId(Long contentId) { + this.contentId = contentId; + } - public Long getLastProcessMsid() { - return lastProcessMsid; - } + public Long getLastProcessMsid() { + return lastProcessMsid; + } + + public void setLastProcessMsid(Long lastProcessMsid) { + this.lastProcessMsid = lastProcessMsid; + } - public void setLastProcessMsid(Long lastProcessMsid) { - this.lastProcessMsid = lastProcessMsid; - } - public Long getLastProcessNumber() { - return lastProcessNumber; - } + return lastProcessNumber; + } - public void setLastProcessNumber(Long lastProcessNumber) { - this.lastProcessNumber = lastProcessNumber; - } + public void setLastProcessNumber(Long lastProcessNumber) { + this.lastProcessNumber = lastProcessNumber; + } - public Date getCreated() { - return created; - } + public Date getCreated() { + return created; + } - public void setCreated(Date created) { - this.created = created; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("SyncQueueItemVO {id:").append(getId()).append(", queueId: ").append(getQueueId()); - sb.append(", contentType: ").append(getContentType()); - sb.append(", contentId: ").append(getContentId()); - sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); - sb.append(", lastprocessNumber: ").append(getLastProcessNumber()); - sb.append(", created: ").append(getCreated()); - sb.append("}"); - return sb.toString(); - } + public void setCreated(Date created) { + this.created = created; + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("SyncQueueItemVO {id:").append(getId()).append(", queueId: ").append(getQueueId()); + sb.append(", contentType: ").append(getContentType()); + sb.append(", contentId: ").append(getContentId()); + sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); + sb.append(", lastprocessNumber: ").append(getLastProcessNumber()); + sb.append(", lastProcessTime: ").append(getLastProcessTime()); + sb.append(", created: ").append(getCreated()); + sb.append("}"); + return sb.toString(); + } + + public Date getLastProcessTime() { + return lastProcessTime; + } + + public void setLastProcessTime(Date lastProcessTime) { + this.lastProcessTime = lastProcessTime; + } } diff --git a/core/src/com/cloud/async/SyncQueueVO.java b/core/src/com/cloud/async/SyncQueueVO.java index 741312f74dd..4f2bc4fdf5b 100644 --- a/core/src/com/cloud/async/SyncQueueVO.java +++ b/core/src/com/cloud/async/SyncQueueVO.java @@ -14,10 +14,12 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. + package com.cloud.async; -import java.util.Date; +import org.apache.cloudstack.api.InternalIdentity; +import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -29,111 +31,107 @@ import javax.persistence.TemporalType; @Entity @Table(name="sync_queue") -public class SyncQueueVO { - @Id +public class SyncQueueVO implements InternalIdentity { + + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private Long id; @Column(name="sync_objtype") - private String syncObjType; - + + private String syncObjType; + @Column(name="sync_objid") - private Long syncObjId; - + private Long syncObjId; + @Column(name="queue_proc_number") private Long lastProcessNumber; - - @Column(name="queue_proc_time") - @Temporal(TemporalType.TIMESTAMP) - private Date lastProcessTime; - - @Column(name="queue_proc_msid") - private Long lastProcessMsid; - + @Column(name="created") @Temporal(TemporalType.TIMESTAMP) - private Date created; - + private Date created; + @Column(name="last_updated") @Temporal(TemporalType.TIMESTAMP) - private Date lastUpdated; + private Date lastUpdated; + + @Column(name="queue_size") + private long queueSize = 0; + + @Column(name="queue_size_limit") + private long queueSizeLimit = 0; + + public long getId() { + return id; + } + + public String getSyncObjType() { + return syncObjType; + } + + public void setSyncObjType(String syncObjType) { + this.syncObjType = syncObjType; + } + + public Long getSyncObjId() { + return syncObjId; + } + + public void setSyncObjId(Long syncObjId) { + this.syncObjId = syncObjId; + } - public Long getId() { - return id; - } + public Long getLastProcessNumber() { + return lastProcessNumber; + } + + public void setLastProcessNumber(Long number) { + lastProcessNumber = number; + } - public void setId(Long id) { - this.id = id; - } + public Date getCreated() { + return created; + } - public String getSyncObjType() { - return syncObjType; - } + public void setCreated(Date created) { + this.created = created; + } - public void setSyncObjType(String syncObjType) { - this.syncObjType = syncObjType; - } + public Date getLastUpdated() { + return lastUpdated; + } - public Long getSyncObjId() { - return syncObjId; - } + public void setLastUpdated(Date lastUpdated) { + this.lastUpdated = lastUpdated; + } - public void setSyncObjId(Long syncObjId) { - this.syncObjId = syncObjId; - } - - public Long getLastProcessNumber() { - return lastProcessNumber; - } - - public void setLastProcessNumber(Long number) { - lastProcessNumber = number; - } + public String toString() { + StringBuffer sb = new StringBuffer(); + sb.append("SyncQueueVO {id:").append(getId()); + sb.append(", syncObjType: ").append(getSyncObjType()); + sb.append(", syncObjId: ").append(getSyncObjId()); + sb.append(", lastProcessNumber: ").append(getLastProcessNumber()); + sb.append(", lastUpdated: ").append(getLastUpdated()); + sb.append(", created: ").append(getCreated()); + sb.append(", count: ").append(getQueueSize()); + sb.append("}"); + return sb.toString(); + } - public Date getLastProcessTime() { - return lastProcessTime; - } + public long getQueueSize() { + return queueSize; + } - public void setLastProcessTime(Date lastProcessTime) { - this.lastProcessTime = lastProcessTime; - } + public void setQueueSize(long queueSize) { + this.queueSize = queueSize; + } - public Long getLastProcessMsid() { - return lastProcessMsid; - } + public long getQueueSizeLimit() { + return queueSizeLimit; + } - public void setLastProcessMsid(Long lastProcessMsid) { - this.lastProcessMsid = lastProcessMsid; - } - - public Date getCreated() { - return created; - } - - public void setCreated(Date created) { - this.created = created; - } - - public Date getLastUpdated() { - return lastUpdated; - } - - public void setLastUpdated(Date lastUpdated) { - this.lastUpdated = lastUpdated; - } - - public String toString() { - StringBuffer sb = new StringBuffer(); - sb.append("SyncQueueVO {id:").append(getId()); - sb.append(", syncObjType: ").append(getSyncObjType()); - sb.append(", syncObjId: ").append(getSyncObjId()); - sb.append(", lastProcessMsid: ").append(getLastProcessMsid()); - sb.append(", lastProcessNumber: ").append(getLastProcessNumber()); - sb.append(", lastProcessTime: ").append(getLastProcessTime()); - sb.append(", lastUpdated: ").append(getLastUpdated()); - sb.append(", created: ").append(getCreated()); - sb.append("}"); - return sb.toString(); - } + public void setQueueSizeLimit(long queueSizeLimit) { + this.queueSizeLimit = queueSizeLimit; + } } diff --git a/core/src/com/cloud/capacity/CapacityVO.java b/core/src/com/cloud/capacity/CapacityVO.java index 1bf06ce8205..d34e9d36840 100755 --- a/core/src/com/cloud/capacity/CapacityVO.java +++ b/core/src/com/cloud/capacity/CapacityVO.java @@ -29,6 +29,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="op_host_capacity") @@ -102,7 +103,7 @@ public class CapacityVO implements Capacity { public long getId() { return id; } - + @Override public Long getHostOrPoolId() { return hostOrPoolId; @@ -195,4 +196,9 @@ public class CapacityVO implements Capacity { public void setUsedPercentage(float usedPercentage) { this.usedPercentage = usedPercentage; } + + @Override + public String getUuid() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } } diff --git a/core/src/com/cloud/certificate/CertificateVO.java b/core/src/com/cloud/certificate/CertificateVO.java index 23c333146e7..4f0476092e4 100644 --- a/core/src/com/cloud/certificate/CertificateVO.java +++ b/core/src/com/cloud/certificate/CertificateVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.certificate; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="certificate") -public class CertificateVO { +public class CertificateVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -40,7 +42,7 @@ public class CertificateVO { public CertificateVO() {} - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/configuration/ResourceCountVO.java b/core/src/com/cloud/configuration/ResourceCountVO.java index 7cf601e272a..b87f55caa5e 100644 --- a/core/src/com/cloud/configuration/ResourceCountVO.java +++ b/core/src/com/cloud/configuration/ResourceCountVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.configuration; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -62,7 +64,7 @@ public class ResourceCountVO implements ResourceCount { } @Override - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/configuration/ResourceLimitVO.java b/core/src/com/cloud/configuration/ResourceLimitVO.java index ff5397e1950..c131495a74f 100644 --- a/core/src/com/cloud/configuration/ResourceLimitVO.java +++ b/core/src/com/cloud/configuration/ResourceLimitVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.configuration; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -62,7 +64,7 @@ public class ResourceLimitVO implements ResourceLimit { } @Override - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/event/EventVO.java b/core/src/com/cloud/event/EventVO.java index 79787888eba..ac46f24b2ee 100644 --- a/core/src/com/cloud/event/EventVO.java +++ b/core/src/com/cloud/event/EventVO.java @@ -29,12 +29,13 @@ import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="event") -public class EventVO implements Event, Identity { +public class EventVO implements Event { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/event/UsageEvent.java b/core/src/com/cloud/event/UsageEvent.java index bf56f5e3fa9..0d4ef177405 100644 --- a/core/src/com/cloud/event/UsageEvent.java +++ b/core/src/com/cloud/event/UsageEvent.java @@ -16,10 +16,11 @@ // under the License. package com.cloud.event; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface UsageEvent { - long getId(); +public interface UsageEvent extends InternalIdentity { String getType(); Date getCreateDate(); diff --git a/core/src/com/cloud/event/UsageEventVO.java b/core/src/com/cloud/event/UsageEventVO.java index 201892facef..c92972b6072 100644 --- a/core/src/com/cloud/event/UsageEventVO.java +++ b/core/src/com/cloud/event/UsageEventVO.java @@ -26,6 +26,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="usage_event") diff --git a/core/src/com/cloud/host/DetailVO.java b/core/src/com/cloud/host/DetailVO.java index d7ee8142c5a..4e624905a47 100644 --- a/core/src/com/cloud/host/DetailVO.java +++ b/core/src/com/cloud/host/DetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.host; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="host_details") -public class DetailVO { +public class DetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/host/HostTagVO.java b/core/src/com/cloud/host/HostTagVO.java index 7164d10df0c..b1f5ace99c0 100644 --- a/core/src/com/cloud/host/HostTagVO.java +++ b/core/src/com/cloud/host/HostTagVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.host; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="host_tags") -public class HostTagVO { +public class HostTagVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/host/HostVO.java b/core/src/com/cloud/host/HostVO.java index dab9768a943..c814b94a426 100755 --- a/core/src/com/cloud/host/HostVO.java +++ b/core/src/com/cloud/host/HostVO.java @@ -37,18 +37,19 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.resource.ResourceState; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="host") @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class HostVO implements Host, Identity { +public class HostVO implements Host { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -128,20 +129,20 @@ public class HostVO implements Host, Identity { @Column(name="setup") private boolean setup = false; - + @Column(name="resource_state", nullable=false) @Enumerated(value=EnumType.STRING) private ResourceState resourceState; @Column(name="hypervisor_version") private String hypervisorVersion; - + @Column(name="update_count", updatable = true, nullable=false) protected long updated; // This field should be updated everytime the state is updated. There's no set method in the vo object because it is done with in the dao code. @Column(name="uuid") private String uuid; - + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call host dao to load it. @@ -695,36 +696,36 @@ public class HostVO implements Host, Identity { public Status getState() { return status; } - + @Override public ResourceState getResourceState() { return resourceState; } - + public void setResourceState(ResourceState state) { resourceState = state; } - + @Override public boolean isInMaintenanceStates() { return (getResourceState() == ResourceState.Maintenance || getResourceState() == ResourceState.ErrorInMaintenance || getResourceState() == ResourceState.PrepareForMaintenance); } - + public long getUpdated() { return updated; } - + public long incrUpdated() { updated++; return updated; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java b/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java index 75eebeb0dbc..56e8e0a734d 100644 --- a/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java +++ b/core/src/com/cloud/hypervisor/HypervisorCapabilitiesVO.java @@ -27,13 +27,14 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.NumbersUtil; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="hypervisor_capabilities") -public class HypervisorCapabilitiesVO implements HypervisorCapabilities, Identity { +public class HypervisorCapabilitiesVO implements HypervisorCapabilities { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/network/VpnUserVO.java b/core/src/com/cloud/network/VpnUserVO.java index f376e704187..5a8e531893e 100644 --- a/core/src/com/cloud/network/VpnUserVO.java +++ b/core/src/com/cloud/network/VpnUserVO.java @@ -27,12 +27,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("vpn_users")) -public class VpnUserVO implements VpnUser, Identity { +public class VpnUserVO implements VpnUser { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") 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/network/security/SecurityGroupRuleVO.java b/core/src/com/cloud/network/security/SecurityGroupRuleVO.java index 7d38af853db..f01b50fd250 100644 --- a/core/src/com/cloud/network/security/SecurityGroupRuleVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupRuleVO.java @@ -27,9 +27,9 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; import com.cloud.async.AsyncInstanceCreateStatus; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("security_group_rule")) diff --git a/core/src/com/cloud/network/security/SecurityGroupRulesVO.java b/core/src/com/cloud/network/security/SecurityGroupRulesVO.java index d322a79d304..82060efce12 100644 --- a/core/src/com/cloud/network/security/SecurityGroupRulesVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupRulesVO.java @@ -27,6 +27,7 @@ import javax.persistence.Table; import com.cloud.network.security.SecurityRule.SecurityRuleType; import com.cloud.utils.db.JoinType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("security_group")) diff --git a/core/src/com/cloud/network/security/SecurityGroupVMMapVO.java b/core/src/com/cloud/network/security/SecurityGroupVMMapVO.java index e3dd28108c8..75bde3321ce 100644 --- a/core/src/com/cloud/network/security/SecurityGroupVMMapVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupVMMapVO.java @@ -27,13 +27,14 @@ import javax.persistence.SecondaryTables; import javax.persistence.Table; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("security_group_vm_map")) @SecondaryTables({ @SecondaryTable(name = "nics", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "instance_id", referencedColumnName = "instance_id") }), @SecondaryTable(name = "vm_instance", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "instance_id", referencedColumnName = "id") }), @SecondaryTable(name = "security_group", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "security_group_id", referencedColumnName = "id") }) }) -public class SecurityGroupVMMapVO { +public class SecurityGroupVMMapVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -62,7 +63,7 @@ public class SecurityGroupVMMapVO { this.instanceId = instanceId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/network/security/SecurityGroupVO.java b/core/src/com/cloud/network/security/SecurityGroupVO.java index b059e8c67f1..be7c593f744 100644 --- a/core/src/com/cloud/network/security/SecurityGroupVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupVO.java @@ -25,11 +25,12 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("security_group")) -public class SecurityGroupVO implements SecurityGroup, Identity { +public class SecurityGroupVO implements SecurityGroup { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/core/src/com/cloud/network/security/SecurityGroupWork.java b/core/src/com/cloud/network/security/SecurityGroupWork.java index a7f89561174..e50f3eb425c 100644 --- a/core/src/com/cloud/network/security/SecurityGroupWork.java +++ b/core/src/com/cloud/network/security/SecurityGroupWork.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.security; +import org.apache.cloudstack.api.InternalIdentity; + /** * Work related to security groups for a vm * diff --git a/core/src/com/cloud/network/security/SecurityGroupWorkVO.java b/core/src/com/cloud/network/security/SecurityGroupWorkVO.java index b0c8ef3a463..33d30fb1d59 100644 --- a/core/src/com/cloud/network/security/SecurityGroupWorkVO.java +++ b/core/src/com/cloud/network/security/SecurityGroupWorkVO.java @@ -30,10 +30,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="op_nwgrp_work") -public class SecurityGroupWorkVO implements SecurityGroupWork{ +public class SecurityGroupWorkVO implements SecurityGroupWork, InternalIdentity { @Id @@ -67,7 +68,7 @@ public class SecurityGroupWorkVO implements SecurityGroupWork{ protected SecurityGroupWorkVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/network/security/VmRulesetLogVO.java b/core/src/com/cloud/network/security/VmRulesetLogVO.java index 709a3c97cd9..2090ce359e4 100644 --- a/core/src/com/cloud/network/security/VmRulesetLogVO.java +++ b/core/src/com/cloud/network/security/VmRulesetLogVO.java @@ -26,6 +26,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * Records the intent to update a VM's ingress ruleset @@ -33,7 +34,7 @@ import com.cloud.utils.db.GenericDao; */ @Entity @Table(name="op_vm_ruleset_log") -public class VmRulesetLogVO { +public class VmRulesetLogVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -57,7 +58,7 @@ public class VmRulesetLogVO { this.instanceId = instanceId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/DiskOfferingVO.java b/core/src/com/cloud/storage/DiskOfferingVO.java index 02198407ba6..5f4f18bcd34 100755 --- a/core/src/com/cloud/storage/DiskOfferingVO.java +++ b/core/src/com/cloud/storage/DiskOfferingVO.java @@ -34,20 +34,21 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.offering.DiskOffering; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="disk_offering") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class DiskOfferingVO implements DiskOffering, Identity { +public class DiskOfferingVO implements DiskOffering { public enum Type { Disk, Service }; - + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -58,7 +59,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { @Column(name="unique_name") private String uniqueName; - + @Column(name="name") private String name = null; @@ -70,39 +71,39 @@ public class DiskOfferingVO implements DiskOffering, Identity { @Column(name="tags", length=4096) String tags; - + @Column(name="type") Type type; - + @Column(name=GenericDao.REMOVED) @Temporal(TemporalType.TIMESTAMP) private Date removed; @Column(name=GenericDao.CREATED_COLUMN) private Date created; - + @Column(name="recreatable") private boolean recreatable; - + @Column(name="use_local_storage") private boolean useLocalStorage; - + @Column(name="system_use") private boolean systemUse; - + @Column(name="customized") private boolean customized; @Column(name="uuid") private String uuid; - + @Column(name="sort_key") int sortKey; public DiskOfferingVO() { this.uuid = UUID.randomUUID().toString(); } - + public DiskOfferingVO(Long domainId, String name, String displayText, long diskSize, String tags, boolean isCustomized) { this.domainId = domainId; this.name = name; @@ -115,7 +116,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { this.customized = isCustomized; this.uuid = UUID.randomUUID().toString(); } - + public DiskOfferingVO(String name, String displayText, boolean mirrored, String tags, boolean recreatable, boolean useLocalStorage, boolean systemUse, boolean customized) { this.domainId = null; this.type = Type.Service; @@ -147,7 +148,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { public long getId() { return id; } - + @Override public boolean isCustomized() { return customized; @@ -161,25 +162,25 @@ public class DiskOfferingVO implements DiskOffering, Identity { public String getUniqueName() { return uniqueName; } - + @Override public boolean getUseLocalStorage() { return useLocalStorage; } - + @Override public Long getDomainId() { return domainId; } - + public Type getType() { return type; } - + public boolean isRecreatable() { return recreatable; } - + public void setDomainId(Long domainId) { this.domainId = domainId; } @@ -188,17 +189,17 @@ public class DiskOfferingVO implements DiskOffering, Identity { public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + @Override public boolean getSystemUse() { return systemUse; } - + public void setSystemUse(boolean systemUse) { this.systemUse = systemUse; } @@ -215,7 +216,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { public long getDiskSize(){ return diskSize; } - + @Override public void setDiskSize(long diskSize) { this.diskSize = diskSize; @@ -224,21 +225,21 @@ public class DiskOfferingVO implements DiskOffering, Identity { public Date getRemoved() { return removed; } - + @Override public Date getCreated() { return created; } - + protected void setTags(String tags) { this.tags = tags; } - + @Override public String getTags() { return tags; } - + public void setUniqueName(String name) { this.uniqueName = name; } @@ -250,7 +251,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { if (tags == null || tags.isEmpty()) { return new String[0]; } - + return tags.split(","); } @@ -259,30 +260,30 @@ public class DiskOfferingVO implements DiskOffering, Identity { if (this.tags == null) { return false; } - + for (String tag : tags) { if (!this.tags.matches(tag)) { return false; } } - + return true; } - + @Transient public void setTagsArray(List newTags) { if (newTags.isEmpty()) { setTags(null); return; } - + StringBuilder buf = new StringBuilder(); for (String tag : newTags) { buf.append(tag).append(","); } - + buf.delete(buf.length() - 1, buf.length()); - + setTags(buf.toString()); } @@ -293,12 +294,12 @@ public class DiskOfferingVO implements DiskOffering, Identity { public void setRemoved(Date removed) { this.removed = removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -306,7 +307,7 @@ public class DiskOfferingVO implements DiskOffering, Identity { public void setSortKey(int key) { sortKey = key; } - + public int getSortKey() { return sortKey; } diff --git a/core/src/com/cloud/storage/GuestOSCategoryVO.java b/core/src/com/cloud/storage/GuestOSCategoryVO.java index cbe242eef5d..03a74793001 100644 --- a/core/src/com/cloud/storage/GuestOSCategoryVO.java +++ b/core/src/com/cloud/storage/GuestOSCategoryVO.java @@ -25,32 +25,33 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="guest_os_category") -public class GuestOSCategoryVO implements GuestOsCategory, Identity { +public class GuestOSCategoryVO implements GuestOsCategory { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="name") String name; - + @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Override public long getId() { return id; } - + @Override public String getName() { - return name; + return name; } - + @Override public void setName(String name) { this.name = name; @@ -60,7 +61,7 @@ public class GuestOSCategoryVO implements GuestOsCategory, Identity { public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/GuestOSVO.java b/core/src/com/cloud/storage/GuestOSVO.java index 85db94e29f6..49e136d03c1 100644 --- a/core/src/com/cloud/storage/GuestOSVO.java +++ b/core/src/com/cloud/storage/GuestOSVO.java @@ -25,64 +25,65 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="guest_os") -public class GuestOSVO implements GuestOS, Identity { +public class GuestOSVO implements GuestOS { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="category_id") private long categoryId; - + @Column(name="name") String name; - + @Column(name="display_name") String displayName; - + @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Override public long getId() { return id; } - + public long getCategoryId() { return categoryId; } - + public void setCategoryId(long categoryId) { this.categoryId = categoryId; } - + @Override public String getName() { - return name; + return name; } - + public void setName(String name) { this.name = name; } - + @Override public String getDisplayName() { return displayName; } - + public void setDisplayName(String displayName) { this.displayName = displayName; } - + @Override public String getUuid() { - return this.uuid; + return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/LaunchPermissionVO.java b/core/src/com/cloud/storage/LaunchPermissionVO.java index 8bfe09d3719..992bac2365e 100644 --- a/core/src/com/cloud/storage/LaunchPermissionVO.java +++ b/core/src/com/cloud/storage/LaunchPermissionVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -23,7 +25,7 @@ import javax.persistence.Table; @Entity @Table(name="launch_permission") -public class LaunchPermissionVO { +public class LaunchPermissionVO implements InternalIdentity { @Id @Column(name="id") private Long id; @@ -41,7 +43,7 @@ public class LaunchPermissionVO { this.accountId = accountId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/S3VO.java b/core/src/com/cloud/storage/S3VO.java new file mode 100644 index 00000000000..ec49bc92d74 --- /dev/null +++ b/core/src/com/cloud/storage/S3VO.java @@ -0,0 +1,209 @@ +/* + * 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 org.apache.cloudstack.api.InternalIdentity; + +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 { + + 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/SnapshotPolicyVO.java b/core/src/com/cloud/storage/SnapshotPolicyVO.java index d059fcbc6da..4eb4916afd3 100644 --- a/core/src/com/cloud/storage/SnapshotPolicyVO.java +++ b/core/src/com/cloud/storage/SnapshotPolicyVO.java @@ -25,19 +25,20 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.utils.DateUtil.IntervalType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshot_policy") -public class SnapshotPolicyVO implements SnapshotPolicy, Identity { - +public class SnapshotPolicyVO implements SnapshotPolicy { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="volume_id") long volumeId; @@ -46,20 +47,20 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { @Column(name="timezone") String timezone; - + @Column(name="interval") private short interval; - + @Column(name="max_snaps") private int maxSnaps; - + @Column(name="active") boolean active = false; @Column(name="uuid") String uuid; - - public SnapshotPolicyVO() { + + public SnapshotPolicyVO() { this.uuid = UUID.randomUUID().toString(); } @@ -76,7 +77,7 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public long getId() { return id; } - + public long getVolumeId() { return volumeId; } @@ -88,7 +89,7 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public String getSchedule() { return schedule; } - + public void setInterval(short interval) { this.interval = interval; } @@ -96,11 +97,11 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public void setTimezone(String timezone) { this.timezone = timezone; } - + public String getTimezone() { return timezone; } - + public short getInterval() { return interval; } @@ -120,12 +121,12 @@ public class SnapshotPolicyVO implements SnapshotPolicy, Identity { public void setActive(boolean active) { this.active = active; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/SnapshotScheduleVO.java b/core/src/com/cloud/storage/SnapshotScheduleVO.java index 80216e48a55..75757c6b22b 100644 --- a/core/src/com/cloud/storage/SnapshotScheduleVO.java +++ b/core/src/com/cloud/storage/SnapshotScheduleVO.java @@ -28,18 +28,19 @@ import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.snapshot.SnapshotSchedule; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshot_schedule") -public class SnapshotScheduleVO implements SnapshotSchedule, Identity { +public class SnapshotScheduleVO implements SnapshotSchedule { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + // DB constraint: For a given volume and policyId, there will only be one entry in this table. @Column(name="volume_id") long volumeId; @@ -50,16 +51,16 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { @Column(name="scheduled_timestamp") @Temporal(value=TemporalType.TIMESTAMP) Date scheduledTimestamp; - + @Column(name="async_job_id") Long asyncJobId; - + @Column(name="snapshot_id") Long snapshotId; @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + public SnapshotScheduleVO() { } public SnapshotScheduleVO(long volumeId, long policyId, Date scheduledTimestamp) { @@ -69,15 +70,15 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { this.snapshotId = null; this.asyncJobId = null; } - + public long getId() { return id; } - + public Long getVolumeId() { return volumeId; } - + public Long getPolicyId() { return policyId; } @@ -92,7 +93,7 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { public Date getScheduledTimestamp() { return scheduledTimestamp; } - + public void setScheduledTimestamp(Date scheduledTimestamp) { this.scheduledTimestamp = scheduledTimestamp; } @@ -100,24 +101,24 @@ public class SnapshotScheduleVO implements SnapshotSchedule, Identity { public Long getAsyncJobId() { return asyncJobId; } - + public void setAsyncJobId(Long asyncJobId) { this.asyncJobId = asyncJobId; } - + public Long getSnapshotId() { return snapshotId; } - + public void setSnapshotId(Long snapshotId) { this.snapshotId = snapshotId; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/SnapshotVO.java b/core/src/com/cloud/storage/SnapshotVO.java index 75f965745d1..8ed6a5a5ce4 100644 --- a/core/src/com/cloud/storage/SnapshotVO.java +++ b/core/src/com/cloud/storage/SnapshotVO.java @@ -28,14 +28,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.utils.db.GenericDao; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="snapshots") -public class SnapshotVO implements Snapshot, Identity { +public class SnapshotVO implements Snapshot { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -91,6 +92,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; @@ -291,4 +295,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/StoragePoolDetailVO.java b/core/src/com/cloud/storage/StoragePoolDetailVO.java index 2e1af7b6dab..48487e566ac 100644 --- a/core/src/com/cloud/storage/StoragePoolDetailVO.java +++ b/core/src/com/cloud/storage/StoragePoolDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="storage_pool_details") -public class StoragePoolDetailVO { +public class StoragePoolDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/storage/StoragePoolHostAssoc.java b/core/src/com/cloud/storage/StoragePoolHostAssoc.java index 3e0d8daa149..34326d963a6 100644 --- a/core/src/com/cloud/storage/StoragePoolHostAssoc.java +++ b/core/src/com/cloud/storage/StoragePoolHostAssoc.java @@ -16,9 +16,11 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface StoragePoolHostAssoc { +public interface StoragePoolHostAssoc extends InternalIdentity { long getHostId(); diff --git a/core/src/com/cloud/storage/StoragePoolHostVO.java b/core/src/com/cloud/storage/StoragePoolHostVO.java index 41c7ce853e6..a8a2bac4886 100644 --- a/core/src/com/cloud/storage/StoragePoolHostVO.java +++ b/core/src/com/cloud/storage/StoragePoolHostVO.java @@ -28,6 +28,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage pools and hosts @@ -75,7 +76,7 @@ public class StoragePoolHostVO implements StoragePoolHostAssoc { } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/StoragePoolVO.java b/core/src/com/cloud/storage/StoragePoolVO.java index f6bb210871b..b76d74246c7 100644 --- a/core/src/com/cloud/storage/StoragePoolVO.java +++ b/core/src/com/cloud/storage/StoragePoolVO.java @@ -30,13 +30,14 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="storage_pool") -public class StoragePoolVO implements StoragePool, Identity { +public class StoragePoolVO implements StoragePool { @Id @TableGenerator(name="storage_pool_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="storage_pool_seq", allocationSize=1) @Column(name="id", updatable=false, nullable = false) diff --git a/core/src/com/cloud/storage/StoragePoolWorkVO.java b/core/src/com/cloud/storage/StoragePoolWorkVO.java index c5101eabb85..440065da66b 100644 --- a/core/src/com/cloud/storage/StoragePoolWorkVO.java +++ b/core/src/com/cloud/storage/StoragePoolWorkVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; @@ -26,9 +28,9 @@ import javax.persistence.Table; @Entity @Table(name="storage_pool_work") -public class StoragePoolWorkVO { +public class StoragePoolWorkVO implements InternalIdentity { - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/SwiftVO.java b/core/src/com/cloud/storage/SwiftVO.java index 7e07629e72b..c99f0efc702 100644 --- a/core/src/com/cloud/storage/SwiftVO.java +++ b/core/src/com/cloud/storage/SwiftVO.java @@ -27,24 +27,25 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="swift") -public class SwiftVO implements Swift, Identity { - +public class SwiftVO implements Swift, InternalIdentity { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="url") String url; @Column(name="account") String account; - + @Column(name="username") String userName; @@ -53,10 +54,10 @@ public class SwiftVO implements Swift, Identity { @Column(name="uuid") String uuid = UUID.randomUUID().toString(); - + @Column(name = GenericDao.CREATED_COLUMN) private Date created; - + public SwiftVO() { } public SwiftVO(String url, String account, String userName, String key) { @@ -95,12 +96,12 @@ public class SwiftVO implements Swift, Identity { public SwiftTO toSwiftTO() { return new SwiftTO(getId(), getUrl(), getAccount(), getUserName(), getKey()); } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/storage/UploadVO.java b/core/src/com/cloud/storage/UploadVO.java index b39553e8638..d761bf17e3b 100755 --- a/core/src/com/cloud/storage/UploadVO.java +++ b/core/src/com/cloud/storage/UploadVO.java @@ -17,6 +17,7 @@ package com.cloud.storage; import java.util.Date; +import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; @@ -31,6 +32,7 @@ import javax.persistence.TemporalType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="upload") @@ -38,47 +40,50 @@ public class UploadVO implements Upload { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; - + + @Column(name="uuid") + private String uuid; + @Column(name="host_id") private long hostId; - + @Column(name="type_id") private long typeId; - + @Column(name=GenericDaoBase.CREATED_COLUMN) private Date created = null; - + @Column(name="last_updated") @Temporal(value=TemporalType.TIMESTAMP) - private Date lastUpdated = null; - + private Date lastUpdated = null; + @Column (name="upload_pct") - private int uploadPercent; - + private int uploadPercent; + @Column (name="type") @Enumerated(EnumType.STRING) private Type type; - + @Column (name="mode") @Enumerated(EnumType.STRING) private Mode mode = Mode.FTP_UPLOAD; - + @Column (name="upload_state") @Enumerated(EnumType.STRING) private Status uploadState; - + @Column (name="error_str") private String errorString; @Column (name="job_id") private String jobId; - + @Column (name="url") private String uploadUrl; @Column (name="install_path") private String installPath; - + @Override public long getHostId() { return hostId; @@ -93,7 +98,12 @@ public class UploadVO implements Upload { return id; } - @Override + + public String getUuid() { + return uuid; + } + + @Override public Date getCreated() { return created; } @@ -102,7 +112,7 @@ public class UploadVO implements Upload { public Date getLastUpdated() { return lastUpdated; } - + public void setLastUpdated(Date date) { lastUpdated = date; } @@ -111,6 +121,7 @@ public class UploadVO implements Upload { super(); this.hostId = hostId; this.typeId = templateId; + this.uuid = UUID.randomUUID().toString(); } public UploadVO(long hostId, long typeId, Date lastUpdated, @@ -124,8 +135,9 @@ public class UploadVO implements Upload { this.mode = mode; this.type = type; this.uploadUrl = uploadUrl; + this.uuid = UUID.randomUUID().toString(); } - + public UploadVO(long hostId, long typeId, Date lastUpdated, Status uploadState, int uploadPercent, Type type, Mode mode) { @@ -137,9 +149,11 @@ public class UploadVO implements Upload { this.uploadPercent = uploadPercent; this.type = type; this.mode = mode; + this.uuid = UUID.randomUUID().toString(); + } - protected UploadVO() { + protected UploadVO() { } public UploadVO(Long uploadId) { @@ -219,7 +233,7 @@ public class UploadVO implements Upload { return mode; } - public void setMode(Mode mode) { + public void setMode(Mode mode) { this.mode = mode; } diff --git a/core/src/com/cloud/storage/VMTemplateDetailVO.java b/core/src/com/cloud/storage/VMTemplateDetailVO.java index e3f7487460f..c007802db3f 100644 --- a/core/src/com/cloud/storage/VMTemplateDetailVO.java +++ b/core/src/com/cloud/storage/VMTemplateDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.storage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="vm_template_details") -public class VMTemplateDetailVO { +public class VMTemplateDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/storage/VMTemplateHostVO.java b/core/src/com/cloud/storage/VMTemplateHostVO.java index 9c85dd2cc6c..9eae1a00303 100755 --- a/core/src/com/cloud/storage/VMTemplateHostVO.java +++ b/core/src/com/cloud/storage/VMTemplateHostVO.java @@ -30,6 +30,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage hosts and templates diff --git a/core/src/com/cloud/storage/VMTemplateS3VO.java b/core/src/com/cloud/storage/VMTemplateS3VO.java new file mode 100644 index 00000000000..02f3ff5cf7f --- /dev/null +++ b/core/src/com/cloud/storage/VMTemplateS3VO.java @@ -0,0 +1,204 @@ +/* + * 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 org.apache.cloudstack.api.InternalIdentity; + +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 implements InternalIdentity { + + 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/VMTemplateStoragePoolVO.java b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java index f497c099f2b..32c9dd2ece5 100644 --- a/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java +++ b/core/src/com/cloud/storage/VMTemplateStoragePoolVO.java @@ -30,6 +30,7 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage pools and templates @@ -37,7 +38,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name="template_spool_ref") -public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc{ +public class VMTemplateStoragePoolVO implements VMTemplateStorageResourceAssoc { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; diff --git a/core/src/com/cloud/storage/VMTemplateSwiftVO.java b/core/src/com/cloud/storage/VMTemplateSwiftVO.java index a009e237943..6c7a73d3c05 100755 --- a/core/src/com/cloud/storage/VMTemplateSwiftVO.java +++ b/core/src/com/cloud/storage/VMTemplateSwiftVO.java @@ -26,6 +26,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for swift and templates @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name = "template_swift_ref") -public class VMTemplateSwiftVO { +public class VMTemplateSwiftVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id; diff --git a/core/src/com/cloud/storage/VMTemplateVO.java b/core/src/com/cloud/storage/VMTemplateVO.java index cd17bc9bf5a..fcfdd0067e1 100755 --- a/core/src/com/cloud/storage/VMTemplateVO.java +++ b/core/src/com/cloud/storage/VMTemplateVO.java @@ -31,16 +31,17 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.Storage.TemplateType; import com.cloud.template.VirtualMachineTemplate; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vm_template") -public class VMTemplateVO implements VirtualMachineTemplate, Identity { +public class VMTemplateVO implements VirtualMachineTemplate { @Id @TableGenerator(name="vm_template_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="vm_template_seq", allocationSize=1) @Column(name="id", nullable = false) @@ -85,7 +86,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { private long accountId; @Column(name="checksum") - private String checksum; + private String checksum; @Column(name="display_text", length=4096) private String displayText; @@ -117,16 +118,16 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { @Column(name="template_tag") private String templateTag; - + @Column(name="uuid") private String uuid; - + @Column(name="sort_key") private int sortKey; - + @Column(name="enable_sshkey") private boolean enableSshKey; - + @Transient Map details; @@ -156,7 +157,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { this.templateTag = templateTag; this.uuid = UUID.randomUUID().toString(); this.enableSshKey = sshKeyEnabled; - } + } public VMTemplateVO(Long id, String uniqueName, String name, ImageFormat format, boolean isPublic, boolean featured, TemplateType type, String url, Date created, boolean requiresHvm, int bits, long accountId, String cksum, String displayText, boolean enablePassword, long guestOSId, boolean bootable, HypervisorType hyperType) { this.id = id; @@ -391,30 +392,30 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { @Override public String getTemplateTag() { return templateTag; - } + } public void setTemplateTag(String templateTag) { this.templateTag = templateTag; - } + } @Override public long getDomainId() { return -1; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } - + public Map getDetails() { return this.details; } - + public void setDetails(Map details) { this.details = details; } @@ -429,7 +430,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { } VMTemplateVO other = (VMTemplateVO)that; - return ((this.getUniqueName().equals(other.getUniqueName()))); + return ((this.getUniqueName().equals(other.getUniqueName()))); } @Override @@ -450,11 +451,11 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public void setRemoved(Date removed) { this.removed = removed; } - + public void setSortKey(int key) { sortKey = key; } - + public int getSortKey() { return sortKey; } @@ -463,7 +464,7 @@ public class VMTemplateVO implements VirtualMachineTemplate, Identity { public boolean getEnableSshKey() { return enableSshKey; } - + public void setEnableSshKey(boolean enable) { enableSshKey = enable; } diff --git a/core/src/com/cloud/storage/VMTemplateZoneVO.java b/core/src/com/cloud/storage/VMTemplateZoneVO.java index e7169b8cdae..93a67b565d4 100644 --- a/core/src/com/cloud/storage/VMTemplateZoneVO.java +++ b/core/src/com/cloud/storage/VMTemplateZoneVO.java @@ -29,10 +29,11 @@ import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="template_zone_ref") -public class VMTemplateZoneVO { +public class VMTemplateZoneVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id; @@ -64,7 +65,7 @@ public class VMTemplateZoneVO { this.lastUpdated = lastUpdated; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/storage/VolumeHostVO.java b/core/src/com/cloud/storage/VolumeHostVO.java index d3d88ae27a8..f4fc7abc4ee 100755 --- a/core/src/com/cloud/storage/VolumeHostVO.java +++ b/core/src/com/cloud/storage/VolumeHostVO.java @@ -33,6 +33,7 @@ import javax.persistence.TemporalType; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; import com.cloud.utils.db.GenericDaoBase; +import org.apache.cloudstack.api.InternalIdentity; /** * Join table for storage hosts and volumes @@ -40,7 +41,7 @@ import com.cloud.utils.db.GenericDaoBase; */ @Entity @Table(name="volume_host_ref") -public class VolumeHostVO { +public class VolumeHostVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) Long id; diff --git a/core/src/com/cloud/storage/VolumeVO.java b/core/src/com/cloud/storage/VolumeVO.java index 5765953f59a..907fb03552b 100755 --- a/core/src/com/cloud/storage/VolumeVO.java +++ b/core/src/com/cloud/storage/VolumeVO.java @@ -31,14 +31,15 @@ import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "volumes") -public class VolumeVO implements Volume, Identity { +public class VolumeVO implements Volume { @Id @TableGenerator(name = "volume_sq", table = "sequence", pkColumnName = "name", valueColumnName = "value", pkColumnValue = "volume_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE) diff --git a/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java b/core/src/com/cloud/storage/resource/NfsSecondaryStorageResource.java index 155210df499..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,8 +91,8 @@ 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.api.commands.DeleteVolumeCmd; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host; import com.cloud.host.Host.Type; @@ -90,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; @@ -97,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; @@ -168,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 { @@ -185,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(); @@ -256,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(); @@ -279,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"); @@ -451,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(); @@ -622,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(); @@ -629,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/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java b/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java index f5f810a9be1..6f3d2ce5468 100644 --- a/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java +++ b/core/src/com/cloud/storage/snapshot/SnapshotSchedule.java @@ -16,13 +16,15 @@ // under the License. package com.cloud.storage.snapshot; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; -public interface SnapshotSchedule { - long getId(); - +public interface SnapshotSchedule extends InternalIdentity, Identity { + Long getVolumeId(); - + Long getPolicyId(); void setPolicyId(long policyId); @@ -31,14 +33,14 @@ public interface SnapshotSchedule { * @return the scheduledTimestamp */ Date getScheduledTimestamp(); - + void setScheduledTimestamp(Date scheduledTimestamp); Long getAsyncJobId(); - + void setAsyncJobId(Long asyncJobId); - + Long getSnapshotId(); - + void setSnapshotId(Long snapshotId); } diff --git a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java index bd607b3dc76..628ad64c0dc 100644 --- a/core/src/com/cloud/storage/template/HttpTemplateDownloader.java +++ b/core/src/com/cloud/storage/template/HttpTemplateDownloader.java @@ -37,6 +37,7 @@ import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.HttpMethodRetryHandler; import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.NoHttpResponseException; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; @@ -56,6 +57,7 @@ import com.cloud.utils.Pair; */ public class HttpTemplateDownloader implements TemplateDownloader { public static final Logger s_logger = Logger.getLogger(HttpTemplateDownloader.class.getName()); + private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private static final int CHUNK_SIZE = 1024*1024; //1M private String downloadUrl; @@ -88,7 +90,7 @@ public class HttpTemplateDownloader implements TemplateDownloader { this.MAX_TEMPLATE_SIZE_IN_BYTES = maxTemplateSizeInBytes; this.totalBytes = 0; - this.client = new HttpClient(); + this.client = new HttpClient(s_httpClientManager); myretryhandler = new HttpMethodRetryHandler() { public boolean retryMethod( diff --git a/core/src/com/cloud/user/AccountVO.java b/core/src/com/cloud/user/AccountVO.java index b0418de5867..922c8b99eb5 100644 --- a/core/src/com/cloud/user/AccountVO.java +++ b/core/src/com/cloud/user/AccountVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account") -public class AccountVO implements Account, Identity { +public class AccountVO implements Account { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -54,28 +55,28 @@ public class AccountVO implements Account, Identity { @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + @Column(name="cleanup_needed") private boolean needsCleanup = false; - + @Column(name="network_domain") private String networkDomain; @Column(name="uuid") private String uuid; - + @Column(name="default_zone_id") private Long defaultZoneId = null; public AccountVO() { this.uuid = UUID.randomUUID().toString(); } - + public AccountVO(long id) { this.id = id; this.uuid = UUID.randomUUID().toString(); } - + public AccountVO(String accountName, long domainId, String networkDomain, short type) { this.accountName = accountName; this.domainId = domainId; @@ -84,11 +85,11 @@ public class AccountVO implements Account, Identity { this.state = State.enabled; this.uuid = UUID.randomUUID().toString(); } - + public void setNeedsCleanup(boolean value) { needsCleanup = value; } - + public boolean getNeedsCleanup() { return needsCleanup; } @@ -102,16 +103,16 @@ public class AccountVO implements Account, Identity { public String getAccountName() { return accountName; } - + public void setAccountName(String accountName) { this.accountName = accountName; } - + @Override public short getType() { return type; } - + public void setType(short type) { this.type = type; } @@ -120,16 +121,16 @@ public class AccountVO implements Account, Identity { public long getDomainId() { return domainId; } - + public void setDomainId(long domainId) { this.domainId = domainId; } - + @Override public Long getDefaultZoneId() { return defaultZoneId; } - + public void setDefaultZoneId(Long defaultZoneId) { this.defaultZoneId = defaultZoneId; } @@ -138,7 +139,7 @@ public class AccountVO implements Account, Identity { public State getState() { return state; } - + public void setState(State state) { this.state = state; } @@ -147,31 +148,31 @@ public class AccountVO implements Account, Identity { public Date getRemoved() { return removed; } - + @Override public long getAccountId() { return id; } - + @Override public String toString() { return new StringBuilder("Acct[").append(id).append("-").append(accountName).append("]").toString(); } - + @Override public String getNetworkDomain() { return networkDomain; } - + public void setNetworkDomain(String networkDomain) { this.networkDomain = networkDomain; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/core/src/com/cloud/user/SSHKeyPairVO.java b/core/src/com/cloud/user/SSHKeyPairVO.java index 0e13dc54c00..ab7eb8ea0b5 100644 --- a/core/src/com/cloud/user/SSHKeyPairVO.java +++ b/core/src/com/cloud/user/SSHKeyPairVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; diff --git a/core/src/com/cloud/user/UserAccountVO.java b/core/src/com/cloud/user/UserAccountVO.java index 1236061475b..cfad6171e55 100644 --- a/core/src/com/cloud/user/UserAccountVO.java +++ b/core/src/com/cloud/user/UserAccountVO.java @@ -29,12 +29,13 @@ import javax.persistence.Table; import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="user") @SecondaryTable(name="account", pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) -public class UserAccountVO implements UserAccount { +public class UserAccountVO implements UserAccount, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -101,7 +102,7 @@ public class UserAccountVO implements UserAccount { public UserAccountVO() {} @Override - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/user/UserStatisticsVO.java b/core/src/com/cloud/user/UserStatisticsVO.java index d560c3e6dad..eb59a74f8aa 100644 --- a/core/src/com/cloud/user/UserStatisticsVO.java +++ b/core/src/com/cloud/user/UserStatisticsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.user; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="user_statistics") -public class UserStatisticsVO { +public class UserStatisticsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -88,7 +90,7 @@ public class UserStatisticsVO { return accountId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/user/UserVO.java b/core/src/com/cloud/user/UserVO.java index f5fd5da8f96..919f4134e06 100644 --- a/core/src/com/cloud/user/UserVO.java +++ b/core/src/com/cloud/user/UserVO.java @@ -28,10 +28,11 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.user.Account.State; import com.cloud.utils.db.Encrypt; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * A bean representing a user @@ -39,7 +40,7 @@ import com.cloud.utils.db.GenericDao; */ @Entity @Table(name = "user") -public class UserVO implements User, Identity { +public class UserVO implements User, Identity, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/core/src/com/cloud/vm/InstanceGroupVMMapVO.java b/core/src/com/cloud/vm/InstanceGroupVMMapVO.java index 09cfd9c6070..996655da57e 100644 --- a/core/src/com/cloud/vm/InstanceGroupVMMapVO.java +++ b/core/src/com/cloud/vm/InstanceGroupVMMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.vm; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -34,7 +36,7 @@ import javax.persistence.Table; @SecondaryTable(name="instance_group", pkJoinColumns={@PrimaryKeyJoinColumn(name="group_id", referencedColumnName="id")}) }) -public class InstanceGroupVMMapVO { +public class InstanceGroupVMMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -54,7 +56,7 @@ public class InstanceGroupVMMapVO { this.instanceId = instanceId; } - public Long getId() { + public long getId() { return id; } diff --git a/core/src/com/cloud/vm/InstanceGroupVO.java b/core/src/com/cloud/vm/InstanceGroupVO.java index da1efa897da..ad66b5a4b2c 100644 --- a/core/src/com/cloud/vm/InstanceGroupVO.java +++ b/core/src/com/cloud/vm/InstanceGroupVO.java @@ -28,14 +28,15 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.SecondaryTable; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="instance_group") @SecondaryTable(name="account", pkJoinColumns={@PrimaryKeyJoinColumn(name="account_id", referencedColumnName="id")}) -public class InstanceGroupVO implements InstanceGroup, Identity { +public class InstanceGroupVO implements InstanceGroup { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/vm/UserVmDetailVO.java b/core/src/com/cloud/vm/UserVmDetailVO.java index bf2f32351a1..245b577bc39 100644 --- a/core/src/com/cloud/vm/UserVmDetailVO.java +++ b/core/src/com/cloud/vm/UserVmDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.vm; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="user_vm_details") -public class UserVmDetailVO { +public class UserVmDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/core/src/com/cloud/vm/VMInstanceVO.java b/core/src/com/cloud/vm/VMInstanceVO.java index 4f9717ecd80..c63dd839c58 100644 --- a/core/src/com/cloud/vm/VMInstanceVO.java +++ b/core/src/com/cloud/vm/VMInstanceVO.java @@ -42,6 +42,7 @@ import com.cloud.utils.db.GenericDao; import com.cloud.utils.db.StateMachine; import com.cloud.utils.fsm.FiniteStateObject; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vm_instance") diff --git a/debian/cloud-agent.install b/debian/cloud-agent.install index 1afb7fa9f94..c67e90ab492 100644 --- a/debian/cloud-agent.install +++ b/debian/cloud-agent.install @@ -21,4 +21,5 @@ /etc/cloud/agent/log4j-cloud.xml /etc/init.d/cloud-agent /usr/bin/cloud-setup-agent +/usr/bin/cloud-ssh /var/log/cloud/agent diff --git a/debian/cloud-utils.install b/debian/cloud-utils.install index b26a02c5095..39c357a1fa6 100644 --- a/debian/cloud-utils.install +++ b/debian/cloud-utils.install @@ -17,8 +17,6 @@ /usr/share/java/cloud-utils.jar /usr/share/java/cloud-api.jar -/usr/share/doc/cloud/sccs-info /usr/share/doc/cloud/version-info -/usr/share/doc/cloud/configure-info /usr/bin/cloud-sccs /usr/bin/cloud-gitrevs diff --git a/debian/control b/debian/control index 44736d74511..380b2e4a78d 100644 --- a/debian/control +++ b/debian/control @@ -90,7 +90,7 @@ Description: CloudStack agent libraries Package: cloud-agent Architecture: any -Depends: openjdk-6-jre, cloud-utils (= ${source:Version}), cloud-core (= ${source:Version}), cloud-agent-deps (= ${source:Version}), cloud-python (= ${source:Version}), cloud-agent-libs (= ${source:Version}), cloud-scripts (= ${source:Version}), libvirt0, sysvinit-utils, chkconfig, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, ebtables, vlan, liblog4j1.2-java (>= 1.2.16), libjna-java, wget, jsvc, lsb-base (>= 3.2) +Depends: openjdk-6-jre, cloud-utils (= ${source:Version}), cloud-core (= ${source:Version}), cloud-agent-deps (= ${source:Version}), cloud-python (= ${source:Version}), cloud-agent-libs (= ${source:Version}), cloud-scripts (= ${source:Version}), cloud-system-iso (= ${source:Version}), libvirt0, sysvinit-utils, chkconfig, qemu-kvm, libvirt-bin, uuid-runtime, rsync, grep, iproute, ebtables, vlan, liblog4j1.2-java (>= 1.2.16), libjna-java, wget, jsvc, lsb-base (>= 3.2) Description: CloudStack agent The CloudStack agent is in charge of managing shared computing resources in a CloudStack powered cloud. Install this package if this computer diff --git a/debian/rules b/debian/rules index 674d65df8c7..36b611ddc04 100755 --- a/debian/rules +++ b/debian/rules @@ -16,77 +16,55 @@ export DH_VERBOSE=1 # This has to be exported to make some magic below work. export DH_OPTIONS - - - - - configure: configure-stamp configure-stamp: dh_testdir - # Add here commands to configure the package. - ./waf configure --prefix=/usr --libdir=/usr/lib --bindir=/usr/bin --javadir=/usr/share/java --sharedstatedir=/var/lib --localstatedir=/var --sysconfdir=/etc --mandir=/usr/share/man --libexecdir=/usr/bin --with-tomcat=/usr/share/tomcat6 --tomcat-user=cloud --fast --package-version=$(PACKAGEVERSION) - ./waf showconfig + cp packaging/debian/replace.properties build/replace.properties + echo VERSION=$VERSION >> build/replace.properties touch configure-stamp - -#Architecture -# build: build-arch build-indep build: build-arch build-arch: build-arch-stamp build-arch-stamp: configure-stamp - - # Add here commands to compile the arch part of the package. - ./waf build --build-number=$(BUILDNUMBER) --package-version=$(PACKAGEVERSION) + mvn package -Dsystemvm touch $@ -# build-indep: build-indep-stamp -# build-indep-stamp: configure-stamp -# -# # Add here commands to compile the indep part of the package. -# #$(MAKE) doc -# touch $@ -# clean: dh_testdir dh_testroot rm -f build-arch-stamp build-indep-stamp configure-stamp - - # Add here commands to clean up after the build process. - ./waf distclean - dh_clean -install: install-arch -# install: install-indep install-arch -# install-indep: -# dh_testdir -# dh_testroot -# dh_prep -i -# dh_installdirs -i -# -# # Add here commands to install the indep part of the package into -# # debian/-doc. -# #INSTALLDOC# -# -# dh_install -i - -install-arch: +install: dh_testdir dh_testroot - dh_prep -s + dh_prep -s + mkdir -p debian/tmp/usr/bin + mkdir -p debian/tmp/usr/share/cloud/management + mkdir -p debian/tmp/var/log/cloud + mkdir debian/tmp/var/log/cloud/managament + mkdir debian/tmp/var/log/cloud/awsapi + mkdir debian/tmp/var/log/cloud/agent + mkdir debian/tmp/var/log/cloud/ipallocator + mkdir debian/tmp/var/log/cloud/usage + mkdir -p debian/tmp/etc/cloud + mkdir debian/tmp/etc/cloud/agent + mkdir debian/tmp/etc/cloud/server + mkdir debian/tmp/etc/cloud/management + mkdir debian/tmp/etc/cloud/usage + mkdir -p debian/tmp/var/cache/cloud + mkdir debian/tmp/var/cache/cloud/management + mkdir -p debian/tmp/usr/share/cloud + mkdir debian/tmp/usr/share/cloud/setup + mkdir -p debian/tmp/usr/share/cloud/management/webapps/client + + cp -r client/target/utilities/scripts/db/* debian/tmp/usr/share/cloud/setup/ + cp -r client/target/cloud-client-ui-4.1.0-SNAPSHOT/* debian/tmp/usr/share/cloud/management/webapps/client/ dh_installdirs -s - - # Add here commands to install the arch part of the package into - # debian/tmp. - # we put the build number again here, otherwise state checking will cause an almost-full recompile - ./waf install --destdir=$(CURDIR)/debian/tmp install --nochown --build-number=$(BUILDNUMBER) - dh_install -s -# Must not depend on anything. This is to be called by -# binary-arch/binary-indep -# in another 'make' thread. + +binary: binary-common binary-common: dh_testdir dh_testroot @@ -95,39 +73,13 @@ binary-common: dh_installdocs DISCLAIMER dh_installdocs NOTICE dh_installdocs INSTALL.md -# dh_installexamples -# dh_installmenu -# dh_installdebconf -# dh_installlogrotate -# dh_installemacsen -# dh_installpam -# dh_installmime -# dh_python -# dh_installinit -# dh_installcron -# dh_installinfo dh_installman dh_link dh_strip dh_compress dh_fixperms -# dh_perl dh_makeshlibs dh_installdeb -# dh_shlibdeps dh_gencontrol dh_md5sums - mkdir -p ./artifacts/debs - dh_builddeb --destdir=$(CURDIR)/artifacts/debs -# Build architecture independant packages using the common target. -# binary-indep: build-indep install-indep -# $(MAKE) -f debian/rules DH_OPTIONS=-i binary-common - -# Build architecture dependant packages using the common target. -binary-arch: build-arch install-arch - $(MAKE) -f debian/rules DH_OPTIONS=-s binary-common - -# binary: binary-arch binary-indep -binary: binary-arch -# .PHONY: build clean binary-indep binary-arch binary install install-indep install-arch configure -.PHONY: build clean binary-arch binary install install-arch configure + dh_builddeb diff --git a/deps/XenServerJava/BSD b/deps/XenServerJava/BSD deleted file mode 100644 index 634d6890be7..00000000000 --- a/deps/XenServerJava/BSD +++ /dev/null @@ -1,26 +0,0 @@ -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. diff --git a/deps/XenServerJava/LICENSE.Apache-2.0.txt b/deps/XenServerJava/LICENSE.Apache-2.0.txt deleted file mode 100644 index 261eeb9e9f8..00000000000 --- a/deps/XenServerJava/LICENSE.Apache-2.0.txt +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) 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. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed 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/deps/XenServerJava/LICENSE.txt b/deps/XenServerJava/LICENSE.txt deleted file mode 100644 index 76c4a2240fa..00000000000 --- a/deps/XenServerJava/LICENSE.txt +++ /dev/null @@ -1,26 +0,0 @@ -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. \ No newline at end of file diff --git a/deps/XenServerJava/README.txt b/deps/XenServerJava/README.txt deleted file mode 100644 index a7cea3549c8..00000000000 --- a/deps/XenServerJava/README.txt +++ /dev/null @@ -1,46 +0,0 @@ -XenServerJava -============= - -Version 5.6.100-1. - -XenServerJava is a complete SDK for Citrix XenServer, exposing the XenServer -API as Java classes. - -For XenServer documentation, see http://docs.xensource.com. -XenServerJava includes a class for every XenServer class, and a method for -each XenServer API call, so API documentation and examples written for -for other languages will apply equally well to Java. -In particular, the SDK Guide and API Documentation are ideal for developers -wishing to use XenServerJava. - -For community content, blogs, and downloads, visit the XenServer Developer -Network at http://community.citrix.com/cdn/xs. - -XenServerJava is free sofware. You can redistribute and modify it under the -terms of the BSD 2-clause license. See LICENSE.txt for details. - -This library may be accompanied by pedagogical examples. These do not form -part of this library, and are licensed for redistribution and modification -under less restrictive terms. Such examples are licensed clearly at the top -of each file. - -XenServerJava is dependent upon Apache XML-RPC and WS-Commons, both by The -Apache Software Foundation. We would like to thank the ASF and the -Apache XML-RPC development team in particular. -Both are licensed under the Apache Software License 2.0; see -LICENSE.Apache-2.0.txt for details. - -We test with version 3.1 of Apache XML-RPC, and version 1.0.2 of WS-Commons. -We recommend that you use these versions, though others may work. - -Downloads ---------- - -XenServerJava is available in three separate archives, one for the compiled -binaries, one for the source code, and one containing sample code. - -All three archives are available from the XenServer Developer Network at -http://community.citrix.com/cdn/xs. - -Apache XML-RPC is available from http://ws.apache.org/xmlrpc/. -WS-Commons is available from http://ws.apache.org/commons/. 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/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/install-non-oss.sh b/deps/install-non-oss.sh index 9c65a311b94..28eb03e1562 100755 --- a/deps/install-non-oss.sh +++ b/deps/install-non-oss.sh @@ -19,7 +19,13 @@ mvn install:install-file -Dfile=cloud-iControl.jar -DgroupId=com.cloud.com.f5 -DartifactId=icontrol -Dversion=1.0 -Dpackaging=jar mvn install:install-file -Dfile=cloud-netscaler.jar -DgroupId=com.cloud.com.citrix -DartifactId=netscaler -Dversion=1.0 -Dpackaging=jar mvn install:install-file -Dfile=cloud-netscaler-sdx.jar -DgroupId=com.cloud.com.citrix -DartifactId=netscaler-sdx -Dversion=1.0 -Dpackaging=jar -mvn install:install-file -Dfile=cloud-manageontap.jar -DgroupId=com.cloud.com.netapp -DartifactId=manageontap -Dversion=1.0 -Dpackaging=jar -mvn install:install-file -Dfile=vmware-vim.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim -Dversion=1.0 -Dpackaging=jar -mvn install:install-file -Dfile=vmware-vim25.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=1.0 -Dpackaging=jar -mvn install:install-file -Dfile=vmware-apputils.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-apputils -Dversion=1.0 -Dpackaging=jar +# +# From http://support.netapp.com/ (not available online, contact your support representative) +# Version: 4.0 +mvn install:install-file -Dfile=manageontap.jar -DgroupId=com.cloud.com.netapp -DartifactId=manageontap -Dversion=4.0 -Dpackaging=jar +# +# From https://my.vmware.com/group/vmware/get-download?downloadGroup=VSDK41 +# Version: 4.1, Release-date: 2010-07-13, Build: 257238 +mvn install:install-file -Dfile=vim25.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim25 -Dversion=4.1 -Dpackaging=jar +mvn install:install-file -Dfile=apputils.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-apputils -Dversion=4.1 -Dpackaging=jar +mvn install:install-file -Dfile=vim.jar -DgroupId=com.cloud.com.vmware -DartifactId=vmware-vim -Dversion=4.1 -Dpackaging=jar diff --git a/deps/pom.xml b/deps/pom.xml deleted file mode 100644 index 38bb17108c0..00000000000 --- a/deps/pom.xml +++ /dev/null @@ -1,201 +0,0 @@ - - - 4.0.0 - cloud-deps - Apache CloudStack Dependencies - jar - - org.apache.cloudstack - cloudstack - 4.1.0-SNAPSHOT - - - - org.apache.cloudstack - cloud-server - ${project.version} - - - org.apache.cloudstack - cloud-plugin-user-authenticator-ldap - ${project.version} - - - org.apache.cloudstack - cloud-plugin-user-authenticator-md5 - ${project.version} - - - org.apache.cloudstack - cloud-plugin-user-authenticator-plaintext - ${project.version} - - - org.apache.cloudstack - cloud-plugin-network-nvp - ${project.version} - - - org.apache.cloudstack - cloud-plugin-network-ovs - ${project.version} - - - org.apache.cloudstack - cloud-plugin-network-elb - ${project.version} - - - org.apache.cloudstack - cloud-plugin-hypervisor-xen - ${project.version} - - - org.apache.cloudstack - cloud-plugin-hypervisor-ovm - ${project.version} - - - org.apache.cloudstack - cloud-plugin-hypervisor-kvm - ${project.version} - - - org.apache.cloudstack - cloud-plugin-storage-allocator-random - ${project.version} - - - org.apache.cloudstack - cloud-plugin-planner-user-dispersing - ${project.version} - - - org.apache.cloudstack - cloud-plugin-planner-user-concentrated-pod - ${project.version} - - - org.apache.cloudstack - cloud-plugin-host-allocator-random - ${project.version} - - - org.apache.cloudstack - cloud-awsapi - ${project.version} - - - mysql - mysql-connector-java - 5.1.21 - runtime - - - - - org.apache.axis2 - axis2-ant-plugin - 1.4.1 - - - - org.apache.axis - axis - ${cs.axis.version} - - - org.apache.axis - axis-jaxrpc - ${cs.axis.version} - - - - install - - - org.apache.maven.plugins - maven-dependency-plugin - 2.5.1 - - - copy-dependencies - install - - copy-dependencies - - - . - false - false - true - cloud-core,cloud-server,cloud-api,cloud-vmware-base,cloud-agent,cloud-plugin-host-allocator-random,cloud-plugin-hypervisor-kvm,cloud-plugin-hypervisor-ovm,cloud-plugin-hypervisor-vmware,cloud-plugin-hypervisor-xen,cloud-plugin-netapp,cloud-plugin-network-elb,cloud-plugin-network-f5,cloud-plugin-network-netscaler,cloud-plugin-network-nvp,cloud-plugin-network-ovs,cloud-plugin-network-srx,cloud-plugin-planner-user-concentrated-pod,cloud-plugin-planner-user-dispersing,cloud-plugin-storage-allocator-random,cloud-plugin-user-authenticator-ldap,cloud-plugin-user-authenticator-md5,cloud-plugin-user-authenticator-plaintext,cloud-utils,cloud-vmware-base,cloud-awsapi,cloud-testclient - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - - org.apache.maven.plugins - - - maven-antrun-plugin - - [1.7,) - - run - - - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [2.0,) - - copy-dependencies - - - - - - - - - - - - - - diff --git a/developer/developer-prefill.sql b/developer/developer-prefill.sql new file mode 100644 index 00000000000..e14ac375e98 --- /dev/null +++ b/developer/developer-prefill.sql @@ -0,0 +1,54 @@ +-- 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. + +-- Add a default ROOT domain +use cloud; + +INSERT INTO `cloud`.`domain` (id, name, parent, path, owner) VALUES + (1, 'ROOT', NULL, '/', 2); + +-- Add system and admin accounts +INSERT INTO `cloud`.`account` (id, account_name, type, domain_id, state) VALUES + (1, 'system', 1, 1, 'enabled'); + +INSERT INTO `cloud`.`account` (id, account_name, type, domain_id, state) VALUES + (2, 'admin', 1, 1, 'enabled'); + +-- Add system user +INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, + lastname, email, state, created) VALUES (1, 'system', RAND(), + '1', 'system', 'cloud', NULL, 'enabled', NOW()); + +-- Add system user with encrypted password=password +INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, + lastname, email, state, created) VALUES (2, 'admin', '5f4dcc3b5aa765d61d8327deb882cf99', + '2', 'Admin', 'User', 'admin@mailprovider.com', 'enabled', NOW()); + +-- Add configurations +INSERT INTO `cloud`.`configuration` (category, instance, component, name, value) + VALUES ('Hidden', 'DEFAULT', 'management-server', 'init', 'false'); + +INSERT INTO `cloud`.`configuration` (category, instance, component, name, value) + VALUES ('Advanced', 'DEFAULT', 'management-server', + 'integration.api.port', '8096'); + +-- Add developer configuration entry; allows management server to be run as a user other than "cloud" +INSERT INTO `cloud`.`configuration` (category, instance, component, name, value) + VALUES ('Advanced', 'DEFAULT', 'management-server', + 'developer', 'true'); + +commit; diff --git a/developer/pom.xml b/developer/pom.xml index c4d77f7dadd..4ebb903289d 100644 --- a/developer/pom.xml +++ b/developer/pom.xml @@ -1,14 +1,15 @@ - + 4.0.0 cloud-developer @@ -292,6 +293,7 @@ + org.gjt.mm.mysql.Driver jdbc:mysql://${db.cloud.host}:${db.cloud.port}/cloud ${db.cloud.username} @@ -300,7 +302,6 @@ ${maven.test.skip} true - drop-database @@ -424,11 +425,13 @@ root ${db.root.password} jdbc:mysql://${db.cloud.host}:${db.cloud.port} - drop database if exists `cloudbridge` + GRANT ALL ON cloud_usage.* to + ${db.cloud.username}@`localhost` identified by + '${db.cloud.password}'; - create-database-cloudbridge + grant-user-cloud-usage-all process-test-resources execute @@ -437,7 +440,9 @@ root ${db.root.password} jdbc:mysql://${db.cloud.host}:${db.cloud.port} - create database `cloudbridge` + GRANT ALL ON cloud_usage.* to + ${db.cloud.username}@`%` identified by + '${db.cloud.password}'; @@ -470,6 +475,166 @@ '${db.cloud.password}'; + + create-schema + process-test-resources + + execute + + + + ${basedir}/target/db/create-schema.sql + ${basedir}/target/db/create-schema-view.sql + ${basedir}/target/db/create-schema-premium.sql + ${basedir}/target/db/templates.sql + ${basedir}/target/db/create-index-fk.sql + ${basedir}/target/db/cloudbridge_schema.sql + ${basedir}/target/db/cloudbridge_multipart.sql + ${basedir}/target/db/cloudbridge_index.sql + ${basedir}/target/db/cloudbridge_multipart_alter.sql + ${basedir}/target/db/cloudbridge_bucketpolicy.sql + ${basedir}/target/db/cloudbridge_policy_alter.sql + ${basedir}/target/db/cloudbridge_offering.sql + ${basedir}/target/db/cloudbridge_offering_alter.sql + + + + + prefill-developer-schema + process-test-resources + + execute + + + true + + ${basedir}/developer-prefill.sql + + + + + + + + + + + + simulator + + deploydb-simulator + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 + + + initialize + + read-project-properties + + + + ${project.parent.basedir}/utils/conf/db.properties + ${project.parent.basedir}/utils/conf/db.properties.override + + true + + + + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + + + mysql + mysql-connector-java + ${cs.mysql.version} + + + + org.gjt.mm.mysql.Driver + jdbc:mysql://${db.simulator.host}:3306/simulator + ${db.simulator.username} + ${db.simulator.password} + ${maven.test.skip} + true + + + + drop-database + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + drop database if exists `simulator` + + + + create-database + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + create database `simulator` + + + + grant-user-cloud + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + GRANT ALL ON simulator.* to + ${db.simulator.username}@`localhost` identified by + '${db.simulator.password}'; + + + + grant-user-cloud-all + process-test-resources + + execute + + + root + ${db.root.password} + jdbc:mysql://${db.simulator.host}:3306 + GRANT ALL ON simulator.* to + ${db.simulator.username}@`%` identified by + '${db.simulator.password}'; + + + + create-schema + process-test-resources + + execute + + + + ${basedir}/target/db/create-schema-simulator.sql + ${basedir}/target/db/templates.simulator.sql + + + diff --git a/docs/README.txt b/docs/README.txt index 113cfed77ee..e327fb9101c 100644 --- a/docs/README.txt +++ b/docs/README.txt @@ -122,7 +122,7 @@ publican build --formats test --langs en-US publican build --formats html,pdf --langs en-US -Output will be found in the /tmp subdirectory. +Output will be found in the tmp subdirectory of the docs directory. @@ -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: @@ -210,8 +210,7 @@ TAGS FOR A SECTION Our publication tool (publican) prefers the note tag. The tool will automatically insert the text NOTE: for you, so please don't type it. Use this for anything that is vital to avoid runtime errors. Don't use - other tags such as caution. Our publication tool (publican) prefers the warning tag. The tool will - automatically insert the text WARNING: for you, so please don't type it. + other tags such as caution. Our publication tool (publican) prefers the warning tag. The tool will automatically insert the text WARNING: for you, so please don't type it. Here's how to do a bulleted list: Bulleted list item text. diff --git a/docs/en-US/Admin_Guide.xml b/docs/en-US/Admin_Guide.xml index b8b90ee62e5..07f5e889fc8 100644 --- a/docs/en-US/Admin_Guide.xml +++ b/docs/en-US/Admin_Guide.xml @@ -24,9 +24,9 @@ - &PRODUCT; Admin Guide + &PRODUCT; Administrator's Guide Apache CloudStack - 4.0 + 4.0.0-incubating 1 @@ -45,7 +45,30 @@ - + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/docs/en-US/Book_Info.xml b/docs/en-US/Book_Info.xml index 3bd6efa176f..c125ab8de2b 100644 --- a/docs/en-US/Book_Info.xml +++ b/docs/en-US/Book_Info.xml @@ -27,7 +27,7 @@ &PRODUCT; Guide Revised August 9, 2012 10:48 pm Pacific Apache CloudStack - 4.0 + 4.0.0-incubating 1 diff --git a/docs/en-US/Book_Info_Release_Notes_4-0.xml b/docs/en-US/Book_Info_Release_Notes_4-0.xml new file mode 100644 index 00000000000..0d57fb6d9a8 --- /dev/null +++ b/docs/en-US/Book_Info_Release_Notes_4-0.xml @@ -0,0 +1,39 @@ + + +%BOOK_ENTITIES; +]> + + + Version 4.0.0-incubating Release Notes + Revised October 17, 2012 19:49 UTC + Apache CloudStack + + + + Release notes for the Apache CloudStack 4.0.0-incubating release. + + + + + + + + + + + diff --git a/docs/en-US/CloudStack_Nicira_NVP_Guide.xml b/docs/en-US/CloudStack_Nicira_NVP_Guide.xml index c535c7cb891..a4c367c26f7 100644 --- a/docs/en-US/CloudStack_Nicira_NVP_Guide.xml +++ b/docs/en-US/CloudStack_Nicira_NVP_Guide.xml @@ -28,7 +28,7 @@ &PRODUCT; Plugin Guide for the Nicira NVP Plugin Apache CloudStack - 4.0 + 4.0.0-incubating 1 diff --git a/docs/en-US/API_Developers_Guide.ent b/docs/en-US/Developers_Guide.ent similarity index 91% rename from docs/en-US/API_Developers_Guide.ent rename to docs/en-US/Developers_Guide.ent index 6e902acd479..47a2b6757f8 100644 --- a/docs/en-US/API_Developers_Guide.ent +++ b/docs/en-US/Developers_Guide.ent @@ -15,7 +15,7 @@ specific language governing permissions and limitations under the License. --> - + - + \ No newline at end of file diff --git a/docs/en-US/API_Developers_Guide.xml b/docs/en-US/Developers_Guide.xml similarity index 62% rename from docs/en-US/API_Developers_Guide.xml rename to docs/en-US/Developers_Guide.xml index 7d55e0dd890..6c09354f6a8 100644 --- a/docs/en-US/API_Developers_Guide.xml +++ b/docs/en-US/Developers_Guide.xml @@ -23,15 +23,15 @@ --> - - &PRODUCT; API Developers Guide + + &PRODUCT; Developer's Guide Apache CloudStack - 4.0 + 4.0.0-incubating - Complete technical documentation of &PRODUCT;. + 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,7 +45,14 @@ - + + + + + + + + + - diff --git a/docs/en-US/Installation_Guide.xml b/docs/en-US/Installation_Guide.xml index 773fffb5815..2f60acac984 100644 --- a/docs/en-US/Installation_Guide.xml +++ b/docs/en-US/Installation_Guide.xml @@ -26,7 +26,7 @@ &PRODUCT; Installation Guide Apache CloudStack - 4.0 + 4.0.0-incubating 1 @@ -46,10 +46,16 @@ + + + + + + diff --git a/docs/en-US/release-notes.ent b/docs/en-US/Release_Notes.ent similarity index 100% rename from docs/en-US/release-notes.ent rename to docs/en-US/Release_Notes.ent diff --git a/docs/en-US/Release_Notes.xml b/docs/en-US/Release_Notes.xml new file mode 100644 index 00000000000..c8cc6869737 --- /dev/null +++ b/docs/en-US/Release_Notes.xml @@ -0,0 +1,2923 @@ + + +%BOOK_ENTITIES; +]> + + + + + Submitting Feedback and Getting Help + The Apache CloudStack project has mailing lists for users and developers. These are the + official channels of communication for the project and are the best way to get answers about + using and contributing to CloudStack. It's a good idea to subscribe to the cloudstack-users + mailing list if you've deployed or are deploying CloudStack into production, and even for test + deployments. + The CloudStack developer's mailing list (cloudstack-dev) is for discussions about + CloudStack development, and is the best list for discussing possible bugs in CloudStack. + Anyone contributing to CloudStack should be on this mailing list. + You can also report bugs in CloudStack using the Apache Defect Tracking + System. + To posts to the lists, you'll need to be subscribed. See the CloudStack Web site + for instructions. + + + Upgrade Instructions +
+ Upgrade from 3.0.2 to 4.0.0-incubating + Perform the following to upgrade from version 3.0.2 to version 4.0.0-incubating. Note + that some of the steps here are only required if you're using a specific hypervisor. The + steps that are hypervisor-specific are called out with a note. + + + Ensure that you query your IP address usage records and process them or make a + backup. During the upgrade you will lose the old IP address usage records. + Starting in 3.0.2, the usage record format for IP addresses is the same as the rest + of the usage types. Instead of a single record with the assignment and release dates, + separate records are generated per aggregation period with start and end dates. After + upgrading, any existing IP address usage records in the old format will no longer be + available. + + + + The following upgrade instructions apply only if you're using VMware hosts. If + you're not using VMware hosts, skip this step and move on to step 3: stopping all + usage servers. + + In each zone that includes VMware hosts, you need to add a new system VM template. + + + While running the existing 3.0.2 system, log in to the UI as root + administrator. + + + In the left navigation bar, click Templates. + + + In Select view, click Templates. + + + Click Register template. + The Register template dialog box is displayed. + + + In the Register template dialog box, specify the following values (do not change + these): + + + + + + + Field + Value + + + + + Name + systemvm-vmware-3.0.0 + + + Description + systemvm-vmware-3.0.0 + + + URL + http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova + + + Zone + Choose the zone where this hypervisor is used + + + Hypervisor + VMware + + + Format + OVA + + + OS Type + Debian GNU/Linux 5.0 (32-bit) + + + Extractable + no + + + Password Enabled + no + + + Public + no + + + Featured + no + + + + + + + Watch the screen to be sure that the template downloads successfully and enters + the READY state. Do not proceed until this is successful. + + + + + Stop all Usage Servers if running. Run this on all Usage Server hosts. + # service cloud-usage stop + + + Stop the Management Servers. Run this on all Management Server hosts. + # service cloud-management stop + + + On the MySQL master, take a backup of the MySQL databases. We recommend performing + this step even in test upgrades. If there is an issue, this will assist with + debugging. + In the following commands, it is assumed that you have set the root password on the + database, which is a CloudStack recommended best practice. Substitute your own MySQL + root password. + # mysqldump -u root -pmysql_password cloud > cloud-backup.dmp +# mysqldump -u root -pmysql_password cloud_usage > cloud-usage-backup.dmp + + + Either build RPM/DEB packages as detailed in the Installation Guide, or use one of + the community provided yum/apt repositories to gain access to the &PRODUCT; + binaries. + + + After you have configured an appropriate yum or apt repository, you may execute the + one of the following commands as appropriate for your environment in order to upgrade + &PRODUCT;: # yum update cloud-* + # apt-get update +# apt-get upgrade cloud-* + + You will, of course, have to agree to the changes suggested by Yum or APT. + + If the upgrade output includes a message similar to the following, then some + custom content was found in your old components.xml, and you need to merge the two + files: + warning: /etc/cloud/management/components.xml created as /etc/cloud/management/components.xml.rpmnew + Instructions follow in the next step. + + + + If you have made changes to your copy of + /etc/cloud/management/components.xml the changes will be + preserved in the upgrade. However, you need to do the following steps to place these + changes in a new version of the file which is compatible with version + 4.0.0-incubating. + + + Make a backup copy of /etc/cloud/management/components.xml. + For example: + # mv /etc/cloud/management/components.xml /etc/cloud/management/components.xml-backup + + + Copy /etc/cloud/management/components.xml.rpmnew to create + a new /etc/cloud/management/components.xml: + # cp -ap /etc/cloud/management/components.xml.rpmnew /etc/cloud/management/components.xml + + + Merge your changes from the backup file into the new + components.xml. + # vi /etc/cloud/management/components.xml + + + + If you have more than one management server node, repeat the upgrade steps on each + node. + + + + Start the first Management Server. Do not start any other Management Server nodes + yet. + # service cloud-management start + Wait until the databases are upgraded. Ensure that the database upgrade is complete. + After confirmation, start the other Management Servers one at a time by running the same + command on each node. + + Failing to restart the Management Server indicates a problem in the upgrade. + Having the Management Server restarted without any issues indicates that the upgrade + is successfully completed. + + + + Start all Usage Servers (if they were running on your previous version). Perform + this on each Usage Server host. + # service cloud-usage start + + + + Additional steps are required for each KVM host. These steps will not affect + running guests in the cloud. These steps are required only for clouds using KVM as + hosts and only on the KVM hosts. + + + + Configure a yum or apt respository containing the &PRODUCT; packages as outlined + in the Installation Guide. + + + Stop the running agent. + # service cloud-agent stop + + + Update the agent software with one of the following command sets as appropriate + for your environment. + # yum update cloud-* + # apt-get update + # apt-get upgrade cloud-* + + + Start the agent. + # service cloud-agent start + + + Edit /etc/cloud/agent/agent.properties to change the + resource parameter from + "com.cloud.agent.resource.computing.LibvirtComputingResource" to + "com.cloud.hypervisor.kvm.resource.LibvirtComputingResource". + + + Start the cloud agent and cloud management services. + + + When the Management Server is up and running, log in to the CloudStack UI and + restart the virtual router for proper functioning of all the features. + + + + + Log in to the CloudStack UI as administrator, and check the status of the hosts. All + hosts should come to Up state (except those that you know to be offline). You may need + to wait 20 or 30 minutes, depending on the number of hosts. + + Troubleshooting: If login fails, clear your browser cache and reload the + page. + + + Do not proceed to the next step until the hosts show in Up state. + + + If you are upgrading from 3.0.2, perform the following: + + + Ensure that the admin port is set to 8096 by using the "integration.api.port" + global parameter. + This port is used by the cloud-sysvmadm script at the end of the upgrade + procedure. For information about how to set this parameter, see "Setting Global + Configuration Parameters" in the Installation Guide. + + + Restart the Management Server. + + If you don't want the admin port to remain open, you can set it to null after + the upgrade is done and restart the management server. + + + + + + Run the cloud-sysvmadm script to stop, then start, all Secondary + Storage VMs, Console Proxy VMs, and virtual routers. Run the script once on each + management server. Substitute your own IP address of the MySQL instance, the MySQL user + to connect as, and the password to use for that user. In addition to those parameters, + provide the -c and -r arguments. For + example: + # nohup cloud-sysvmadm -d 192.168.1.5 -u cloud -p password -c -r > + sysvm.log 2>&1 & + # tail -f sysvm.log + This might take up to an hour or more to run, depending on the number of accounts in + the system. + + + If needed, upgrade all Citrix XenServer hypervisor hosts in your cloud to a version + supported by CloudStack 4.0.0-incubating. The supported versions are XenServer 5.6 SP2 + and 6.0.2. Instructions for upgrade can be found in the CloudStack 4.0.0-incubating + Installation Guide. + + + Now apply the XenServer hotfix XS602E003 (and any other needed hotfixes) to + XenServer v6.0.2 hypervisor hosts. + + + Disconnect the XenServer cluster from CloudStack. + In the left navigation bar of the CloudStack UI, select Infrastructure. Under + Clusters, click View All. Select the XenServer cluster and click Actions - + Unmanage. + This may fail if there are hosts not in one of the states Up, Down, + Disconnected, or Alert. You may need to fix that before unmanaging this + cluster. + Wait until the status of the cluster has reached Unmanaged. Use the CloudStack + UI to check on the status. When the cluster is in the unmanaged state, there is no + connection to the hosts in the cluster. + + + To clean up the VLAN, log in to one XenServer host and run: + /opt/xensource/bin/cloud-clean-vlan.sh + + + Now prepare the upgrade by running the following on one XenServer host: + /opt/xensource/bin/cloud-prepare-upgrade.sh + If you see a message like "can't eject CD", log in to the VM and unmount the CD, + then run this script again. + + + Upload the hotfix to the XenServer hosts. Always start with the Xen pool master, + then the slaves. Using your favorite file copy utility (e.g. WinSCP), copy the + hotfixes to the host. Place them in a temporary folder such as /tmp. + On the Xen pool master, upload the hotfix with this command: + xe patch-upload file-name=XS602E003.xsupdate + Make a note of the output from this command, which is a UUID for the hotfix + file. You'll need it in another step later. + + (Optional) If you are applying other hotfixes as well, you can repeat the + commands in this section with the appropriate hotfix number. For example, + XS602E004.xsupdate. + + + + Manually live migrate all VMs on this host to another host. First, get a list of + the VMs on this host: + # xe vm-list + Then use this command to migrate each VM. Replace the example host name and VM + name with your own: + # xe vm-migrate live=true host=host-name + vm=VM-name + + Troubleshooting + If you see a message like "You attempted an operation on a VM which requires + PV drivers to be installed but the drivers were not detected," run: + /opt/xensource/bin/make_migratable.sh + b6cf79c8-02ee-050b-922f-49583d9f1a14. + + + + Apply the hotfix. First, get the UUID of this host: + # xe host-list + Then use the following command to apply the hotfix. Replace the example host + UUID with the current host ID, and replace the hotfix UUID with the output from the + patch-upload command you ran on this machine earlier. You can also get the hotfix + UUID by running xe patch-list. + xe patch-apply host-uuid=host-uuid uuid=hotfix-uuid + + + Copy the following files from the CloudStack Management Server to the + host. + + + + + + + Copy from here... + ...to here + + + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py + /opt/xensource/sm/NFSSR.py + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/setupxenserver.sh + /opt/xensource/bin/setupxenserver.sh + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/make_migratable.sh + /opt/xensource/bin/make_migratable.sh + + + + + + + (Only for hotfixes XS602E005 and XS602E007) You need to apply a new Cloud + Support Pack. + + + Download the CSP software onto the XenServer host from one of the following + links: + For hotfix XS602E005: http://coltrane.eng.hq.xensource.com/release/XenServer-6.x/XS-6.0.2/hotfixes/XS602E005/56710/xe-phase-2/xenserver-cloud-supp.tgz + For hotfix XS602E007: http://coltrane.eng.hq.xensource.com/release/XenServer-6.x/XS-6.0.2/hotfixes/XS602E007/57824/xe-phase-2/xenserver-cloud-supp.tgz + + + Extract the file: + # tar xf xenserver-cloud-supp.tgz + + + Run the following script: + # xe-install-supplemental-pack xenserver-cloud-supp.iso + + + If the XenServer host is part of a zone that uses basic networking, disable + Open vSwitch (OVS): + # xe-switch-network-backend bridge + + + + + Reboot this XenServer host. + + + Run the following: + /opt/xensource/bin/setupxenserver.sh + + If the message "mv: cannot stat `/etc/cron.daily/logrotate': No such file or + directory" appears, you can safely ignore it. + + + + Run the following: + for pbd in `xe pbd-list currently-attached=false| grep ^uuid | awk '{print $NF}'`; do xe pbd-plug uuid=$pbd ; + + + On each slave host in the Xen pool, repeat these steps, starting from "manually + live migrate VMs." + + + + + + Troubleshooting Tip + If passwords which you know to be valid appear not to work after upgrade, or other UI + issues are seen, try clearing your browser cache and reloading the UI page. + +
+
+ Upgrade from 2.2.14 to 4.0.0-incubating + + + Ensure that you query your IPaddress usage records and process them; for example, + issue invoices for any usage that you have not yet billed users for. + Starting in 3.0.2, the usage record format for IP addresses is the same as the rest + of the usage types. Instead of a single record with the assignment and release dates, + separate records are generated per aggregation period with start and end dates. After + upgrading to 4.0.0-incubating, any existing IP address usage records in the old format + will no longer be available. + + + If you are using version 2.2.0 - 2.2.13, first upgrade to 2.2.14 by using the + instructions in the 2.2.14 Release Notes. + + KVM Hosts + If KVM hypervisor is used in your cloud, be sure you completed the step to insert + a valid username and password into the host_details table on each KVM node as + described in the 2.2.14 Release Notes. This step is critical, as the database will be + encrypted after the upgrade to 4.0.0-incubating. + + + + While running the 2.2.14 system, log in to the UI as root administrator. + + + Using the UI, add a new System VM template for each hypervisor type that is used in + your cloud. In each zone, add a system VM template for each hypervisor used in that + zone + + + In the left navigation bar, click Templates. + + + In Select view, click Templates. + + + Click Register template. + The Register template dialog box is displayed. + + + In the Register template dialog box, specify the following values depending on + the hypervisor type (do not change these): + + + + + + + Hypervisor + Description + + + + + XenServer + Name: systemvm-xenserver-3.0.0 + Description: systemvm-xenserver-3.0.0 + URL: + http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2 + Zone: Choose the zone where this hypervisor is used + Hypervisor: XenServer + Format: VHD + OS Type: Debian GNU/Linux 5.0 (32-bit) + Extractable: no + Password Enabled: no + Public: no + Featured: no + + + + KVM + Name: systemvm-kvm-3.0.0 + Description: systemvm-kvm-3.0.0 + URL: + http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 + Zone: Choose the zone where this hypervisor is used + Hypervisor: KVM + Format: QCOW2 + OS Type: Debian GNU/Linux 5.0 (32-bit) + Extractable: no + Password Enabled: no + Public: no + Featured: no + + + + VMware + Name: systemvm-vmware-3.0.0 + Description: systemvm-vmware-3.0.0 + URL: + http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova + Zone: Choose the zone where this hypervisor is used + Hypervisor: VMware + Format: OVA + OS Type: Debian GNU/Linux 5.0 (32-bit) + Extractable: no + Password Enabled: no + Public: no + Featured: no + + + + + + + + + + Watch the screen to be sure that the template downloads successfully and enters the + READY state. Do not proceed until this is successful + + + WARNING: If you use more than one type of + hypervisor in your cloud, be sure you have repeated these steps to download the system + VM template for each hypervisor type. Otherwise, the upgrade will fail. + + + Stop all Usage Servers if running. Run this on all Usage Server hosts. + # service cloud-usage stop + + + Stop the Management Servers. Run this on all Management Server hosts. + # service cloud-management stop + + + On the MySQL master, take a backup of the MySQL databases. We recommend performing + this step even in test upgrades. If there is an issue, this will assist with + debugging. + In the following commands, it is assumed that you have set the root password on the + database, which is a CloudStack recommended best practice. Substitute your own MySQL + root password. + # mysqldump -u root -pmysql_password cloud > cloud-backup.dmp +# mysqldump -u root -pmysql_password cloud_usage > cloud-usage-backup.dmp + + + + Either build RPM/DEB packages as detailed in the Installation Guide, or use one of + the community provided yum/apt repositories to gain access to the &PRODUCT; binaries. + + + + After you have configured an appropriate yum or apt repository, you may execute the + one of the following commands as appropriate for your environment in order to upgrade + &PRODUCT;: # yum update cloud-* + # apt-get update +# apt-get upgrade cloud-* + + You will, of course, have to agree to the changes suggested by Yum or APT. + + + If you have made changes to your existing copy of the file components.xml in your + previous-version CloudStack installation, the changes will be preserved in the upgrade. + However, you need to do the following steps to place these changes in a new version of + the file which is compatible with version 4.0.0-incubating. + + How will you know whether you need to do this? If the upgrade output in the + previous step included a message like the following, then some custom content was + found in your old components.xml, and you need to merge the two files: + + warning: /etc/cloud/management/components.xml created as /etc/cloud/management/components.xml.rpmnew + + + Make a backup copy of your + /etc/cloud/management/components.xml file. For + example: + # mv /etc/cloud/management/components.xml /etc/cloud/management/components.xml-backup + + + Copy /etc/cloud/management/components.xml.rpmnew to create + a new /etc/cloud/management/components.xml: + # cp -ap /etc/cloud/management/components.xml.rpmnew /etc/cloud/management/components.xml + + + Merge your changes from the backup file into the new components.xml file. + # vi /etc/cloud/management/components.xml + + + + + + If you have made changes to your existing copy of the + /etc/cloud/management/db.properties file in your previous-version + CloudStack installation, the changes will be preserved in the upgrade. However, you need + to do the following steps to place these changes in a new version of the file which is + compatible with version 4.0.0-incubating. + + + Make a backup copy of your file + /etc/cloud/management/db.properties. For example: + # mv /etc/cloud/management/db.properties /etc/cloud/management/db.properties-backup + + + Copy /etc/cloud/management/db.properties.rpmnew to create a + new /etc/cloud/management/db.properties: + # cp -ap /etc/cloud/management/db.properties.rpmnew etc/cloud/management/db.properties + + + Merge your changes from the backup file into the new db.properties file. + # vi /etc/cloud/management/db.properties + + + + + On the management server node, run the following command. It is recommended that you + use the command-line flags to provide your own encryption keys. See Password and Key + Encryption in the Installation Guide. + # cloud-setup-encryption -e encryption_type -m management_server_key -k database_key + When used without arguments, as in the following example, the default encryption + type and keys will be used: + + + (Optional) For encryption_type, use file or web to indicate the technique used + to pass in the database encryption password. Default: file. + + + (Optional) For management_server_key, substitute the default key that is used to + encrypt confidential parameters in the properties file. Default: password. It is + highly recommended that you replace this with a more secure value + + + (Optional) For database_key, substitute the default key that is used to encrypt + confidential parameters in the CloudStack database. Default: password. It is highly + recommended that you replace this with a more secure value. + + + + + Repeat steps 10 - 14 on every management server node. If you provided your own + encryption key in step 14, use the same key on all other management servers. + + + Start the first Management Server. Do not start any other Management Server nodes + yet. + # service cloud-management start + Wait until the databases are upgraded. Ensure that the database upgrade is complete. + You should see a message like "Complete! Done." After confirmation, start the other + Management Servers one at a time by running the same command on each node. + + + Start all Usage Servers (if they were running on your previous version). Perform + this on each Usage Server host. + # service cloud-usage start + + + (KVM only) Additional steps are required for each KVM host. These steps will not + affect running guests in the cloud. These steps are required only for clouds using KVM + as hosts and only on the KVM hosts. + + + Configure your CloudStack package repositories as outlined in the Installation + Guide + + + Stop the running agent. + # service cloud-agent stop + + + Update the agent software with one of the following command sets as + appropriate. + # yum update cloud-* + + # apt-get update +# apt-get upgrade cloud-* + + + + Start the agent. + # service cloud-agent start + + + Copy the contents of the agent.properties file to the new + agent.properties file by using the following command + sed -i 's/com.cloud.agent.resource.computing.LibvirtComputingResource/com.cloud.hypervisor.kvm.resource.LibvirtComputingResource/g' /etc/cloud/agent/agent.properties + + + Start the cloud agent and cloud management services. + + + When the Management Server is up and running, log in to the CloudStack UI and + restart the virtual router for proper functioning of all the features. + + + + + Log in to the CloudStack UI as admin, and check the status of the hosts. All hosts + should come to Up state (except those that you know to be offline). You may need to wait + 20 or 30 minutes, depending on the number of hosts. + Do not proceed to the next step until the hosts show in the Up state. If the hosts + do not come to the Up state, contact support. + + + Run the following script to stop, then start, all Secondary Storage VMs, Console + Proxy VMs, and virtual routers. + + + Run the command once on one management server. Substitute your own IP address of + the MySQL instance, the MySQL user to connect as, and the password to use for that + user. In addition to those parameters, provide the "-c" and "-r" arguments. For + example: + # nohup cloud-sysvmadm -d 192.168.1.5 -u cloud -p password -c -r > sysvm.log 2>&1 & +# tail -f sysvm.log + This might take up to an hour or more to run, depending on the number of + accounts in the system. + + + After the script terminates, check the log to verify correct execution: + # tail -f sysvm.log + The content should be like the following: + +Stopping and starting 1 secondary storage vm(s)... +Done stopping and starting secondary storage vm(s) +Stopping and starting 1 console proxy vm(s)... +Done stopping and starting console proxy vm(s). +Stopping and starting 4 running routing vm(s)... +Done restarting router(s). + + + + + + If you would like additional confirmation that the new system VM templates were + correctly applied when these system VMs were rebooted, SSH into the System VM and check + the version. + Use one of the following techniques, depending on the hypervisor. + + XenServer or KVM: + SSH in by using the link local IP address of the system VM. For example, in the + command below, substitute your own path to the private key used to log in to the + system VM and your own link local IP. + + Run the following commands on the XenServer or KVM host on which the system VM is + present: + # ssh -i private-key-path link-local-ip -p 3922 +# cat /etc/cloudstack-release + The output should be like the following: + Cloudstack Release 4.0.0-incubating Mon Oct 9 15:10:04 PST 2012 + + ESXi + SSH in using the private IP address of the system VM. For example, in the command + below, substitute your own path to the private key used to log in to the system VM and + your own private IP. + + Run the following commands on the Management Server: + # ssh -i private-key-path private-ip -p 3922 +# cat /etc/cloudstack-release + + The output should be like the following: + Cloudstack Release 4.0.0-incubating Mon Oct 9 15:10:04 PST 2012 + + + If needed, upgrade all Citrix XenServer hypervisor hosts in your cloud to a version + supported by CloudStack 4.0.0-incubating. The supported versions are XenServer 5.6 SP2 + and 6.0.2. Instructions for upgrade can be found in the CloudStack 4.0.0-incubating + Installation Guide. + + + Apply the XenServer hotfix XS602E003 (and any other needed hotfixes) to XenServer + v6.0.2 hypervisor hosts. + + + Disconnect the XenServer cluster from CloudStack. + In the left navigation bar of the CloudStack UI, select Infrastructure. Under + Clusters, click View All. Select the XenServer cluster and click Actions - + Unmanage. + This may fail if there are hosts not in one of the states Up, Down, + Disconnected, or Alert. You may need to fix that before unmanaging this + cluster. + Wait until the status of the cluster has reached Unmanaged. Use the CloudStack + UI to check on the status. When the cluster is in the unmanaged state, there is no + connection to the hosts in the cluster. + + + To clean up the VLAN, log in to one XenServer host and run: + /opt/xensource/bin/cloud-clean-vlan.sh + + + Prepare the upgrade by running the following on one XenServer host: + /opt/xensource/bin/cloud-prepare-upgrade.sh + If you see a message like "can't eject CD", log in to the VM and umount the CD, + then run this script again. + + + Upload the hotfix to the XenServer hosts. Always start with the Xen pool master, + then the slaves. Using your favorite file copy utility (e.g. WinSCP), copy the + hotfixes to the host. Place them in a temporary folder such as /root or /tmp. + On the Xen pool master, upload the hotfix with this command: + xe patch-upload file-name=XS602E003.xsupdate + Make a note of the output from this command, which is a UUID for the hotfix + file. You'll need it in another step later. + + (Optional) If you are applying other hotfixes as well, you can repeat the + commands in this section with the appropriate hotfix number. For example, + XS602E004.xsupdate. + + + + Manually live migrate all VMs on this host to another host. First, get a list of + the VMs on this host: + # xe vm-list + Then use this command to migrate each VM. Replace the example host name and VM + name with your own: + # xe vm-migrate live=true host=host-name vm=VM-name + + Troubleshooting + If you see a message like "You attempted an operation on a VM which requires + PV drivers to be installed but the drivers were not detected," run: + /opt/xensource/bin/make_migratable.sh + b6cf79c8-02ee-050b-922f-49583d9f1a14. + + + + Apply the hotfix. First, get the UUID of this host: + # xe host-list + Then use the following command to apply the hotfix. Replace the example host + UUID with the current host ID, and replace the hotfix UUID with the output from the + patch-upload command you ran on this machine earlier. You can also get the hotfix + UUID by running xe patch-list. + xe patch-apply host-uuid=host-uuid + uuid=hotfix-uuid + + + Copy the following files from the CloudStack Management Server to the + host. + + + + + + + Copy from here... + ...to here + + + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py + /opt/xensource/sm/NFSSR.py + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/setupxenserver.sh + /opt/xensource/bin/setupxenserver.sh + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/make_migratable.sh + /opt/xensource/bin/make_migratable.sh + + + + + + + (Only for hotfixes XS602E005 and XS602E007) You need to apply a new Cloud + Support Pack. + + + Download the CSP software onto the XenServer host from one of the following + links: + For hotfix XS602E005: http://coltrane.eng.hq.xensource.com/release/XenServer-6.x/XS-6.0.2/hotfixes/XS602E005/56710/xe-phase-2/xenserver-cloud-supp.tgz + For hotfix XS602E007: http://coltrane.eng.hq.xensource.com/release/XenServer-6.x/XS-6.0.2/hotfixes/XS602E007/57824/xe-phase-2/xenserver-cloud-supp.tgz + + + Extract the file: + # tar xf xenserver-cloud-supp.tgz + + + Run the following script: + # xe-install-supplemental-pack + xenserver-cloud-supp.iso + + + If the XenServer host is part of a zone that uses basic networking, disable + Open vSwitch (OVS): + # xe-switch-network-backend bridge + + + + + Reboot this XenServer host. + + + Run the following: + /opt/xensource/bin/setupxenserver.sh + + If the message "mv: cannot stat `/etc/cron.daily/logrotate': No such file or + directory" appears, you can safely ignore it. + + + + Run the following: + for pbd in `xe pbd-list currently-attached=false| grep ^uuid | awk + '{print $NF}'`; do xe pbd-plug uuid=$pbd ; + + + + On each slave host in the Xen pool, repeat these steps, starting from "manually + live migrate VMs." + + + + +
+
+ + Version 4.0.0-incubating +
+ What’s New in 4.0.0-incubating + Apache CloudStack 4.0.0-incubating includes the following new features: +
+ Inter-VLAN Routing + Inter-VLAN Routing is the capability to route network traffic between VLANs. This + feature enables you to set up Virtual Private Clouds (VPC) that can hold multi-tier + applications. These tiers are deployed on different VLANs that can communicate with each + other. You can provision VLANs to the tiers your create, and VMs can be deployed on + different tiers, such as Web, Application, or Database. The VLANs are connected to a + virtual router, which facilitates communication between the VMs. In effect, you can + segment VMs by means of VLANs into different networks that can host multi-tier + applications. Such segmentation by means of VLANs logically separate application VMs for + higher security and lower broadcasts, while remaining physically connected to the same + device. + This feature is supported on XenServer and VMware hypervisors. +
+
+ Site-to-Site VPN + A Site-to-Site VPN connection helps you establish a secure connection from an + enterprise datacenter to the cloud infrastructure. This allows users to access the guest + VMs by establishing a VPN connection to the virtual router of the account from a device in + the datacenter of the enterprise. Having this facility eliminates the need to establish + VPN connections to individual VMs. + The supported endpoints on the remote datacenters are: + + + Cisco ISR with IOS 12.4 or later + + + Juniper J-Series routers with JunOS 9.5 or later + + +
+
+ Local Storage Support for Data Volumes + You can now create data volumes on local storage. The data volume is placed on the + same XenServer host as the VM instance that is attached to the data volume. These local + data volumes can be attached to virtual machines, detached, re-attached, and deleted just + as with the other types of data volume. In earlier releases of CloudStack, only the root + disk could be placed in local storage. + Local storage is ideal for scenarios where persistence of data volumes and HA is not + required. Some of the benefits include reduced disk I/O latency and cost reduction from + using inexpensive local disks. + In order for local volumes to be used, the feature must be enabled for the + zone. + You can create a data disk offering for local storage. When a user creates a new VM, + they can select this disk offering in order to cause the data disk volume to be placed in + local storage. + You can not migrate a VM that has a volume in local storage to a different host, nor + migrate the volume itself away to a different host. If you want to put a host into + maintenance mode, you must first stop any VMs with local data volumes on that host. + Local storage support for volumes is available for XenServer, KVM, and VMware + hypervisors. +
+
+ Tags + A tag is a key-value pair that stores metadata about a resource in the cloud. Tags are + useful for categorizing resources. For example, you can tag a user VM with a value that + indicates the user's city of residence. In this case, the key would be "city" and the + value might be "Toronto" or "Tokyo." You can then request CloudStack to find all resources + that have a given tag; for example, VMs for users in a given city. + You can tag a user virtual machine, volume, snapshot, guest network, template, ISO, + firewall rule, port forwarding rule, public IP address, security group, load balancer + rule, project, VPC, network ACL, or static route. You can not tag a remote access + VPN. + You can work with tags through the UI or through the new API commands createTags, + deleteTags, and listTags. You can define multiple tags for each resource. There is no + limit on the number of tags you can define. Each tag can be up to 255 characters long. + Users can define tags on the resources they own, and administrators can define tags on any + resources in the cloud. + A new optional input parameter, "tags," has been added to many of the list* API + commands. The following example shows how to use this new parameter to find all the + volumes having tag region=canada OR tag city=Toronto: + command=listVolumes +&listAll=true +&tags[0].key=region +&tags[0].value=canada +&tags[1].key=city +&tags[1].value=Toronto + The following API commands have the new "tags" input parameter: + + + listVirtualMachines + + + listVolumes + + + listSnapshots + + + listNetworks + + + listTemplates + + + listIsos + + + listFirewallRules + + + listPortForwardingRules + + + listPublicIpAddresses + + + listSecurityGroups + + + listLoadBalancerRules + + + listProjects + + + listVPCs + + + listNetworkACLs + + + listStaticRoutes + + +
+
+ AWS API Changes for Tags + Some changes have been made to the Amazon Web Services API compatibility support in + order to accommodate the new tagging feature. + New APIs: + + + + + + + + New API + + + Description + + + + + + + ec2-create-tags + + + Add tags to one or more resources. + + + + + ec2-delete-tags + + + Remove tags from one or more resources. + + + + ec2-describe-tags + + Show currently defined tags. + + + + + + Changed APIs: + + + + + + + + Changed API + + + Description + + + + + + ec2-describe-images + + Output now shows tags defined for each image. + + + + + ec2-describe-instances + + + Output now shows tags defined for each image. + The following filters can now be passed in to limit the output result set: + tag-key, tag-value and tag:key + + + + + ec2-describe-snapshots + + + Output now shows tags defined for each image. + The following filters can now be passed in to limit the output result set: + tag-key, tag-value and tag:key + + + + ec2-describe-volumes + + Output now shows tags defined for each image. + The following filters can now be passed in to limit the output result set: + tag-key, tag-value and tag:key + + + + + +
+
+ Secure Console Access on XenServer + With the addition of Secure Console feature, users can now securely access the VM + consoles on the XenServer hypervisor. You can either SSH or use the View Console option in + the Management Server to securely connect to the VMs on the XenServer host. The Management + Server uses the xapi API to stream the VM consoles. However, there is no change in the way + you can access the console of a VM. This feature is supported on XenServer 5.6 and 6.0 + versions. +
+
+ Stopped VM + This release supports creating VMs without starting them on the backend. You can + determine whether the VM needs to be started as part of the VM deployment. A VM can be + deployed in two ways: create and start a VM (the default method); create a VM and leave it + in the stopped state. + A new request parameter, startVM, is introduced in the deployVm API to support the + stopped VM feature. The possible values are: + + + true - The VM starts as a part of the VM deployment + + + false - The VM is left in stopped state at the end of the VM deployment + + +
+
+ Uploading an Existing Volume to a Virtual Machine + Existing data can now be made accessible to a virtual machine. This is called + uploading a volume to the VM. For example, this is useful to upload data from a local file + system and attach it to a VM. Root administrators, domain administrators, and end users + can all upload existing volumes to VMs. The upload is performed by using HTTP. The + uploaded volume is placed in the zone's secondary storage. + This functionality is supported for the following hypervisors: + + + Hypervisor : Disk Image Format + + + XenServer : VHD + + + VMware : OVA + + + KVM : QCOW2 + + + +
+
+ Dedicated High-Availability Hosts + One or more hosts can now be designated for use only by high-availability (HA) enabled + VMs that are restarted due to a host failure. Setting up a pool of such dedicated HA hosts + as the recovery destination for all HA-enabled VMs make it easier to determine which VMs + are restarted as part of the high-availability function. You can designate a host as a + dedicated-HA restart node only if the Dedicated HA Hosts feature is enabled by setting the + appropriate global configuration parameter. +
+
+ Support for Amazon Web Services API + This release supports Amazon Web Services APIs, including Elastic Compute Cloud (EC2) + API. Fidelity with the EC2 API and the installation experience for this functionality are + both enhanced. In prior releases, users were required to install a separate component + called CloudBridge, in addition to installing the Management Server. For new installations + of CloudStack 4.0.0-incubating, this software is installed automatically along with + CloudStack and runs in a more closely integrated fashion. The feature is disabled by + default, but can be easily enabled by setting the appropriate global configuration + parameter and performing a few setup steps. +
+
+ The Nicira NVP Plugin + The Nicira NVP plug-in allows CloudStack to use the Nicira solution for virtualized + network as a provider for CloudStack networks and services. In CloudStack 4.0.0-incubating + this plug-in supports the Connectivity service. This service is responsible for creating + Layer 2 networks supporting the networks created by guests. When a tenant creates a new + network, instead of a traditional VLAN, a logical network will be created by sending the + appropriate calls to the Nicira NVP Controller. The plug-in has been tested with Nicira + NVP versions 2.1.0, 2.2.0 and 2.2.1. +
+
+ Support for CAStor Cluster + CloudStack 4.0.0-incubating supports using a CAStor cluster as the back-end storage + system for a CloudStack S3 front-end. The CAStor back-end storage for CloudStack extends + the existing storage classes and allows the storage configuration attribute to point to a + CAStor cluster. This feature makes use of the CloudStack server's local disk to spool + files before writing them to CAStor when handling the PUT operations. However, a file must + be successfully written into the CAStor cluster prior to the return of a success code to + the S3 client to ensure that the transaction outcome is correctly reported. + The S3 multipart file upload is not supported in this release. You are prompted with + proper error message if a multipart upload is attempted. +
+
+ Clustered Logical Volume Manager Support for KVM + This release adds Clustered Logical Volume Manager (CLVM) storage support for KVM + hosts. With this support, you can use CLVM as primary storage. + The CLVM support for KVM allows root and data disks (primary storage) to reside on + Linux logical volumes. The administrators are required to configure CLVM on the KVM hosts + independent of CloudStack. When the volume groups are available, an administrator can + simply add primary storage of type CLVM, providing the volume group name. Then CloudStack + creates and manages logical volumes as needed. + CLVM also supports Snapshots. CloudStack creates an LVM snapshot, copy the applicable + logical volume to the secondary storage in the qcow2 format, and then delete the LVM + snapshot. +
+
+ Rados Block Device Support for KVM + You can now use Rados Block Device (RBD) to run instances on Apache CloudStack + 4.0.0-incubating. This can be done by adding a RBD pool as primary storage. Before using + RBD, ensure that Qemu is compiled with RBD enabled, and the libvirt version is at least + 0.10 with RBD enabled on the KVM host + Create a disk offering for RBD so that you can ensure that StoragePoolAllocator + chooses the RBD pool to deploy instances. +
+
+
+ Issues Fixed in 4.0.0-incubating + Many bugs include a defect number that reflects the bug number that was held in the bug + tracker run by Citrix (bugs.cloudstack.org). The Apache CloudStack project now uses Jira to manage its bugs, so + some of the bugs that are referenced here may not be available to view. However, we are + still including them for completeness. + + + + + + + + Defect + + + Description + + + + + + Many + vSphere 5.0 now has GA support. Formerly only Beta support was + provided. + + + CS-16135 + Creating volumes after upgrading from snapshot taken in 2.2.14 no longer + deletes the snapshot physically from the secondary storage. + + + CS-16122 + In a site-to-site VPN setup, alerts are generated when the VPC virtual + router is rebooted with multiple vpn connections. + + + CS-16022 + If host connection fails due to a database error, host now disconnects + and the Managerment Server id is removed. + + + CS-16011 + Name of network offering is no longer truncated due to too-narrow field + width in Add Guest Network dialog box. + + + + CS-15978 + When the virtual router and its host go down, the high availability + mechanism now works for the virtual router. + + + + CS-15921 + The 2.2.x security group script now accounts for the VMs created in the + version 2.1 timeframe. + + + + CS-15919 + A level parameter is added to the listVolumes command; therefore queries + return the response more quickly. + + + CS-15904 + Upgrade from version 2.2.14 to CloudStack-3.0.5-0.2944-rhel5 works as + expected. The upgrade script, + /usr/share/cloud/setup/db/schema-2214to30-cleanup.sql, works as + expected. + + + CS-15879 + The database upgrade from version 3.0.4 to 3.0.5 works as + expected. + + + + CS-15807 + Network label for OVM now available in UI. + + + + CS-15779 + When the thumbnail is requested, the console session will not be + terminated. + + + + CS-15778 + Fetching a VM thumbnail now gets a thumbnail of appropriate visual + dimensions. + + + + CS-15734 + KVM Snapshots no longer shows incorrect disk usage. + + + CS-15733 + The domainId parameter for the listNetworks command now lists the + resources belonging to the domain specified. + + + CS-15676 + Stopping the router no longer fails with the null pointer + exception. + + + + CS-15648 + If creating a volume from a snapshot fails, the error is reported on the + UI but the volume is stuck in the creating state. + + + + CS-15646 + createFirewallRule API no longer causes null pointer + exception. + + + CS-15628 + In a KVM host, the high availability mechanism no longer takes a long + time to migrate VMs to another KVM host if there are multiple storage + pools. + + + CS-15627 + Metadata instance-id and vm-id for existing VMs stays the same after + upgrade. + + + CS-15621 + Solved difficulty with allocating disk volumes when running multiple VM + deployment in parallel. + + + CS-15603 + CloudStack now stop the VMs when destroyVM command is + called. + + + CS-15586 + Public Vlan for an account no longer fails if multiple physical networks + are present. + + + CS-15582 + The dns-name filter is now supported for ec2-describe-instances in the + Amazon Web Services API compatibility commands. The filter maps to the name of a + user VM. + + + CS-15503 + An IP address which has static NAT rules can now be released. + Subsequently, restarting this network after it was shutdown can + succeed. + + + CS-15464 + Can now delete static route whose state is set to Revoke. + + + CS-15443 + Creating a firewall rule no longer fails with an internal server + error. + + + CS-15398 + Corrected technique for programming DNS on the user VMs. + + + CS-15356 + Internal DNS 2 entry now correctly shown in UI. + + + CS-15335 + The CloudBridge S3 Engine now connects to the database by using the + deciphered password in the db.properties file. + + + CS-15318 + UI now correctly prevents the user from stopping a VM that is in the + Starting state. + + + CS-15307 + Fixed Japanese localization of instance statuses in the Instances + menu. + + + CS-15278 + The deployment planner no longer takes long time to locate a suitable + host to deploy VMs when large number of clusters are present. + + + CS-15274 + Creating a VLAN range using Zone ID without network ID now + succeeds. + + + CS-15243 + Now check to be sure source NAT and VPN have same + provider. + + + CS-15232 + Ensure that networks using external load balancer/firewall in 2.2.14 or + earlier can properly upgrade. + + + CS-15200 + No exception when trying to attach the same volume while attaching the + first volume is in progress. + + + CS-15173 + Additional cluster can no longer be added with same VSM IP address as + another cluster. + + + CS-15167 + AWS API calls now honor the admin account's ability to view or act on the + resources owned by the regular users. + + + CS-15163 + The minimum limit is not honored when there is not enough capacity to + deploy all the VMs and the ec2-run-instances command with the -n >n1 -n2> + option is used to deploy multiple VMs. + + + CS-15157 + Can now add/enable service providers for multiple physical networks + through the UI. + + + CS-15145 + AWS API call ec2-register has better error handling for negative + cases. + + + CS-15122 + Filters now supported for AWS API call + ec2-describe-availability-zones. + + + CS-15120 + Actions column in UI of Volume page now shows action + links. + + + CS-15099 + Buttons no longer overlap text on Account Deletion confirmation page in + UI. + + + CS-15095 + Ensures you can not create a VM with a CPU frequency greater than the + host CPU frequency. + + + CS-15094 + CPU cap now set properly in VMware. + + + CS-15077 + NullPointerException is no longer observed while executing the command to + list the public IP in a basic zone created with the default shared NetScaler EIP + and ELB network offering. + + + CS-15044 + UI now provides option to view the list of instances which are part of + the guest network. + + + CS-15026 + UI in Deploy VM dialog now lists only templates or ISOs depending on + which is selected in previous dialog. + + + CS-14989 + In KVM, the Create Instance wizard now shows only templates from the + current (KVM) zone. + + + CS-14986, CS-14985 + Listing filters works as expected in the ec2-describe-volumes and + ec2-describe-snapshots commands. + + + CS-14964 + Automatically starting the Console Proxy no longer fails due to its + missing volume on the primary storage + + + CS-14907 + User is now correctly prevented from trying to download an uploaded + volume which has not yet been moved to primary storage. + + + CS-14879 + When a user VM is stopped or terminated, the static NAT associated with + this VM is now disabled. This public IP address is no longer owned by this account + and can be associated to any other user VM. + + + CS-14854 + Only the admin user can change the template permission to Public, so this + option is removed from the UI for domain Admins and regular Users. + + + CS-14817 + While checking if network has any external provider, CloudStack will + consider all providers in the network. + + + CS-14796 + When deploying a VM with ec2-run-instances, userdata is now + encoded. + + + CS-14770 + The API returns the keypair information when a VM is deployed with + sshkey. This affects the API commands related to virtual machines + (deployVirtualMachine, listVirtualMachines, ... *VirtualMachine), as well as the + corresponding AWS APIs. + + + CS-14724 + UI no longer displays the dropdown list of isolation method choices if + sdn.ovs.controller is false. + + + CS-14345 + Logout API returns XML header. + + + CS-14724 + Host IPs now associated with appropriate IPs according to traffic + type. + + + CS-14253 + Can now delete and re-create port forwarding rule on same + firewall. + + + CS-14724 + UI no longer displays the dropdown list of isolation method choices if + sdn.ovs.controller is false. + + + CS-14452 + Data disk volumes are now automatically copied from one cluster to + another. + + + CS-13539 + Windows VM can get IP after reboot. + + + CS-13537 + When user tries to delete a domain that contains sub-domains, an error + message is now sent to convey the reason for the delete failure. + + + CS-13153 + System VMs support HTTP proxy. + + + CS-12642 + Added Close button to Select Project list view popup in + UI. + + + CS-12510 + Deleting and reinserting host_details no longer causes + deadlocks. + + + CS-12407 + F5 and Netscaler - when dedicated is selected, capacity field is + disabled. + + + CS-12111 + Email validation for edit user form. + + + CS-10928 + Network read/write values now always positive numbers. + + + CS-15376, CS-15373 + The AWS APIs (EC2 and S3) now listen on the 7080 port and send request to + CloudStack on the 8080 port just as any other clients of + CloudStack. + + + CS-13944 + The CloudStack 2.2.x to 3.0.x database upgrade for multiple physical + networks is now supported. + + + CS-15300 + The admin accounts of a domain now honour the limits imposed on that + domain just like the regular accounts do. A domain admin now is not allowed to + create an unlimited number of instances, volumes, snapshots, and so + on. + + + CS-15396 + The CloudStack database now contain the UUD information after the 2.2.14 + to 3.0.4 upgrade. + + + CS-15450 + Upgrade from 2.2.14 to 3.0.4 no longer fails on a VMware + host. + + + CS-15449 + Running cloudstack-aws-api-register no longer fails with the "User + registration failed with error: [Errno 113] No route to host" + error. + + + CS-15455 + The iptable rules are configured to open the awsapi port (7080) as part + of the installation. + + + CS-15429 + While creating an instance with data volume, disk offering also is + considered while checking the account limit on volume resources. + + + CS-15414 + After the 2.2.14 to 3.0.4 upgrade, the value of the global parameter + xen.guest.network.device is now decrypted before setting the traffic + label. + + + CS-15382 + During 2.2.14 to 3.0.4 upgrade, the hosts no longer go to the Alert state + if destroyed networks existed with non-existent tags prior to + upgrade. + + + CS-15323 + CloudStack supports the following Citrix XenServer hotfixes: XS602E003, + XS602E004, and XS602E005. + + + CS-15430 + Create snapshot now fails if creating a snapshot exceeds the snapshot + resource limit for a domain admin or a user account. + + + CS-14256 + Virtual Router no longer remains in starting state for subdomain or user + on a KVM 3.0.1 prerlease host on RHEL 6.2. + + + CS-7495 + Implemented a variety of Xen management host improvements. + + + CS-8105 + NFS v4 for primary storage now works as expected on KVM + hosts. + + + CS-9989 + The error messages returned during VM deployment failure will have much + more details than before. + + + CS-12584 + You can no longer add security groups not supported by the hypervisor in + use. + + + CS-12705 + When creating a Network offering by using SRX as the service provider for + SourceNAT servcies, an option is given in the CloudStack UI now to set the + source_nat type to "per Zone"/"per account". + + + CS-12782 + Assigning a VM from Basic to Advanced zone no longer ignores the network + ID. A warning message is displayed for VM movements across zones. + + + CS-12591 + Broadcast Address on the Second Public IP NIC is now + corrected. + + + CS-13272 + When a user is deleted, all the associated properties, such as IPs and + virtual routers, are now deleted. + + + CS-13377 + Creating template from a root disk of a stopped instance now provides an + option to make it a "Featured template". + + + CS-13500 + Reaching the first guest VM by using its public IP from the second guest + VM no longer fails. + + + CS-13853 + The default gateway can no longer be 0.0.0.0 in the Secondary Storage VM + (SSVM). + + + CS-13863 + The queryAsyncJobResult command in XML format now returns the correct + UUIDs. + + + CS-13867 + Corrected CSP xenserver-cloud-supp.tgz for XenServer 5.6 and + 6.0. + + + CS-13904 + Labels and values for the service offerings CPU and memory are now + consistent. + + + CS-13998 + The SSVM kernel panic issue is fixed on XenServer. + + + CS-14090 + The issue is fixed where running the VMware snapshots randomly fails with + the ArrayIndexOutOfBoundsException error. + + + CS-14021 + The java.lang.OutOfMemoryError is fixed on the Management + Server. + + + CS-14025 + The Python Eggs are provided to easily package the test client for each + branch of CloudStack. + + + CS-14068 + Resetting the VM password through the CloudStack UI no longer causes any + error. + + + CS-14156 + The pod which has the administrator's virtual router is no longer + selected while creating the virtual routers for guests. + + + CS-14182 + The users can now delete their ISOs as normal users. + + + CS-14185 + The listOSTypes API now filters out the types of operating system by + using the keywords. + + + CS-14204 + The cloud-setup-bonding.sh command no longer generates the "command not + found" error. + + + CS-14214 + The Specify VLAN option cannot be enabled now for an isolated Network + offering with SourceNAT enabled. + + + CS-14234 + Sending project invite email to an account now requires SMTP configured + in CloudStack. + + + CS-14237 + The garbage collector of the primary storage no longer fails when the + first host in the cluster is not up. + + + CS-14241 + Custom Volume Disk Offering is now matching the Global configuration + value. + + + CS-14270 + The listNetworks API no longer assumes that the broadcast type is always + VLAN. + + + CS-14319 + The internal name of the VM is no longer present in the error message + that is displayed to a domain administrator. + + + CS-14321 + The listVolumes API call now returns a valid value for the isExtractable + parameter for the ISO-derived disk and data disk volumes. + + + CS-14323 + Invalid API calls will now give valid response in json/xml + format. + + + CS-14339 + Custom Disk Size will now allow values larger than 100GB. + + + CS-14357 + The ConsoleProxyLoadReportCommand is no longer fired + continuously. + + + CS-14421 + Fixed the issue of virtual router deployments. The DHCP entries can now + be assigned to the router. + + + CS-14555 + Unzipped downloaded template MD5SUM will no longer override the zipped + template MD5SUM in the database. + + + CS-14598 + The complete screen of the running VM is now displayed in the console + proxy. + + + CS-14600 + Windows or Linux based consoles are no longer lost upon rebooting + VMs. + + + CS-14784 + Multiple subnets with the same VLAN now work as expected. + + + CS-13303, 14874, 13897, 13944, 14088, 14190 + A variety of upgrade issues have been fixed in release + 3.0.3. + + + CS-15080 + Setting a private network on a VLAN for VMWare environment is now + supported. + + + CS-15168 + The console proxy now works as expected and no exception is shown in the + log after upgrading from version 2.2.14 to 3.0.2. + + + CS-15172 + Version 3.0.2 now accepts the valid public key. + + + + +
+
+ Known Issues in 4.0.0-incubating + + + + + + + + Issue ID + + + Description + + + + + + CLOUDSTACK-301 + Nexus 1000v DVS integration is not functional + This source code release includes some partial functionality to support the + Cisco Nexus 1000v Distributed Virtual Switch within a VMware hypervisor + environment. The functionality is not complete at this time. + + + + CLOUDSTACK-368 + OVM - cannot create guest VM + This source code release has regressed from the CloudStack 2.2.x code + and is unable to support Oracle VM (OVM). + + + + CLOUDSTACK-279 + Deleting a project fails when executed by the regular user. This works as + expected for root/domain admin. To workaround, perform either of the + following: + + Use the account cleanup thread which will eventually complete the project + deletion. + + + Execute the call as the root/domain admin on behalf of the regular + user. + + + + + + CS-16067 + The command=listTags&key=city command does not work as expected. The + command does not return tags for the resources of the account with the tag, city + + + + + CS-16063 + The current values of volumes and snapshots are incorrect when using KVM + as a host. To fix this, the database upgrade codes, volumes.size and + snapshots.size, should be changed to show the virtual sizes. + + + + CS-16058 + Null pointer Exception while deleting the host after moving the host to + maintenance state. + + + + CS-16045 + Only the root administrator can handle the API keys. The domain + administrators are not allowed to create, delete, or retrieve API keys for the + users in their domain. + + + + CS-16019 + CIDR list in the Add VPN Customer Gateway dialog does not prompt the user + that they can provide a comma separated CIDRs if multiple CIDRs have to be + supplied. + + + + CS-16015 + Deleting a network is not supported when its network providers are + disabled. + + + + CS-16012 + Unable to delete a zone in the UI because the necessary cleanup cannot be + completed. When the hosts are removed, the expunge process fails to delete the + volumes as no hosts are present to send the commands to. Therefore, the storage + pool removal fails, and zone can't be cleaned and deleted. + + + + CS-16011 + Name of network offering might be truncated due to too-narrow field width + in Add Guest Network dialog box. + + + + CS-15789 + Invalid global setting prevents management server to restart. For + example, if you configure the "project.invite.timeout" parameter to "300" and + attempt to restart management server, it fails without throwing a warning or + setting the value to the default. + + + + CS-15749 + Restarting VPC is resulting in intermittent connection loss to the port + forwarding and StaticNAT rules. + + + + CS-15690 + The IpAssoc command failed as a part of starting the virtual router, but + the final start result is reported as succes. + + + + CS-15672, CS-15635 + The FQDN of the VM is not configured if it is deployed as a part of + default shared network and isolated guest network + (DefaultIsolatedNetworkOfferingWithSourceNatService). + + + + CS-15634 + The FQDN of a VM that is deployed as a part of both a shared network and + default isolated guest network has the suffix of the shared network instead of the + default isolated guest network. + + + + CS-15576 + Stopping a VM on XenServer creates a backlog of API commands. For + example, the Attach volume calls become delayed while waiting for the + stopVirtualMachine command to be executed. + + + + CS-15569 + Misleading error message in the exception when creating a StaticNAT rule + fails in a VPC. + + + + CS-15566 + External device such as Netscaler is not supported in VPC. + + + CS-15557 + Intermittent traffic loss in the VPN connection if Juniper is the remote + router and the life time is 300 seconds. + + + + CS-15361 + Egress rules are not working in NetScaler loadbalancer. + + + + CS-15163 + The minimum limit is not honored when there is not enough capacity to + deploy all the VMs and the ec2-run-instances command with the -n >n1 -n2> + option is used to deploy multiple VMs. + + + CS-15105 + The cloud-sysvmadm script does not work if the integration.api.port + parameter is set to any port other than 8096. + + + CS-15092 + Connecting to the guest VMs through SSH is extremely slow, and it results + in connection timeout. + + + CS-15037 + Hairpin NAT is not supported when NetScaler is used for + EIP. + + + CS-15009 + The port_profile table will not be populated with port profile + information. In this release, CloudStack directly connects to the VSM for all the + port profile operations; therefore, no port profile information is + cached. + + + CS-14939 + Adding a VMware cluster is not supported when the Management Network is + migrated to the Distributed Virtual Switch environment. + + + CS-14780 + You are allowed to ping the elastic IP address of the VM even though no + ingress rule is set that allows the ICMP protocol. + + + CS-14756 + Installing KVM on RHEL 6.2 will result in unreliable network performance. + Workaround: blacklist vhost-net. Edit /etc/modprobe.d/blacklist-kvm.conf and + include vhost-net. + + + CS-14346 + The UpdateVirtualMachine API call does not check whether the VM is + stopped. Therefore, stop the VM manually before issuing this call. + + + CS-14303 (was 14537) + The IP addresses for a shared network are still being consumed even if no + services are defined for that network. + + + CS-14296 (was 14530) + OVM: Network traffic labels are not supported. + + + CS-14291 (was 14523) + The EIP/ELB network offering for basic zones does not support multiple + NetScalers. + + + CS-14275 (was 14506) + F5: Unable to properly remove a F5 device. + + + CS-14201 (was 14430) + VMWare: Template sizes are being reported different depending on whether + the primary storage is using ISCSI or NFS. + + + CS-13758 (was 13963) + vSphere: template download from templates created off of the root volume + does not work properly. + + + CS-13733 (was 13935) + vSphere: detaching an ISO from a restored VM instance + fails. + + + CS-13682 (was 13883) + Multiple NetScalers are not supported in Basic Networking. + + + CS-13599 (was 13359) + Programming F5/NetScaler rules can be better optimized. + + + CS-13337 (was 13518) + Security Groups are not supported in Advanced Networking + + + CS-13173 (was 13336) + vSphere: cross cluster volume migration does not work + properly. + + + CS-12714 (was 12840) + Capacity view is not available for pods or clusters. + + + CS-12624 (was 12741) + vSphere: maintenance mode will not live migrate system VM to another + host. + + + + CS-15476 + + + The 2.2.14 to 4.0.0-incubating upgrade fails if multiple untagged physical + networks exist before the upgrade. + + + + + CS-15407 + + + After the 2.2.14 to 4.0.0-incubating upgrade, VLAN allocation on multiple + physical networks does not happen as expected. + To workaround this issue, follow the instructions given below: + + + Revert to your 2.2.14 setup. + + + Stop all the VMs with the isolated virtual networks in your cloud + setup. + + + Run following query to find if any networks still have the NICs + allocated: + + + Check if any virtual guest networks have the NICs allocated: + #SELECT DISTINCT op.id from `cloud`.`op_networks` op JOIN `cloud`.`networks` n on op.id=n.id WHERE nics_count != 0 AND guest_type = 'Virtual'; + + + If this returns any network IDs, then ensure the following: + + + All the VMs are stopped. + + + No new VM is started. + + + Shutdown the Management Server. + + + + + Remove the NICs count for the virtual network IDs returned in step + (a), and set the NIC count to 0: + UPDATE `cloud`.`op_networks` SET nics_count = 0 WHERE id = enter id of virtual network + + + Restart the Management Server, and wait for all the networks to shut + down. + + Networks shutdown is determined by the network.gc.interval and + network.gc.wait parameters. + + + + + + Ensure that all the networks are shut down and all the guest VNETs are + free. + + + Run the upgrade script. + This allocates all your guest VNET ranges to the first physical + network. + + + By using the updatePhysicalNetwork API, reconfigure the VNET ranges for + each physical network as desired. + + + Start all the VMs. + + + + + + + CS-14680 + + + CloudStack and LDAP user validation cannot happen simultaneously because the + user password is hashed and stored in the database, and LDAP requires the + passwords in plain text. + To work with the LDAP user, the MD5 hash should be disabled in the login + process by commenting the following variable in sharedFunctions.js file available + at /usr/share/cloud/management/webapps/client/scripts, and restart the + cloud-management service. + var md5HashedLogin = false; + However, if md5HashedLogin is set to false, the end user can login with the + LDAP credentials but not with the CloudStack user credentials. + + + + CS-14346 + The UpdateVirtualMachine API call does not check whether the VM is + stopped. Therefore, stop the VM manually before issuing this call. + + + CS-15130 + Data disk volumes are not automatically copied from one cluster to + another. + + + CS-14780 + You are allowed to ping the elastic IP address of the VM even though no + ingress rule is set that allows the ICMP protocol. + + + CS-14939 + Adding a VMware cluster is not supported when the Management Network is + migrated to the Distributed Virtual Switch environment. + + + CS-15009 + The port_profile table will not be populated with port profile + information. In this release, CloudStack directly connects to the VSM for all the + port profile operations; therefore, no port profile information is + cached. + + + CS-15037 + Hairpin NAT is not supported when NetScaler is used for + EIP. + + + CS-15092 + Connecting to the guest VMs through SSH is extremely slow, and it results + in connection timeout. + + + CS-15105 + The cloud-sysvmadm script does not work if the integration.api.port + parameter is set to any port other than 8096. + + + CS-15163 + The minimum limit is not honored when there is not enough capacity to + deploy all the VMs and the ec2-run-instances command with the -n >n1 -n2> + option is used to deploy multiple VMs. + + + + +
+
+ + API Changes from 3.0.2 to 4.0.0-incubating +
+ New API Commands in 4.0.0-incubating + + + createCounter (Adds metric counter) + + + deleteCounter (Deletes a counter) + + + listCounters (List the counters) + + + createCondition (Creates a condition) + + + deleteCondition (Removes a condition) + + + listConditions (List Conditions for the specific user) + + + createTags. Add tags to one or more resources. Example: + command=createTags +&resourceIds=1,10,12 +&resourceType=userVm +&tags[0].key=region +&tags[0].value=canada +&tags[1].key=city +&tags[1].value=Toronto + + + deleteTags. Remove tags from one or more resources. Example: + command=deleteTags +&resourceIds=1,12 +&resourceType=Snapshot +&tags[0].key=city + + + listTags (Show currently defined resource tags) + + + createVPC (Creates a VPC) + + + listVPCs (Lists VPCs) + + + deleteVPC (Deletes a VPC) + + + updateVPC (Updates a VPC) + + + restartVPC (Restarts a VPC) + + + createVPCOffering (Creates VPC offering) + + + updateVPCOffering (Updates VPC offering) + + + deleteVPCOffering (Deletes VPC offering) + + + listVPCOfferings (Lists VPC offerings) + + + createPrivateGateway (Creates a private gateway) + + + listPrivateGateways (List private gateways) + + + deletePrivateGateway (Deletes a Private gateway) + + + createNetworkACL (Creates a ACL rule the given network (the network has to belong to + VPC)) + + + deleteNetworkACL (Deletes a Network ACL) + + + listNetworkACLs (Lists all network ACLs) + + + createStaticRoute (Creates a static route) + + + deleteStaticRoute (Deletes a static route) + + + listStaticRoutes (Lists all static routes) + + + createVpnCustomerGateway (Creates site to site vpn customer gateway) + + + createVpnGateway (Creates site to site vpn local gateway) + + + createVpnConnection (Create site to site vpn connection) + + + deleteVpnCustomerGateway (Delete site to site vpn customer gateway) + + + deleteVpnGateway (Delete site to site vpn gateway) + + + deleteVpnConnection (Delete site to site vpn connection) + + + updateVpnCustomerGateway (Update site to site vpn customer gateway) + + + resetVpnConnection (Reset site to site vpn connection) + + + listVpnCustomerGateways (Lists site to site vpn customer gateways) + + + listVpnGateways (Lists site 2 site vpn gateways) + + + listVpnConnections (Lists site to site vpn connection gateways) + + + markDefaultZoneForAccount (Marks a default zone for the current account) + + + uploadVolume (Uploads a data disk) + + +
+
+ Changed API Commands in 4.0.0-incubating + + + + + + + API Commands + Description + + + + + + copyTemplate + prepareTemplate + registerTemplate + updateTemplate + createProject + activateProject + suspendProject + updateProject + listProjectAccounts + createVolume + migrateVolume + attachVolume + detachVolume + uploadVolume + createSecurityGroup + registerIso + copyIso + updateIso + createIpForwardingRule + listIpForwardingRules + createLoadBalancerRule + updateLoadBalancerRule + createSnapshot + + + The commands in this list have a single new response parameter, and no other + changes. + New response parameter: tags(*) + + Many other commands also have the new tags(*) parameter in addition to other + changes; those commands are listed separately. + + + + + rebootVirtualMachine + attachIso + detachIso + listLoadBalancerRuleInstances + resetPasswordForVirtualMachine + changeServiceForVirtualMachine + recoverVirtualMachine + startVirtualMachine + migrateVirtualMachine + deployVirtualMachine + assignVirtualMachine + updateVirtualMachine + restoreVirtualMachine + stopVirtualMachine + destroyVirtualMachine + + + The commands in this list have two new response parameters, and no other + changes. + New response parameters: keypair, tags(*) + + + + + listSecurityGroups + listFirewallRules + listPortForwardingRules + listSnapshots + listIsos + listProjects + listTemplates + listLoadBalancerRules + + The commands in this list have the following new parameters, and no other + changes. + New request parameter: tags (optional) + New response parameter: tags(*) + + + + + listF5LoadBalancerNetworks + listNetscalerLoadBalancerNetworks + listSrxFirewallNetworks + updateNetwork + + + The commands in this list have three new response parameters, and no other + changes. + New response parameters: canusefordeploy, vpcid, tags(*) + + + + + createZone + updateZone + + The commands in this list have the following new parameters, and no other + changes. + New request parameter: localstorageenabled (optional) + New response parameter: localstorageenabled + + + + listZones + New response parameter: localstorageenabled + + + + rebootRouter + changeServiceForRouter + startRouter + destroyRouter + stopRouter + + The commands in this list have two new response parameters, and no other + changes. + New response parameters: vpcid, nic(*) + + + + updateAccount + disableAccount + listAccounts + markDefaultZoneForAccount + enableAccount + + The commands in this list have three new response parameters, and no + other changes. + New response parameters: vpcavailable, vpclimit, vpctotal + + + listRouters + + New request parameters: forvpc (optional), vpcid (optional) + New response parameters: vpcid, nic(*) + + + + listNetworkOfferings + + New request parameters: forvpc (optional) + New response parameters: forvpc + + + + listVolumes + + New request parameters: details (optional), tags (optional) + New response parameters: tags(*) + + + + addTrafficMonitor + + New request parameters: excludezones (optional), includezones + (optional) + + + + createNetwork + + New request parameters: vpcid (optional) + New response parameters: canusefordeploy, vpcid, tags(*) + + + + listPublicIpAddresses + + New request parameters: tags (optional), vpcid (optional) + New response parameters: vpcid, tags(*) + + + + listNetworks + + New request parameters: canusefordeploy (optional), forvpc (optional), tags + (optional), vpcid (optional) + New response parameters: canusefordeploy, vpcid, tags(*) + + + + restartNetwork + + New response parameters: vpcid, tags(*) + + + + enableStaticNat + + New request parameter: networkid (optional) + + + + createDiskOffering + + New request parameter: storagetype (optional) + New response parameter: storagetype + + + + listDiskOfferings + + New response parameter: storagetype + + + + updateDiskOffering + + New response parameter: storagetype + + + + createFirewallRule + + Changed request parameters: ipaddressid (old version - optional, new version - + required) + New response parameter: tags(*) + + + + listVirtualMachines + + New request parameters: isoid (optional), tags (optional), templateid + (optional) + New response parameters: keypair, tags(*) + + + + updateStorageNetworkIpRange + + New response parameters: id, endip, gateway, netmask, networkid, podid, + startip, vlan, zoneid + + + + reconnectHost + A new response parameter is added: hahost. + + + addCluster + The following request parameters are added: + + + vsmipaddress (optional) + + + vsmpassword (optional) + + + vsmusername (optional) + + + The following parameter is made mandatory: podid + + + + listVolumes + A new response parameter is added: status + + + migrateVolume + A new response parameter is added: status + + + prepareHostForMaintenance + A new response parameter is added: hahost. + + + addSecondaryStorage + A new response parameter is added: hahost. + + + enableAccount + A new response parameter is added: defaultzoneid + + + attachVolume + A new response parameter is added: status + + + cancelHostMaintenance + A new response parameter is added: hahost + + + addSwift + A new response parameter is added: hahost + + + listSwifts + A new response parameter is added: hahost + + + listExternalLoadBalancers + A new response parameter is added: hahost + + + createVolume + A new response parameter is added: status + + + listCapabilities + A new response parameter is added: + customdiskofferingmaxsize + + + disableAccount + A new response parameter is added: defaultzoneid + + + deployVirtualMachine + A new request parameter is added: startvm (optional) + + + deleteStoragePool + A new request parameter is added: forced (optional) + + + updateAccount + A new response parameter is added: defaultzoneid + + + addHost + A new response parameter is added: hahost + + + updateHost + A new response parameter is added: hahost + + + detachVolume + A new response parameter is added: status + + + listAccounts + A new response parameter is added: defaultzoneid + + + listHosts + A new response parameter is added: hahostA new request + parameter is added: hahost (optional) + + + + +
+
+
diff --git a/docs/en-US/about-clusters.xml b/docs/en-US/about-clusters.xml index b01fcfcea1d..aa8604ccd52 100644 --- a/docs/en-US/about-clusters.xml +++ b/docs/en-US/about-clusters.xml @@ -24,9 +24,25 @@
About Clusters - A cluster provides a way to group hosts. To be precise, a cluster is a XenServer server pool, a set of KVM servers, a set of OVM hosts, or a VMware cluster preconfigured in vCenter. The hosts in a cluster all have identical hardware, run the same hypervisor, are on the same subnet, and access the same shared primary storage. Virtual machine instances (VMs) can be live-migrated from one host to another within the same cluster, without interrupting service to the user. - A cluster is the third-largest organizational unit within a &PRODUCT; deployment. Clusters are contained within pods, and pods are contained within zones. Size of the cluster is limited by the underlying hypervisor, although the &PRODUCT; recommends less in most cases; see Best Practices. - A cluster consists of one or more hosts and one or more primary storage servers. + + A cluster provides a way to group hosts. To be precise, a cluster is a + XenServer server pool, a set of KVM servers, , or a + VMware cluster preconfigured in vCenter. The hosts in a cluster all + have identical hardware, run the same hypervisor, are on the same subnet, + and access the same shared primary storage. Virtual machine instances + (VMs) can be live-migrated from one host to another within the same + cluster, without interrupting service to the user. + + + A cluster is the third-largest organizational unit within a &PRODUCT; + deployment. Clusters are contained within pods, and pods are contained + within zones. Size of the cluster is limited by the underlying hypervisor, + although the &PRODUCT; recommends less in most cases; see Best Practices. + + + A cluster consists of one or more hosts and one or more primary storage + servers. + @@ -34,6 +50,14 @@ cluster-overview.png: Structure of a simple cluster &PRODUCT; allows multiple clusters in a cloud deployment. - Even when local storage is used, clusters are still required. In this case, there is just one host per cluster. - When VMware is used, every VMware cluster is managed by a vCenter server. Administrator must register the vCenter server with &PRODUCT;. There may be multiple vCenter servers per zone. Each vCenter server may manage multiple VMware clusters. + + Even when local storage is used exclusively, clusters are still required + organizationally, even if there is just one host per cluster. + + + When VMware is used, every VMware cluster is managed by a vCenter server. + Administrator must register the vCenter server with &PRODUCT;. There may + be multiple vCenter servers per zone. Each vCenter server may manage + multiple VMware clusters. +
diff --git a/docs/en-US/about-hosts.xml b/docs/en-US/about-hosts.xml index 2002a6a74d0..87b6bab1ee1 100644 --- a/docs/en-US/about-hosts.xml +++ b/docs/en-US/about-hosts.xml @@ -28,7 +28,8 @@ The host is the smallest organizational unit within a &PRODUCT; deployment. Hosts are contained within clusters, clusters are contained within pods, and pods are contained within zones. Hosts in a &PRODUCT; deployment: - Provide the CPU, memory, storage, and networking resources needed to host the virtual machines + Provide the CPU, memory, storage, and networking resources needed to host the virtual + machines Interconnect using a high bandwidth TCP/IP network and connect to the Internet May reside in multiple data centers across different geographic locations May have different capacities (different CPU speeds, different amounts of RAM, etc.), although the hosts within a cluster must all be homogeneous diff --git a/docs/en-US/about-password-encryption.xml b/docs/en-US/about-password-encryption.xml new file mode 100644 index 00000000000..3cd84d19508 --- /dev/null +++ b/docs/en-US/about-password-encryption.xml @@ -0,0 +1,65 @@ + + +%BOOK_ENTITIES; +]> + +
+ About Password and Key Encryption + &PRODUCT; stores several sensitive passwords and secret keys that are used to provide + security. These values are always automatically encrypted: + + + Database secret key + + + Database password + + + SSH keys + + + Compute node root password + + + VPN password + + + User API secret key + + + VNC password + + + &PRODUCT; uses the Java Simplified Encryption (JASYPT) library. The data values are + encrypted and decrypted using a database secret key, which is stored in one of &PRODUCT;’s + internal properties files along with the database password. The other encrypted values listed + above, such as SSH keys, are in the &PRODUCT; internal database. + Of course, the database secret key itself can not be stored in the open – it must be + encrypted. How then does &PRODUCT; read it? A second secret key must be provided from an + 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 + 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 + &PRODUCT; installation. They are all parameters to the &PRODUCT; database setup script + (cloud-setup-databases). The default values are file, password, and password. It is, of course, + highly recommended that you change these to more secure keys. +
diff --git a/docs/en-US/about-security-groups.xml b/docs/en-US/about-security-groups.xml new file mode 100644 index 00000000000..85e8477cfb1 --- /dev/null +++ b/docs/en-US/about-security-groups.xml @@ -0,0 +1,35 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ About Security Groups + Security groups provide a way to isolate traffic to VMs. A security group is a group of VMs that filter their incoming and outgoing traffic according to a set of rules, called ingress and egress rules. These rules filter network traffic according to the IP address that is attempting to communicate with the VM. Security groups are particularly useful in zones that use basic networking, because there is a single guest network for all guest VMs. In &PRODUCT; 3.0.3 - 3.0.5, security groups are supported only in zones that use basic networking. + In a zone that uses advanced networking, you can instead define multiple guest networks to isolate traffic to VMs. + + + Each &PRODUCT; account comes with a default security group that denies all inbound traffic and allows all outbound traffic. The default security group can be modified so that all new VMs inherit some other desired set of rules. + Any &PRODUCT; user can set up any number of additional security groups. When a new VM is launched, it is assigned to the default security group unless another user-defined security group is specified. A VM can be a member of any number of security groups. Once a VM is assigned to a security group, it remains in that group for its entire lifetime; you can not move a running VM from one security group to another. + You can modify a security group by deleting or adding any number of ingress and egress rules. When you do, the new rules apply to all VMs in the group, whether running or stopped. + If no ingress rules are specified, then no traffic will be allowed in, except for responses to any traffic that has been allowed out through an egress rule. +
diff --git a/docs/en-US/about-virtual-networks.xml b/docs/en-US/about-virtual-networks.xml index 225717e59a6..4dbd2018b27 100644 --- a/docs/en-US/about-virtual-networks.xml +++ b/docs/en-US/about-virtual-networks.xml @@ -27,4 +27,4 @@ -
+ diff --git a/docs/en-US/accounts.xml b/docs/en-US/accounts.xml index 08404c82c96..aa62f680452 100644 --- a/docs/en-US/accounts.xml +++ b/docs/en-US/accounts.xml @@ -22,17 +22,8 @@ under the License. --> -<<<<<<< HEAD Accounts -======= -
- Accounts - - - -
->>>>>>> master diff --git a/docs/en-US/add-clusters-ovm.xml b/docs/en-US/add-clusters-ovm.xml index 11e1a13555f..aa07dfa6506 100644 --- a/docs/en-US/add-clusters-ovm.xml +++ b/docs/en-US/add-clusters-ovm.xml @@ -26,7 +26,7 @@ Add Cluster: OVM To add a Cluster of hosts that run Oracle VM (OVM): - Add a companion non-OVM cluster to the Pod. This cluster provides an environment where the CloudPlatform System VMs can run. You should have already installed a non-OVM hypervisor on at least one Host to prepare for this step. Depending on which hypervisor you used: + Add a companion non-OVM cluster to the Pod. This cluster provides an environment where the &PRODUCT; System VMs can run. You should have already installed a non-OVM hypervisor on at least one Host to prepare for this step. Depending on which hypervisor you used: For VMWare, follow the steps in Add Cluster: vSphere. When finished, return here and continue with the next step. For KVM or XenServer, follow the steps in . When finished, return here and continue with the next step diff --git a/docs/en-US/add-clusters-vsphere.xml b/docs/en-US/add-clusters-vsphere.xml index d9e78d28476..6b2dff2a595 100644 --- a/docs/en-US/add-clusters-vsphere.xml +++ b/docs/en-US/add-clusters-vsphere.xml @@ -91,19 +91,8 @@ vCenter Datacenter. Enter the vCenter datacenter that the cluster is in. For example, "cloud.dc.VM". - If you have enabled Nexus dvSwitch in the environment, the following parameters for - dvSwitch configuration are displayed: - Nexus dvSwitch IP Address: The IP address of the Nexus VSM appliance. - - - Nexus dvSwitch Username: The username required to access the Nexus VSM - applicance. - - - Nexus dvSwitch Password: The password associated with the username specified - above. diff --git a/docs/en-US/add-more-clusters.xml b/docs/en-US/add-more-clusters.xml index a2e41e38f84..894b4d80737 100644 --- a/docs/en-US/add-more-clusters.xml +++ b/docs/en-US/add-more-clusters.xml @@ -24,6 +24,6 @@ so before you begin adding hosts to the cloud, you must add at least one cluster. - + diff --git a/docs/en-US/add-primary-storage.xml b/docs/en-US/add-primary-storage.xml index 9c7ad3dc9cf..a43567f5562 100644 --- a/docs/en-US/add-primary-storage.xml +++ b/docs/en-US/add-primary-storage.xml @@ -94,7 +94,7 @@ Tags (optional). The comma-separated list of tags for this storage device. It should - be an equivalent set or superset of the tags on your disk offerings + be an equivalent set or superset of the tags on your disk offerings. The tag sets on primary storage across clusters in a Zone must be identical. For diff --git a/docs/en-US/added-API-commands-4-0.xml b/docs/en-US/added-API-commands-4-0.xml new file mode 100644 index 00000000000..2d86ba4d6dc --- /dev/null +++ b/docs/en-US/added-API-commands-4-0.xml @@ -0,0 +1,164 @@ + + +%BOOK_ENTITIES; +]> + +
+ Added API Commands in 4.0.0-incubating + + + createCounter (Adds metric counter) + + + deleteCounter (Deletes a counter) + + + listCounters (List the counters) + + + createCondition (Creates a condition) + + + deleteCondition (Removes a condition) + + + listConditions (List Conditions for the specific user) + + + createTags. Add tags to one or more resources. Example: + command=createTags +&resourceIds=1,10,12 +&resourceType=userVm +&tags[0].key=region +&tags[0].value=canada +&tags[1].key=city +&tags[1].value=Toronto + + + deleteTags. Remove tags from one or more resources. Example: + command=deleteTags +&resourceIds=1,12 +&resourceType=Snapshot +&tags[0].key=city + + + listTags (Show currently defined resource tags) + + + createVPC (Creates a VPC) + + + listVPCs (Lists VPCs) + + + deleteVPC (Deletes a VPC) + + + updateVPC (Updates a VPC) + + + restartVPC (Restarts a VPC) + + + createVPCOffering (Creates VPC offering) + + + updateVPCOffering (Updates VPC offering) + + + deleteVPCOffering (Deletes VPC offering) + + + listVPCOfferings (Lists VPC offerings) + + + createPrivateGateway (Creates a private gateway) + + + listPrivateGateways (List private gateways) + + + deletePrivateGateway (Deletes a Private gateway) + + + createNetworkACL (Creates a ACL rule the given network (the network has to belong to + VPC)) + + + deleteNetworkACL (Deletes a Network ACL) + + + listNetworkACLs (Lists all network ACLs) + + + createStaticRoute (Creates a static route) + + + deleteStaticRoute (Deletes a static route) + + + listStaticRoutes (Lists all static routes) + + + createVpnCustomerGateway (Creates site to site vpn customer gateway) + + + createVpnGateway (Creates site to site vpn local gateway) + + + createVpnConnection (Create site to site vpn connection) + + + deleteVpnCustomerGateway (Delete site to site vpn customer gateway) + + + deleteVpnGateway (Delete site to site vpn gateway) + + + deleteVpnConnection (Delete site to site vpn connection) + + + updateVpnCustomerGateway (Update site to site vpn customer gateway) + + + resetVpnConnection (Reset site to site vpn connection) + + + listVpnCustomerGateways (Lists site to site vpn customer gateways) + + + listVpnGateways (Lists site 2 site vpn gateways) + + + listVpnConnections (Lists site to site vpn connection gateways) + + + enableCiscoNexusVSM (Enables Nexus 1000v dvSwitch in &PRODUCT;.) + + + disableCiscoNexusVSM (Disables Nexus 1000v dvSwitch in &PRODUCT;.) + + + deleteCiscoNexusVSM (Deletes Nexus 1000v dvSwitch in &PRODUCT;.) + + + listCiscoNexusVSMs (Lists the control VLAN ID, packet VLAN ID, and data VLAN ID, as well + as the IP address of the Nexus 1000v dvSwitch.) + + +
diff --git a/docs/en-US/added-API-commands.xml b/docs/en-US/added-API-commands.xml index 237c524b75f..208aac29dc2 100644 --- a/docs/en-US/added-API-commands.xml +++ b/docs/en-US/added-API-commands.xml @@ -19,153 +19,9 @@ under the License. -->
- Added API commands - Added in 4.0 - - - createCounter (Adds metric counter) - - - deleteCounter (Deletes a counter) - - - listCounters (List the counters) - - - createCondition (Creates a condition) - - - deleteCondition (Removes a condition) - - - listConditions (List Conditions for the specific user) - - - createTags. Add tags to one or more resources. Example: - command=createTags -&resourceIds=1,10,12 -&resourceType=userVm -&tags[0].key=region -&tags[0].value=canada -&tags[1].key=city -&tags[1].value=Toronto - - - deleteTags. Remove tags from one or more resources. Example: - command=deleteTags -&resourceIds=1,12 -&resourceType=Snapshot -&tags[0].key=city - - - listTags (Show currently defined resource tags) - - - createVPC (Creates a VPC) - - - listVPCs (Lists VPCs) - - - deleteVPC (Deletes a VPC) - - - updateVPC (Updates a VPC) - - - restartVPC (Restarts a VPC) - - - createVPCOffering (Creates VPC offering) - - - updateVPCOffering (Updates VPC offering) - - - deleteVPCOffering (Deletes VPC offering) - - - listVPCOfferings (Lists VPC offerings) - - - createPrivateGateway (Creates a private gateway) - - - listPrivateGateways (List private gateways) - - - deletePrivateGateway (Deletes a Private gateway) - - - createNetworkACL (Creates a ACL rule the given network (the network has to belong to - VPC)) - - - deleteNetworkACL (Deletes a Network ACL) - - - listNetworkACLs (Lists all network ACLs) - - - createStaticRoute (Creates a static route) - - - deleteStaticRoute (Deletes a static route) - - - listStaticRoutes (Lists all static routes) - - - createVpnCustomerGateway (Creates site to site vpn customer gateway) - - - createVpnGateway (Creates site to site vpn local gateway) - - - createVpnConnection (Create site to site vpn connection) - - - deleteVpnCustomerGateway (Delete site to site vpn customer gateway) - - - deleteVpnGateway (Delete site to site vpn gateway) - - - deleteVpnConnection (Delete site to site vpn connection) - - - updateVpnCustomerGateway (Update site to site vpn customer gateway) - - - resetVpnConnection (Reset site to site vpn connection) - - - listVpnCustomerGateways (Lists site to site vpn customer gateways) - - - listVpnGateways (Lists site 2 site vpn gateways) - - - listVpnConnections (Lists site to site vpn connection gateways) - - - Added in 3.0.3: - - - enableCiscoNexusVSM (Enables Nexus 1000v dvSwitch in &PRODUCT;.) - - - disableCiscoNexusVSM (Disables Nexus 1000v dvSwitch in &PRODUCT;.) - - - deleteCiscoNexusVSM (Deletes Nexus 1000v dvSwitch in &PRODUCT;.) - - - listCiscoNexusVSMs (Lists the control VLAN ID, packet VLAN ID, and data VLAN ID, as well - as the IP address of the Nexus 1000v dvSwitch.) - - - Added in 3.0.2: + Added API commands in 3.0 +
+ Added in 3.0.2 changeServiceForSystemVm @@ -173,7 +29,9 @@ system VM must be in a "Stopped" state for this command to take effect. - Added in 3.0.1: +
+
+ Added in 3.0.1 changeServiceForSystemVm @@ -181,7 +39,9 @@ system VM must be in a "Stopped" state for this command to take effect. - Added in 3.0.0: +
+
+ Added in 3.0.0 @@ -331,4 +191,5 @@ +
diff --git a/docs/en-US/added-cloudPlatform-error-codes.xml b/docs/en-US/added-error-codes.xml similarity index 98% rename from docs/en-US/added-cloudPlatform-error-codes.xml rename to docs/en-US/added-error-codes.xml index 6b1e6a355ca..dbfea263598 100644 --- a/docs/en-US/added-cloudPlatform-error-codes.xml +++ b/docs/en-US/added-error-codes.xml @@ -22,7 +22,7 @@ under the License. --> -
+
Added &PRODUCT; Error Codes You can now find the &PRODUCT;-specific error code in the exception response for each type of exception. The following list of error codes is added to the new class named CSExceptionErrorCode. These codes are applicable in &PRODUCT; 3.0.3 and later versions. @@ -128,7 +128,7 @@ 4535 : "com.cloud.exception.VirtualMachineMigrationException" - 9999 : "com.cloud.api.ServerApiException" + 9999 : "org.apache.cloudstack.api.ServerApiException" diff --git a/docs/en-US/additional-installation-options.xml b/docs/en-US/additional-installation-options.xml new file mode 100644 index 00000000000..622ef03d07e --- /dev/null +++ b/docs/en-US/additional-installation-options.xml @@ -0,0 +1,31 @@ + + +%BOOK_ENTITIES; +]> + + + + + Additional Installation Options + The next few sections describe &PRODUCT; features above and beyond the basic deployment options. + + + + diff --git a/docs/en-US/admin-guide.xml b/docs/en-US/admin-guide.xml index 512f7a9846a..f1b0327e9d1 100644 --- a/docs/en-US/admin-guide.xml +++ b/docs/en-US/admin-guide.xml @@ -88,5 +88,5 @@ - + diff --git a/docs/en-US/adv-zone-topology-req.xml b/docs/en-US/adv-zone-topology-req.xml new file mode 100644 index 00000000000..3764e926ebe --- /dev/null +++ b/docs/en-US/adv-zone-topology-req.xml @@ -0,0 +1,25 @@ + + +%BOOK_ENTITIES; +]> + +
+ Advanced Zone Topology Requirements + With Advanced Networking, separate subnets must be used for private and public + networks. +
diff --git a/docs/en-US/advanced-zone-configuration.xml b/docs/en-US/advanced-zone-configuration.xml index 84649db96ef..03a082f21ac 100644 --- a/docs/en-US/advanced-zone-configuration.xml +++ b/docs/en-US/advanced-zone-configuration.xml @@ -84,10 +84,6 @@ These traffic labels will be defined only for the hypervisor selected for the first cluster. For all other hypervisors, the labels can be configured after the zone is created. - (VMware only) If you have enabled Nexus dvSwitch in the environment, you must specify - the corresponding Ethernet port profile names as network traffic label for each traffic type - on the physical network. For more information on Nexus dvSwitch, see Configuring a vSphere - Cluster with Nexus 1000v Virtual Switch. Click Next. @@ -184,9 +180,9 @@ KVM Installation and Configuration - + To configure the first host, enter the following, then click Next: @@ -223,7 +219,7 @@ Protocol. For XenServer, choose either NFS, iSCSI, - or PreSetup. For KVM, choose NFS or SharedMountPoint. For vSphere choose either VMFS + or PreSetup. For KVM, choose NFS, SharedMountPoint, CLVM, and RBD. For vSphere choose either VMFS (iSCSI or FiberChannel) or NFS. The remaining fields in the screen vary depending on what you choose here. diff --git a/docs/en-US/alerts.xml b/docs/en-US/alerts.xml index 9f926cf3080..ebea4b808a4 100644 --- a/docs/en-US/alerts.xml +++ b/docs/en-US/alerts.xml @@ -1,9 +1,8 @@ - %BOOK_ENTITIES; ]> - - - Using the API - - + + + Calling the &PRODUCT; API - - diff --git a/docs/en-US/api-reference.xml b/docs/en-US/api-reference.xml index cab3adadfab..983e76f2aa5 100644 --- a/docs/en-US/api-reference.xml +++ b/docs/en-US/api-reference.xml @@ -18,9 +18,7 @@
API Reference Documentation - 2.2 API Reference: - http://download.cloud.com/support/downloads.html/ - 3.0 API Reference: - http://download.cloud.com/releases/3.0.0/api_3.0.0/TOC_Root_Admin.html/ + You can find all the API reference documentation at the below site: + http://incubator.apache.org/cloudstack/docs/api/
diff --git a/docs/en-US/appendix-a-time-zones.xml b/docs/en-US/appendix-a-time-zones.xml deleted file mode 100644 index 595e7b5cbf5..00000000000 --- a/docs/en-US/appendix-a-time-zones.xml +++ /dev/null @@ -1,143 +0,0 @@ - - -%BOOK_ENTITIES; -]> - - - -
- Appendix A—Time Zones - The following time zone identifiers are accepted by &PRODUCT;. There are several places that have a time zone as a required or optional parameter. These include scheduling recurring snapshots, creating a user, and specifying the usage time zone in the Configuration table. - - - - - Etc/GMT+12 - America/La_Paz - Asia/Jerusalem - - - - Etc/GMT+11 - America/Santiago - Europe/Minsk - - - - Pacific/Samoa - America/St_Johns - Europe/Moscow - - - Pacific/Honolulu - America/Araguaina - Africa/Nairobi - - - US/Alaska - America/Los_Angeles - Mexico/BajaNorte - - - US/Arizona - US/Mountain - America/Chihuahua - - - - America/Chicago - America/Costa_Rica - America/Mexico_City - - - - Canada/Saskatchewan - America/Bogota - America/New_York - - - America/Caracas - America/Asuncion - America/Cuiaba - - - America/Halifax - America/Argentina/Buenos_Aires - America/Cayenne - - - America/Godthab - America/Montevideo - Etc/GMT+2 - - - - Atlantic/Azores - Atlantic/Cape_Verde - Africa/Casablanca - - - - Etc/UTC - Atlantic/Reykjavik - Europe/London - - - CET - Europe/Bucharest - Africa/Johannesburg - - - Asia/Beirut - Africa/Cairo - Asia/Karachi - - - Asia/Kolkata - Asia/Bangkok - Asia/Shanghai - - - Asia/Kuala_Lumpur - Australia/Perth - Asia/Taipei - - - - Asia/Tokyo - Asia/Seoul - Australia/Adelaide - - - - Australia/Darwin - Australia/Brisbane - Australia/Canberra - - - Pacific/Guam - Pacific/Auckland - - - - - - -
diff --git a/docs/en-US/attaching-volume.xml b/docs/en-US/attaching-volume.xml index 385609b8f57..360555eac06 100644 --- a/docs/en-US/attaching-volume.xml +++ b/docs/en-US/attaching-volume.xml @@ -37,7 +37,8 @@
In the Instance popup, choose the VM to which you want to attach the volume. You will only see instances to which you are allowed to attach volumes; for example, a user will see only instances created by that user, but the administrator will have more choices. - If the VM is running in the OVM hypervisor, the VM must be stopped before a new volume can be attached to it. + +
When the volume has been attached, you should be able to see it by clicking Instances, the instance name, and View Volumes.
diff --git a/docs/en-US/aws-ec2-configuration.xml b/docs/en-US/aws-ec2-configuration.xml index e1924072168..d6c4066d1d8 100644 --- a/docs/en-US/aws-ec2-configuration.xml +++ b/docs/en-US/aws-ec2-configuration.xml @@ -23,42 +23,26 @@ -->
- Enabling the AWS API compatible Interface + Enabling the AWS API Compatible Interface - To enable the EC2 compatible service you need to set the configuration variable enable.ec2.apito true. This can be done via the &PRODUCT; GUI by going in Global Settings or via the API. - - - - - - - - Use the GUI to set the configuration variable to true - - - - - The easiest is to use the so-called integration port on which you can make unauthenticated calls. In Global Settings set the port to 8096 and subsequently call the updateConfiguration method. The following url shows you how: - - - - http://localhost:8096/client/api?command=updateConfiguration&name=enable.ec2.api&value=true - - - - Once you have updated enable.ec2.apito true, restart the server. - - - You will also need to define compute service offerings with names compatible with the Amazon EC2 instance types API names (e.g m1.small,m1.large). This is easiest done via the &PRODUCT; GUI. Go under Service Offerings select Compute offering and either create a new compute offering or modify an existing one, ensuring that the name matches an EC2 instance type API name. The snapshot below shows you how: - - - - - - - - Use the GUI to set the name of a compute service offering to an EC2 instance type API name. - - + The software that provides AWS API compatibility is installed along with &PRODUCT;. However, you must enable the feature and perform some setup steps. + + Set the global configuration parameter enable.ec2.api to true. See . + Create a set of &PRODUCT; service offerings with names that match the Amazon service offerings. + You can do this through the &PRODUCT; UI as described in the Administration Guide. + Be sure you have included the Amazon default service offering, m1.small. + If you did not already do so when you set the configuration parameter in step 1, restart the Management Server. + # service cloud-management restart + (Optional) The AWS API listens for requests on port 7080. If you prefer AWS API to listen on another port, you can change it as follows: + + Edit the files /etc/cloud/management/server.xml, /etc/cloud/management/server-nonssl.xml, and /etc/cloud/management/server-ssl.xml. + In each file, find the tag <Service name="Catalina7080">. Under this tag, locate <Connector executor="tomcatThreadPool-internal" port= ....<. + Change the port to whatever port you want to use, then save the files. + Restart the Management Server. + If you re-install CloudStack, you will have to make these changes again. + + + +
diff --git a/docs/en-US/aws-ec2-introduction.xml b/docs/en-US/aws-ec2-introduction.xml index c2bfb32bc61..a4df086d465 100644 --- a/docs/en-US/aws-ec2-introduction.xml +++ b/docs/en-US/aws-ec2-introduction.xml @@ -24,13 +24,14 @@
Amazon Web Services EC2 Compatible Interface - &PRODUCT; can translate Amazon Web Services (AWS) API calls to native &PRODUCT; API calls so that users can continue using existing AWS-compatible tools. This translation service runs as a separate web application in the same tomcat server as the management server of &PRODUCT;, listening on the same port. This Amazon EC2-compatible API is accessible through a SOAP web service as well as the REST query interface. - - Expect the SOAP service to be deprecated in new releases in favor of the REST interface. - + &PRODUCT; can translate Amazon Web Services (AWS) API calls to native &PRODUCT; API calls + so that users can continue using existing AWS-compatible tools. This translation service runs as + a separate web application in the same tomcat server as the management server of &PRODUCT;, + listening on the same port. This Amazon EC2-compatible API is accessible through a SOAP web + service. - This service was previously enabled by a separate software called CloudBridge, it is now fully integrated with the &PRODUCT; management server. - + This service was previously enabled by separate software called CloudBridge. It is now + fully integrated with the &PRODUCT; management server. Limitations diff --git a/docs/en-US/aws-ec2-requirements.xml b/docs/en-US/aws-ec2-requirements.xml index 916cec5fdda..59fb5b6f5ab 100644 --- a/docs/en-US/aws-ec2-requirements.xml +++ b/docs/en-US/aws-ec2-requirements.xml @@ -23,8 +23,13 @@ -->
- System Requirements - This interface complies with Amazon's WDSL version dated November 15, 2010, available at http://ec2.amazonaws.com/doc/2010-11-15/. The EC2 command line utilities compatible with it are EC2 tools v. 1.3.6230that can be downloaded at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip - - Effort is underway to provide support for a newer API -
+ System Requirements + + This interface complies with Amazon's WDSL version dated November 15, 2010, available at + http://ec2.amazonaws.com/doc/2010-11-15/. + Compatible with the EC2 command-line + tools EC2 tools v. 1.3.6230, which can be downloaded at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip. + + +
\ No newline at end of file diff --git a/docs/en-US/aws-ec2-supported-commands.xml b/docs/en-US/aws-ec2-supported-commands.xml index 77e47bd90a5..9494218cd1c 100644 --- a/docs/en-US/aws-ec2-supported-commands.xml +++ b/docs/en-US/aws-ec2-supported-commands.xml @@ -24,10 +24,9 @@
Supported AWS API Calls - - The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatibility feature is enabled. For a few commands, there are differences between the &PRODUCT; and Amazon EC2 versions, and these differences are noted. The underlying SOAP call for each command is also given, for those who have built tools using those calls. + The following Amazon EC2 commands are supported by &PRODUCT; when the AWS API compatibility feature is enabled. + For a few commands, there are differences between the &PRODUCT; and Amazon EC2 versions, and these differences are noted. The underlying SOAP call for each command is also given, for those who have built tools using those calls. - Elastic IP Addresses Elastic IP API mapping @@ -36,7 +35,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -69,7 +68,6 @@
- Availability Zones Availability Zone API mapping @@ -78,7 +76,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -91,7 +89,6 @@
- Images Images API mapping @@ -100,7 +97,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -128,7 +125,6 @@
- Image Attributes Image Attributes API mapping @@ -137,7 +133,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -160,7 +156,6 @@
- Instances Instances API mapping @@ -169,7 +164,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -207,7 +202,6 @@
- Instance Attributes Instance Attributes Mapping @@ -216,7 +210,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -229,7 +223,6 @@
- Key Pairs Keys Pairs Mapping @@ -238,7 +231,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -266,7 +259,6 @@
- Passwords Passwords API Mapping @@ -275,7 +267,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -288,7 +280,6 @@
- Security Groups Security Groups API Mapping @@ -297,7 +288,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -330,7 +321,6 @@
- Snapshots Snapshots API Mapping @@ -339,7 +329,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call @@ -362,7 +352,6 @@
- Volumes Volumes API Mapping @@ -371,7 +360,7 @@ EC2 command - SOAP all + SOAP call &PRODUCT; API call diff --git a/docs/en-US/aws-ec2-timeouts.xml b/docs/en-US/aws-ec2-timeouts.xml new file mode 100644 index 00000000000..c8b3ec6465f --- /dev/null +++ b/docs/en-US/aws-ec2-timeouts.xml @@ -0,0 +1,50 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Using Timeouts to Ensure AWS API Command Completion + The Amazon EC2 command-line tools have a default connection timeout. When used with &PRODUCT;, a longer timeout might be needed for some commands. If you find that commands are not completing due to timeouts, you can gain more time for commands to finish by overriding the default timeouts on individual commands. You can add the following optional command-line parameters to any &PRODUCT;-supported EC2 command: + + + + +
+ + --connection-timeout TIMEOUT + Specifies a connection timeout (in seconds). + Example: --connection-timeout 30 + + + + --request-timeout TIMEOUT + Specifies a request timeout (in seconds). + Example: --request-timeout 45 + + + + + + Example: + ec2-run-instances 2 –z us-test1 –n 1-3 --connection-timeout 120 --request-timeout 120 + \ No newline at end of file diff --git a/docs/en-US/aws-ec2-user-setup.xml b/docs/en-US/aws-ec2-user-setup.xml index 50c9fe26656..8607378d88c 100644 --- a/docs/en-US/aws-ec2-user-setup.xml +++ b/docs/en-US/aws-ec2-user-setup.xml @@ -22,70 +22,76 @@ under the License. -->
- User configuration - - Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools and scripts and use them with their &PRODUCT; deployment, by specifyingi the endpoint of the managment server and using the proper user credentials.In order to do this, each user must perform the following configuration steps: - + AWS API User Setup Steps + In general, users need not be aware that they are using a translation service provided by &PRODUCT;. + They need only send AWS API calls to &PRODUCT;'s endpoint, and it will translate the calls to the native API. + Users of the Amazon EC2 compatible interface will be able to keep their existing EC2 tools + and scripts and use them with their &PRODUCT; deployment, by specifying the endpoint of the + management server and using the proper user credentials. In order to do this, each user must + perform the following configuration steps: - Generate user credentials. + Generate user credentials and register with the service. - Register with the service. + Set up the environment variables for the EC2 command-line tools. - Setup the environment variables + For SOAP access, use the endpoint http://&PRODUCT;-management-server:7080/awsapi. + The &PRODUCT;-management-server can be specified by a fully-qualified domain name or IP address. - - - To register, a user needs to: - - +
+ AWS API User Registration + Each user must perform a one-time registration. The user follows these steps: - - Obtain his API key and his secret key as well as the DNS name or IP address of the &PRODUCT; server. Obtaining the keys can be done by asking the &PRODUCT; administrator or by using the GUI or via the API. - + Obtain the following by looking in the &PRODUCT; UI, using the API, or asking the cloud administrator: + + The &PRODUCT; server's publicly available DNS name or IP address + The user account's API key and Secret key + - Obtain a self-signed X.509 certificate. It can be generated with the following command: + Generate a private key and a self-signed X.509 certificate. The user substitutes their own desired storage location for /path/to/… below. - $ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem + $ openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /path/to/private_key.pem -out /path/to/cert.pem - Register the mapping from the X.509 certificate to the API/Secret keys. Download the following script from http://download.cloud.com/releases/3.0.3/cloudstack-aws-api-register and run it. Substitute the values you obtained from the administrator in the URL below. + Register the mapping from the X.509 certificate to the API/Secret keys. + Download the following script from http://download.cloud.com/releases/3.0.3/cloudstack-aws-api-register and run it. + Substitute the values that were obtained in step 1 in the URL below. -$ cloudstack-aws-api-register --apikey=User’s CloudPlatform API key --secretkey=User’s CloudPlatform Secret key --cert=/path/to/cert.pem --url=http://&PRODUCT;.server:8080/awsapi +$ cloudstack-aws-api-register --apikey=User’s &PRODUCT; API key --secretkey=User’s &PRODUCT; Secret key --cert=/path/to/cert.pem --url=http://&PRODUCT;.server:7080/awsapi - - A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT; but note that the public key would be uploaded to the &PRODUCT; management server database. + A user with an existing AWS certificate could choose to use the same certificate with &PRODUCT;, but the public key would be uploaded to the &PRODUCT; management server database. - - - To use the EC2 command line tools, setup the environment variable in a similar fashion than with Amazon EC2 service. Specifically, in bash shell: - - $ export EC2_CERT=/path/to/cert.pem - $ export EC2_PRIVATE_KEY=/path/to/private_key.pem - $ export EC2_URL=http://&PRODUCT;.server:8080/awsapi - $ export EC2_HOME=/path/to/EC2_tools_directory - - - - - The Amazon EC2 command-line tools have a default connection timeout. If you find that EC2 commands are not completing due to timeouts, you can pass a new timeout value as an argument with --connection-timeout TIMEOUT or --request-timeout TIMEOUT - - - -
+
+
+ AWS API Command-Line Tools Setup + To use the EC2 command-line tools, the user must perform these steps: + + Be sure you have the right version of EC2 Tools. + The supported version is available at http://s3.amazonaws.com/ec2-downloads/ec2-api-tools-1.3-62308.zip. + + + Set up the environment variables that will direct the tools to the server. As a best practice, you may wish to place these commands in a script that may be sourced before using the AWS API translation feature. + $ export EC2_CERT=/path/to/cert.pem +$ export EC2_PRIVATE_KEY=/path/to/private_key.pem +$ export EC2_URL=http://&PRODUCT;.server:7080/awsapi +$ export EC2_HOME=/path/to/EC2_tools_directory + + +
+ \ No newline at end of file diff --git a/docs/en-US/aws-interface-guide.xml b/docs/en-US/aws-interface-compatibility.xml similarity index 88% rename from docs/en-US/aws-interface-guide.xml rename to docs/en-US/aws-interface-compatibility.xml index 0c42b5bdb07..a03d447b50d 100644 --- a/docs/en-US/aws-interface-guide.xml +++ b/docs/en-US/aws-interface-compatibility.xml @@ -22,11 +22,12 @@ under the License. --> - - Amazon Web Service Interface Guide + + Amazon Web Service Interface Compatibility + diff --git a/docs/en-US/basic-adv-networking.xml b/docs/en-US/basic-adv-networking.xml new file mode 100644 index 00000000000..46f0650e69f --- /dev/null +++ b/docs/en-US/basic-adv-networking.xml @@ -0,0 +1,113 @@ + + +%BOOK_ENTITIES; +]> + +
+ Basic and Advanced Networking + &PRODUCT; provides two styles of networking:. + + Basic + For AWS-style networking. Provides a single network where guest isolation can be provided + through layer-3 means such as security groups (IP address source filtering). + + + Advanced + For more sophisticated network topologies. This network model provides the most + flexibility in defining guest networks, but requires more configuration steps than basic + networking. + + Each zone has either basic or advanced networking. Once the choice of networking model for a + zone has been made and configured in &PRODUCT;, it can not be changed. A zone is either + basic or advanced for its entire lifetime. + The following table compares the networking features in the two networking models. + + +
+ + Networking Feature + Basic Network + Advanced Network + + + + + Number of networks + Single network + Multiple networks + + + Firewall type + Physical + Physical and Virtual + + + Load balancer + Physical + Physical and Virtual + + + Isolation type + Layer 3 + Layer 2 and Layer 3 + + + VPN support + No + Yes + + + Port forwarding + Physical + Physical and Virtual + + + 1:1 NAT + Physical + Physical and Virtual + + + Source NAT + No + Physical and Virtual + + + Userdata + Yes + Yes + + + Network usage monitoring + sFlow / netFlow at physical router + Hypervisor and Virtual Router + + + DNS and DHCP + Yes + Yes + + + + + The two types of networking may be in use in the same cloud. However, a given zone must use + either Basic Networking or Advanced Networking. + Different types of network traffic can be segmented on the same physical network. Guest + traffic can also be segmented by account. To isolate traffic, you can use separate VLANs. If you + are using separate VLANs on a single physical network, make sure the VLAN tags are in separate + numerical ranges. + diff --git a/docs/en-US/basic-zone-configuration.xml b/docs/en-US/basic-zone-configuration.xml index 2b37f80f4b3..eb8b5068f76 100644 --- a/docs/en-US/basic-zone-configuration.xml +++ b/docs/en-US/basic-zone-configuration.xml @@ -67,7 +67,6 @@ 3. (Introduced in version 3.0.1) Assign a network traffic label to each traffic type on the physical network. These labels must match the labels you have already defined on the hypervisor host. To assign each label, click the Edit button under the traffic type icon. A popup dialog appears where you can type the label, then click OK. These traffic labels will be defined only for the hypervisor selected for the first cluster. For all other hypervisors, the labels can be configured after the zone is created. - (VMware only) If you have enabled Nexus dvSwitch in the environment, you must specify the corresponding Ethernet port profile names as network traffic label for each traffic type on the physical network. For more information on Nexus dvSwitch, see Configuring a vSphere Cluster with Nexus 1000v Virtual Switch. Click Next.(NetScaler only) If you chose the network offering for NetScaler, you have an additional screen to fill out. Provide the requested details to set up the NetScaler, then click Next. @@ -125,7 +124,7 @@ Citrix XenServer Installation and Configuration VMware vSphere Installation and Configuration KVM vSphere Installation and Configuration - Oracle VM (OVM) Installation and Configuration + To configure the first host, enter the following, then click Next: @@ -139,7 +138,7 @@ To configure the first primary storage server, enter the following, then click Next: Name. The name of the storage device. - Protocol. For XenServer, choose either NFS, iSCSI, or PreSetup. For KVM, choose NFS or SharedMountPoint. For vSphere choose either VMFS (iSCSI or FiberChannel) or NFS. The remaining fields in the screen vary depending on what you choose here. + Protocol. For XenServer, choose either NFS, iSCSI, or PreSetup. For KVM, choose NFS, SharedMountPoint,CLVM, or RBD. For vSphere choose either VMFS (iSCSI or FiberChannel) or NFS. The remaining fields in the screen vary depending on what you choose here. diff --git a/docs/en-US/basic-zone-physical-network-configuration.xml b/docs/en-US/basic-zone-physical-network-configuration.xml index 302c2932a51..4b1d24f2657 100644 --- a/docs/en-US/basic-zone-physical-network-configuration.xml +++ b/docs/en-US/basic-zone-physical-network-configuration.xml @@ -24,4 +24,5 @@
Basic Zone Physical Network Configuration In a basic network, configuring the physical network is fairly straightforward. You only need to configure one guest network to carry traffic that is generated by guest VMs. When you first add a zone to &PRODUCT;, you set up the guest network through the Add Zone screens. -
+ + diff --git a/docs/en-US/best-practices-for-vms.xml b/docs/en-US/best-practices-for-vms.xml index 0ccb183a4f7..bba20c6fce3 100644 --- a/docs/en-US/best-practices-for-vms.xml +++ b/docs/en-US/best-practices-for-vms.xml @@ -1,9 +1,8 @@ - %BOOK_ENTITIES; ]> - + +
+ Building DEB packages + + In addition to the bootstrap dependencies, you'll also need to install + several other dependencies. Note that we recommend using Maven 3, which + is not currently available in 12.04.1 LTS. So, you'll also need to add a + PPA repository that includes Maven 3. After running the command + add-apt-repository, you will be prompted to continue and + a GPG key will be added. + + +$ sudo apt-get update +$ sudo apt-get install python-software-properties +$ sudo add-apt-repository ppa:natecarlson/maven3 +$ sudo apt-get update +$ sudo apt-get install ant debhelper openjdk-6-jdk tomcat6 libws-commons-util-java genisoimage python-mysqldb libcommons-codec-java libcommons-httpclient-java liblog4j1.2-java maven3 + + + While we have defined, and you have presumably already installed the + bootstrap prerequisites, there are a number of build time prerequisites + that need to be resolved. &PRODUCT; uses maven for dependency resolution. + You can resolve the buildtime depdencies for CloudStack by running: + +$ mvn3 -P deps + + Now that we have resolved the dependencies we can move on to building &PRODUCT; + and packaging them into DEBs by issuing the following command. + + +$ dpkg-buildpackge -uc -us + + + + This command will build 16 Debian packages. You should have all of the following: + + +cloud-agent_4.0.0-incubating_amd64.deb +cloud-agent-deps_4.0.0-incubating_amd64.deb +cloud-agent-libs_4.0.0-incubating_amd64.deb +cloud-awsapi_4.0.0-incubating_amd64.deb +cloud-cli_4.0.0-incubating_amd64.deb +cloud-client_4.0.0-incubating_amd64.deb +cloud-client-ui_4.0.0-incubating_amd64.deb +cloud-core_4.0.0-incubating_amd64.deb +cloud-deps_4.0.0-incubating_amd64.deb +cloud-python_4.0.0-incubating_amd64.deb +cloud-scripts_4.0.0-incubating_amd64.deb +cloud-server_4.0.0-incubating_amd64.deb +cloud-setup_4.0.0-incubating_amd64.deb +cloud-system-iso_4.0.0-incubating_amd64.deb +cloud-usage_4.0.0-incubating_amd64.deb +cloud-utils_4.0.0-incubating_amd64.deb + + +
+ Setting up an APT repo + + After you've created the packages, you'll want to copy them to a system where you can serve the packages over HTTP. You'll create a directory for the packages and then use dpkg-scanpackages to create Packages.gz, which holds information about the archive structure. Finally, you'll add the repository to your system(s) so you can install the packages using APT. + + The first step is to make sure that you have the dpkg-dev package installed. This should have been installed when you pulled in the debhelper application previously, but if you're generating Packages.gz on a different system, be sure that it's installed there as well. + +$ sudo apt-get install dpkg-dev + +The next step is to copy the DEBs to the directory where they can be served over HTTP. We'll use /var/www/cloudstack/repo in the examples, but change the directory to whatever works for you. + + +sudo mkdir -p /var/www/cloudstack/repo/binary +sudo cp *.deb /var/www/cloudstack/repo/binary +sudo cd /var/www/cloudstack/repo/binary +sudo dpkg-scanpackages . /dev/null | tee Packages | gzip -9 > Packages.gz + + +Note: Override Files + You can safely ignore the warning about a missing override file. + + +Now you should have all of the DEB packages and Packages.gz in the binary directory and available over HTTP. (You may want to use wget or curl to test this before moving on to the next step.) + +
+
+ Configuring your machines to use the APT repository + + Now that we have created the repository, you need to configure your machine + to make use of the APT repository. You can do this by adding a repository file + under /etc/apt/sources.list.d. Use your preferred editor to + create /etc/apt/sources.list.d/cloudstack.list with this + line: + + deb http://server.url/cloudstack/repo binary/ + + Now that you have the repository info in place, you'll want to run another + update so that APT knows where to find the &PRODUCT; packages. + +$ sudo apt-get update + +You can now move on to the instructions under Install on Ubuntu. + +
+
diff --git a/docs/en-US/build-rpm.xml b/docs/en-US/build-rpm.xml new file mode 100644 index 00000000000..e983aba8fe5 --- /dev/null +++ b/docs/en-US/build-rpm.xml @@ -0,0 +1,82 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Building RPMs + + While we have defined, and you have presumably already installed the + bootstrap prerequisites, there are a number of build time prerequisites + that need to be resolved. &PRODUCT; uses maven for dependency resolution. + You can resolve the buildtime depdencies for CloudStack by running the + following command: + $ mvn -P deps + + + Now that we have resolved the dependencies we can move on to building &PRODUCT; + and packaging them into RPMs by issuing the following command. + $ ./waf rpm + + + Once this completes, you should find assembled RPMs in + artifacts/rpmbuild/RPMS/x86_64 + +
+ Creating a yum repo + + While RPMs is an ideal packaging format - it's most easily consumed from + yum repositories over a network. We'll move into the directory with the + newly created RPMs by issuing the following command: + $ cd artifacts/rpmbuild/RPMS/x86_64 + + + Next we'll issue a command to create the repository metadata by + issuing the following command: + $ createrepo ./ + + + The files and directories within our current working directory can now + be uploaded to a web server and serve as a yum repository + +
+
+ Configuring your systems to use your new yum repository + + Now that your yum repository is populated with RPMs and metadata + we need to configure our machines that need to install CloudStack. + We will create a file at /etc/yum.repos.d/cloudstack.repo + with the following content: + +[apache-cloudstack] +name=Apache CloudStack +baseurl=http://webserver.tld/path/to/repo +enabled=1 +gpgcheck=0 + + + + Completing this step will allow you to easily install CloudStack on a number of + machines across the network. + +
+
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/changing-secondary-storage-serversp.xml b/docs/en-US/building-with-maven.xml similarity index 56% rename from docs/en-US/changing-secondary-storage-serversp.xml rename to docs/en-US/building-with-maven.xml index 62ad65015a3..5363b1d754a 100644 --- a/docs/en-US/changing-secondary-storage-serversp.xml +++ b/docs/en-US/building-with-maven.xml @@ -22,15 +22,11 @@ under the License. --> -
- Changing Secondary Storage Servers - You can change the secondary storage NFS mount. Perform the following steps to do so: - - Stop all running Management Servers. - Wait 30 minutes. This allows any writes to secondary storage to complete. - Copy all files from the old secondary storage mount to the new. - Use the procedure above to change the IP address for secondary storage if required. - Start the Management Server. - -
+ + Using Maven to Build &PRODUCT; + + + + + diff --git a/docs/en-US/castor-with-cs.xml b/docs/en-US/castor-with-cs.xml index 6385452b1ee..5049d33d638 100644 --- a/docs/en-US/castor-with-cs.xml +++ b/docs/en-US/castor-with-cs.xml @@ -34,7 +34,7 @@ To configure CAStor: - Install &PRODUCT; 4.0 by following the instructions given in the INSTALL.txt + Install &PRODUCT; 4.0.0-incubating by following the instructions given in the INSTALL.txt file. You can use the S3 storage system in &PRODUCT; without setting up and installing the diff --git a/docs/en-US/configure-xenserver-dom-memory.xml b/docs/en-US/change-database-config.xml similarity index 65% rename from docs/en-US/configure-xenserver-dom-memory.xml rename to docs/en-US/change-database-config.xml index 0a02d3e3818..34e767251e0 100644 --- a/docs/en-US/configure-xenserver-dom-memory.xml +++ b/docs/en-US/change-database-config.xml @@ -22,8 +22,7 @@ under the License. --> -
- Configure XenServer dom0 Memory - Configure the XenServer dom0 settings to allocate more memory to dom0. This can enable XenServer to handle larger numbers of virtual machines. We recommend 2940 MB of RAM for XenServer dom0. For instructions on how to do this, see Citrix Knowledgebase Article.The article refers to XenServer 5.6, but the same information applies to XenServer 6 +
+ 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.
- 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/change-to-behavior-of-list-commands.xml b/docs/en-US/change-to-behavior-of-list-commands.xml index 9065398ef62..69b9e4d2beb 100644 --- a/docs/en-US/change-to-behavior-of-list-commands.xml +++ b/docs/en-US/change-to-behavior-of-list-commands.xml @@ -105,5 +105,4 @@ The &PRODUCT; UI on a general view will display all resources that the logged-in user is authorized to see, except for project resources. To see the project resources, select the project view. -
diff --git a/docs/en-US/changed-apicommands-4.0.xml b/docs/en-US/changed-apicommands-4-0.xml similarity index 99% rename from docs/en-US/changed-apicommands-4.0.xml rename to docs/en-US/changed-apicommands-4-0.xml index f851bf71b46..042d5e2611e 100644 --- a/docs/en-US/changed-apicommands-4.0.xml +++ b/docs/en-US/changed-apicommands-4-0.xml @@ -19,7 +19,7 @@ under the License. -->
- Changed API Commands in 4.0 + Changed API Commands in 4.0.0-incubating diff --git a/docs/en-US/changing-secondary-storage-servers.xml b/docs/en-US/changing-secondary-storage-servers.xml index 62ad65015a3..a628eec9b39 100644 --- a/docs/en-US/changing-secondary-storage-servers.xml +++ b/docs/en-US/changing-secondary-storage-servers.xml @@ -22,7 +22,7 @@ under the License. --> -
+
Changing Secondary Storage Servers You can change the secondary storage NFS mount. Perform the following steps to do so: diff --git a/docs/en-US/cisco3750-hardware.xml b/docs/en-US/cisco3750-hardware.xml new file mode 100644 index 00000000000..b5266105074 --- /dev/null +++ b/docs/en-US/cisco3750-hardware.xml @@ -0,0 +1,52 @@ + + +%BOOK_ENTITIES; +]> + +
+ Cisco 3750 + The following steps show how a Cisco 3750 is configured for zone-level layer-3 switching. + These steps assume VLAN 201 is used to route untagged private IPs for pod 1, and pod 1’s layer-2 + switch is connected to GigabitEthernet1/0/1. + + + Setting VTP mode to transparent allows us to utilize VLAN IDs above 1000. Since we only + use VLANs up to 999, vtp transparent mode is not strictly required. + vtp mode transparent +vlan 200-999 +exit + + + Configure GigabitEthernet1/0/1. + interface GigabitEthernet1/0/1 +switchport trunk encapsulation dot1q +switchport mode trunk +switchport trunk native vlan 201 +exit + + + The statements configure GigabitEthernet1/0/1 as follows: + + + VLAN 201 is the native untagged VLAN for port GigabitEthernet1/0/1. + + + Cisco passes all VLANs by default. As a result, all VLANs (300-999) are passed to all the pod-level layer-2 switches. + + +
diff --git a/docs/en-US/cisco3750-layer2.xml b/docs/en-US/cisco3750-layer2.xml new file mode 100644 index 00000000000..e4fe1422056 --- /dev/null +++ b/docs/en-US/cisco3750-layer2.xml @@ -0,0 +1,45 @@ + + +%BOOK_ENTITIES; +]> + +
+ Cisco 3750 + The following steps show how a Cisco 3750 is configured for pod-level layer-2 + switching. + + + Setting VTP mode to transparent allows us to utilize VLAN IDs above 1000. Since we only + use VLANs up to 999, vtp transparent mode is not strictly required. + vtp mode transparent +vlan 300-999 +exit + + + Configure all ports to dot1q and set 201 as the native VLAN. + interface range GigabitEthernet 1/0/1-24 +switchport trunk encapsulation dot1q +switchport mode trunk +switchport trunk native vlan 201 +exit + + + By default, Cisco passes all VLANs. Cisco switches complain of the native VLAN IDs are + different when 2 ports are connected together. That’s why you must specify VLAN 201 as the + native VLAN on the layer-2 switch. +
diff --git a/docs/en-US/citrix-xenserver-installation.xml b/docs/en-US/citrix-xenserver-installation.xml index b8ab5923982..867d36e1b10 100644 --- a/docs/en-US/citrix-xenserver-installation.xml +++ b/docs/en-US/citrix-xenserver-installation.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -21,469 +21,728 @@ specific language governing permissions and limitations under the License. --> -
- Citrix XenServer Installation for &PRODUCT; - If you want to use the Citrix XenServer hypervisor to run guest virtual machines, install XenServer 6.0 or XenServer 6.0.2 on the host(s) in your cloud. For an initial installation, follow the steps below. If you have previously installed XenServer and want to upgrade to another version, see . -
- System Requirements for XenServer Hosts - - The host must be certified as compatible with one of the following. See the Citrix Hardware Compatibility Guide: http://hcl.xensource.com + Citrix XenServer Installation for &PRODUCT; + If you want to use the Citrix XenServer hypervisor to run guest virtual machines, install + XenServer 6.0 or XenServer 6.0.2 on the host(s) in your cloud. For an initial installation, + follow the steps below. If you have previously installed XenServer and want to upgrade to + another version, see . +
+ System Requirements for XenServer Hosts - XenServer 5.6 SP2 - XenServer 6.0 - XenServer 6.0.2 + + The host must be certified as compatible with one of the following. See the Citrix + Hardware Compatibility Guide: http://hcl.xensource.com + + + XenServer 5.6 SP2 + + + XenServer 6.0 + + + XenServer 6.0.2 + + + + + You must re-install Citrix XenServer if you are going to re-use a host from a previous + install. + + + Must support HVM (Intel-VT or AMD-V enabled) + + + Be sure all the hotfixes provided by the hypervisor vendor are applied. Track the + release of hypervisor patches through your hypervisor vendor’s support channel, and apply + patches as soon as possible after they are released. &PRODUCT; will not track or notify + you of required hypervisor patches. It is essential that your hosts are completely up to + date with the provided hypervisor patches. The hypervisor vendor is likely to refuse to + support any system that is not up to date with patches. + + + All hosts within a cluster must be homogenous. The CPUs must be of the same type, + count, and feature flags. + + + Must support HVM (Intel-VT or AMD-V enabled in BIOS) + + + 64-bit x86 CPU (more cores results in better performance) + + + Hardware virtualization support required + + + 4 GB of memory + + + 36 GB of local disk + + + At least 1 NIC + + + Statically allocated IP Address + + + When you deploy &PRODUCT;, the hypervisor host must not have any VMs already + running + - - All hosts must be 64-bit and must support HVM (Intel-VT or AMD-V enabled in BIOS). - All hosts within a cluster must be homogenous. That means the CPUs must be of the same type, count, and feature flags. - You must re-install Citrix XenServer if you are going to re-use a host from a previous install. - 64-bit x86 CPU (more cores results in better performance) - Hardware virtualization support required - 4 GB of memory - 36 GB of local disk - At least 1 NIC - Statically allocated IP Address - Be sure all the hotfixes provided by the hypervisor vendor are applied. Track the release of hypervisor patches through your hypervisor vendor’s support channel, and apply patches as soon as possible after they are released. &PRODUCT; will not track or notify you of required hypervisor patches. It is essential that your hosts are completely up to date with the provided hypervisor patches. The hypervisor vendor is likely to refuse to support any system that is not up to date with patches. For more information, see Highly Recommended Hotfixes for XenServer in the &PRODUCT; Knowledge Base. - - The lack of up-do-date hotfixes can lead to data corruption and lost VMs. -
-
- XenServer Installation Steps - - From https://www.citrix.com/English/ss/downloads/, download the appropriate version of XenServer for your &PRODUCT; version (see ). Install it using the Citrix XenServer Installation Guide. - After installation, perform the following configuration steps, which are described in the next few sections: - - - - -
- - Required - Optional - - - - - - - - - - Set up SR if not using NFS, iSCSI, or local disk; see - - - - - - - - - - - - - - - -
- Configure XenServer dom0 Memory - Configure the XenServer dom0 settings to allocate more memory to dom0. This can enable XenServer to handle larger numbers of virtual machines. We recommend 2940 MB of RAM for XenServer dom0. For instructions on how to do this, see http://support.citrix.com/article/CTX126531. The article refers to XenServer 5.6, but the same information applies to XenServer 6.0. -
-
- Username and Password - All XenServers in a cluster must have the same username and password as configured in &PRODUCT;. -
-
- Time Synchronization - The host must be set to use NTP. All hosts in a pod must have the same time. - + + The lack of up-do-date hotfixes can lead to data corruption and lost VMs. + +
+
+ XenServer Installation Steps + - Install NTP. - # yum install ntp + From https://www.citrix.com/English/ss/downloads/, download the appropriate version + of XenServer for your &PRODUCT; version (see ). Install it using the Citrix XenServer + Installation Guide. - Edit the NTP configuration file to point to your NTP server. - # vi /etc/ntp.conf - Add one or more server lines in this file with the names of the NTP servers you want to use. For example: - -server 0.xenserver.pool.ntp.org + After installation, perform the following configuration steps, which are described in + the next few sections: + + + + +
+ + Required + Optional + + + + + + + + + + Set up SR if not using NFS, iSCSI, or local disk; see + + + + + + + + + + + + + + + +
+ Configure XenServer dom0 Memory + Configure the XenServer dom0 settings to allocate more memory to dom0. This can enable + XenServer to handle larger numbers of virtual machines. We recommend 2940 MB of RAM for + XenServer dom0. For instructions on how to do this, see http://support.citrix.com/article/CTX126531. The article refers to XenServer 5.6, + but the same information applies to XenServer 6.0. +
+
+ Username and Password + All XenServers in a cluster must have the same username and password as configured in + &PRODUCT;. +
+
+ Time Synchronization + The host must be set to use NTP. All hosts in a pod must have the same time. + + + Install NTP. + # yum install ntp + + + Edit the NTP configuration file to point to your NTP server. + # vi /etc/ntp.conf + Add one or more server lines in this file with the names of the NTP servers you want + to use. For example: + server 0.xenserver.pool.ntp.org server 1.xenserver.pool.ntp.org server 2.xenserver.pool.ntp.org server 3.xenserver.pool.ntp.org - Restart the NTP client. - # service ntpd restart + Restart the NTP client. + # service ntpd restart - Make sure NTP will start again upon reboot. - # chkconfig ntpd on + Make sure NTP will start again upon reboot. + # chkconfig ntpd on - -
-
- Licensing - Citrix XenServer Free version provides 30 days usage without a license. Following the 30 day trial, XenServer requires a free activation and license. You can choose to install a license now or skip this step. If you skip this step, you will need to install a license when you activate and license the XenServer. -
+ +
+
+ Licensing + Citrix XenServer Free version provides 30 days usage without a license. Following the 30 + day trial, XenServer requires a free activation and license. You can choose to install a + license now or skip this step. If you skip this step, you will need to install a license when + you activate and license the XenServer. +
Getting and Deploying a License - If you choose to install a license now you will need to use the XenCenter to activate and get a license. + If you choose to install a license now you will need to use the XenCenter to activate + and get a license. - In XenCenter, click Tools > License manager. - Select your XenServer and select Activate Free XenServer. - Request a license. + + In XenCenter, click Tools > License manager. + + + Select your XenServer and select Activate Free XenServer. + + + Request a license. + You can install the license with XenCenter or using the xe command line tool. +
-
-
- Install &PRODUCT; XenServer Support Package (CSP) - (Optional) - To enable security groups, elastic load balancing, and elastic IP on XenServer, download and install the &PRODUCT; XenServer Support Package (CSP). After installing XenServer, perform the following additional steps on each XenServer host. - +
+ Install &PRODUCT; XenServer Support Package (CSP) + (Optional) + To enable security groups, elastic load balancing, and elastic IP on XenServer, download + and install the &PRODUCT; XenServer Support Package (CSP). After installing XenServer, perform + the following additional steps on each XenServer host. + - Download the CSP software onto the XenServer host from one of the following links: - For XenServer 6.0.2: - http://download.cloud.com/releases/3.0.1/XS-6.0.2/xenserver-cloud-supp.tgz - For XenServer 5.6 SP2: - http://download.cloud.com/releases/2.2.0/xenserver-cloud-supp.tgz - For XenServer 6.0: - http://download.cloud.com/releases/3.0/xenserver-cloud-supp.tgz + Download the CSP software onto the XenServer host from one of the following + links: + For XenServer 6.0.2: + http://download.cloud.com/releases/3.0.1/XS-6.0.2/xenserver-cloud-supp.tgz + For XenServer 5.6 SP2: + http://download.cloud.com/releases/2.2.0/xenserver-cloud-supp.tgz + For XenServer 6.0: + http://download.cloud.com/releases/3.0/xenserver-cloud-supp.tgz - Extract the file: - # tar xf xenserver-cloud-supp.tgz + Extract the file: + # tar xf xenserver-cloud-supp.tgz - Run the following script: - # xe-install-supplemental-pack xenserver-cloud-supp.iso + Run the following script: + # xe-install-supplemental-pack xenserver-cloud-supp.iso - If the XenServer host is part of a zone that uses basic networking, disable Open vSwitch (OVS): - # xe-switch-network-backend bridge - Restart the host machine when prompted. + If the XenServer host is part of a zone that uses basic networking, disable Open + vSwitch (OVS): + # xe-switch-network-backend bridge + Restart the host machine when prompted. - - The XenServer host is now ready to be added to &PRODUCT;. -
-
- Primary Storage Setup for XenServer - &PRODUCT; natively supports NFS, iSCSI and local storage. If you are using one of these storage types, there is no need to create the XenServer Storage Repository ("SR"). - If, however, you would like to use storage connected via some other technology, such as FiberChannel, you must set up the SR yourself. To do so, perform the following steps. If you have your hosts in a XenServer pool, perform the steps on the master node. If you are working with a single XenServer which is not part of a cluster, perform the steps on that XenServer. - - Connect FiberChannel cable to all hosts in the cluster and to the FiberChannel storage host. + + The XenServer host is now ready to be added to &PRODUCT;. +
+
+ Primary Storage Setup for XenServer + &PRODUCT; natively supports NFS, iSCSI and local storage. If you are using one of these + storage types, there is no need to create the XenServer Storage Repository ("SR"). + If, however, you would like to use storage connected via some other technology, such as + FiberChannel, you must set up the SR yourself. To do so, perform the following steps. If you + have your hosts in a XenServer pool, perform the steps on the master node. If you are working + with a single XenServer which is not part of a cluster, perform the steps on that + XenServer. + - Rescan the SCSI bus. Either use the following command or use XenCenter to perform an HBA rescan. - # scsi-rescan + Connect FiberChannel cable to all hosts in the cluster and to the FiberChannel storage + host. - Repeat step 2 on every host. - Check to be sure you see the new SCSI disk. - # ls /dev/disk/by-id/scsi-360a98000503365344e6f6177615a516b -l - The output should look like this, although the specific file name will be different (scsi-<scsiID>): - -lrwxrwxrwx 1 root root 9 Mar 16 13:47 + Rescan the SCSI bus. Either use the following command or use XenCenter to perform an + HBA rescan. + # scsi-rescan + + + Repeat step 2 on every host. + + + Check to be sure you see the new SCSI disk. + # ls /dev/disk/by-id/scsi-360a98000503365344e6f6177615a516b -l + The output should look like this, although the specific file name will be different + (scsi-<scsiID>): + lrwxrwxrwx 1 root root 9 Mar 16 13:47 /dev/disk/by-id/scsi-360a98000503365344e6f6177615a516b -> ../../sdc - Repeat step 4 on every host. - On the storage server, run this command to get a unique ID for the new SR. - # uuidgen - The output should look like this, although the specific ID will be different: - e6849e96-86c3-4f2c-8fcc-350cc711be3d + Repeat step 4 on every host. - Create the FiberChannel SR. In name-label, use the unique ID you just generated. - + On the storage server, run this command to get a unique ID for the new SR. + # uuidgen + The output should look like this, although the specific ID will be different: + e6849e96-86c3-4f2c-8fcc-350cc711be3d + + + Create the FiberChannel SR. In name-label, use the unique ID you just + generated. + # xe sr-create type=lvmohba shared=true device-config:SCSIid=360a98000503365344e6f6177615a516b name-label="e6849e96-86c3-4f2c-8fcc-350cc711be3d" - This command returns a unique ID for the SR, like the following example (your ID will be different): - 7a143820-e893-6c6a-236e-472da6ee66bf + This command returns a unique ID for the SR, like the following example (your ID will + be different): + 7a143820-e893-6c6a-236e-472da6ee66bf - To create a human-readable description for the SR, use the following command. In uuid, use the SR ID returned by the previous command. In name-description, set whatever friendly text you prefer. - # xe sr-param-set uuid=7a143820-e893-6c6a-236e-472da6ee66bf name-description="Fiber Channel storage repository" - Make note of the values you will need when you add this storage to &PRODUCT; later (see ). In the Add Primary Storage dialog, in Protocol, you will choose PreSetup. In SR Name-Label, you will enter the name-label you set earlier (in this example, e6849e96-86c3-4f2c-8fcc-350cc711be3d). + To create a human-readable description for the SR, use the following command. In uuid, + use the SR ID returned by the previous command. In name-description, set whatever friendly + text you prefer. + # xe sr-param-set uuid=7a143820-e893-6c6a-236e-472da6ee66bf name-description="Fiber Channel storage repository" + Make note of the values you will need when you add this storage to &PRODUCT; later + (see ). In the Add Primary Storage dialog, in + Protocol, you will choose PreSetup. In SR Name-Label, you will enter the name-label you + set earlier (in this example, e6849e96-86c3-4f2c-8fcc-350cc711be3d). - (Optional) If you want to enable multipath I/O on a FiberChannel SAN, refer to the documentation provided by the SAN vendor. - -
-
- iSCSI Multipath Setup for XenServer (Optional) - When setting up the storage repository on a Citrix XenServer, you can enable multipath I/O, which uses redundant physical components to provide greater reliability in the connection between the server and the SAN. To enable multipathing, use a SAN solution that is supported for Citrix servers and follow the procedures in Citrix documentation. The following links provide a starting point: - - http://support.citrix.com/article/CTX118791 - http://support.citrix.com/article/CTX125403 - - You can also ask your SAN vendor for advice about setting up your Citrix repository for multipathing. - Make note of the values you will need when you add this storage to the &PRODUCT; later (see ). In the Add Primary Storage dialog, in Protocol, you will choose PreSetup. In SR Name-Label, you will enter the same name used to create the SR. - If you encounter difficulty, address the support team for the SAN provided by your vendor. If they are not able to solve your issue, see Contacting Support. -
-
- Physical Networking Setup for XenServer - Once XenServer has been installed, you may need to do some additional network configuration. At this point in the installation, you should have a plan for what NICs the host will have and what traffic each NIC will carry. The NICs should be cabled as necessary to implement your plan. - If you plan on using NIC bonding, the NICs on all hosts in the cluster must be cabled exactly the same. For example, if eth0 is in the private bond on one host in a cluster, then eth0 must be in the private bond on all hosts in the cluster. - The IP address assigned for the management network interface must be static. It can be set on the host itself or obtained via static DHCP. - &PRODUCT; configures network traffic of various types to use different NICs or bonds on the XenServer host. You can control this process and provide input to the Management Server through the use of XenServer network name labels. The name labels are placed on physical interfaces or bonds and configured in &PRODUCT;. In some simple cases the name labels are not required. -
- Configuring Public Network with a Dedicated NIC for XenServer (Optional) - &PRODUCT; supports the use of a second NIC (or bonded pair of NICs, described in ) for the public network. If bonding is not used, the public network can be on any NIC and can be on different NICs on the hosts in a cluster. For example, the public network can be on eth0 on node A and eth1 on node B. However, the XenServer name-label for the public network must be identical across all hosts. The following examples set the network label to "cloud-public". After the management server is installed and running you must configure it with the name of the chosen network label (e.g. "cloud-public"); this is discussed in . - If you are using two NICs bonded together to create a public network, see . - If you are using a single dedicated NIC to provide public network access, follow this procedure on each new host that is added to &PRODUCT; before adding the host. - - Run xe network-list and find the public network. This is usually attached to the NIC that is public. Once you find the network make note of its UUID. Call this <UUID-Public>. - - Run the following command. - # xe network-param-set name-label=cloud-public uuid=<UUID-Public> - - + + (Optional) If you want to enable multipath I/O on a FiberChannel SAN, refer to the + documentation provided by the SAN vendor. + +
-
+
+ iSCSI Multipath Setup for XenServer (Optional) + When setting up the storage repository on a Citrix XenServer, you can enable multipath + I/O, which uses redundant physical components to provide greater reliability in the connection + between the server and the SAN. To enable multipathing, use a SAN solution that is supported + for Citrix servers and follow the procedures in Citrix documentation. The following links + provide a starting point: + + + http://support.citrix.com/article/CTX118791 + + + http://support.citrix.com/article/CTX125403 + + + You can also ask your SAN vendor for advice about setting up your Citrix repository for + multipathing. + Make note of the values you will need when you add this storage to the &PRODUCT; later + (see ). In the Add Primary Storage dialog, in Protocol, + you will choose PreSetup. In SR Name-Label, you will enter the same name used to create the + SR. + If you encounter difficulty, address the support team for the SAN provided by your vendor. + If they are not able to solve your issue, see Contacting Support. +
+
+ Physical Networking Setup for XenServer + Once XenServer has been installed, you may need to do some additional network + configuration. At this point in the installation, you should have a plan for what NICs the + host will have and what traffic each NIC will carry. The NICs should be cabled as necessary to + implement your plan. + If you plan on using NIC bonding, the NICs on all hosts in the cluster must be cabled + exactly the same. For example, if eth0 is in the private bond on one host in a cluster, then + eth0 must be in the private bond on all hosts in the cluster. + The IP address assigned for the management network interface must be static. It can be set + on the host itself or obtained via static DHCP. + &PRODUCT; configures network traffic of various types to use different NICs or bonds on + the XenServer host. You can control this process and provide input to the Management Server + through the use of XenServer network name labels. The name labels are placed on physical + interfaces or bonds and configured in &PRODUCT;. In some simple cases the name labels are not + required. +
+ Configuring Public Network with a Dedicated NIC for XenServer (Optional) + &PRODUCT; supports the use of a second NIC (or bonded pair of NICs, described in ) for the public network. If bonding is not used, the + public network can be on any NIC and can be on different NICs on the hosts in a cluster. For + example, the public network can be on eth0 on node A and eth1 on node B. However, the + XenServer name-label for the public network must be identical across all hosts. The + following examples set the network label to "cloud-public". After the management + server is installed and running you must configure it with the name of the chosen network + label (e.g. "cloud-public"); this is discussed in . + If you are using two NICs bonded together to create a public network, see . + If you are using a single dedicated NIC to provide public network access, follow this + procedure on each new host that is added to &PRODUCT; before adding the host. + + + Run xe network-list and find the public network. This is usually attached to the NIC + that is public. Once you find the network make note of its UUID. Call this + <UUID-Public>. + + + Run the following command. + # xe network-param-set name-label=cloud-public uuid=<UUID-Public> + + +
+
Configuring Multiple Guest Networks for XenServer (Optional) - &PRODUCT; supports the use of multiple guest networks with the XenServer hypervisor. Each network is assigned a name-label in XenServer. For example, you might have two networks with the labels "cloud-guest" and "cloud-guest2". After the management server is installed and running, you must add the networks and use these labels so that &PRODUCT; is aware of the networks. + &PRODUCT; supports the use of multiple guest networks with the XenServer hypervisor. + Each network is assigned a name-label in XenServer. For example, you might have two networks + with the labels "cloud-guest" and "cloud-guest2". After the management + server is installed and running, you must add the networks and use these labels so that + &PRODUCT; is aware of the networks. Follow this procedure on each new host before adding the host to &PRODUCT;: - Run xe network-list and find one of the guest networks. Once you find the network make note of its UUID. Call this <UUID-Guest>. - - Run the following command, substituting your own name-label and uuid values. - # xe network-param-set name-label=<cloud-guestN> uuid=<UUID-Guest> - - Repeat these steps for each additional guest network, using a different name-label and uuid each time. + + Run xe network-list and find one of the guest networks. Once you find the network + make note of its UUID. Call this <UUID-Guest>. + + + Run the following command, substituting your own name-label and uuid values. + # xe network-param-set name-label=<cloud-guestN> uuid=<UUID-Guest> + + + Repeat these steps for each additional guest network, using a different name-label + and uuid each time. + -
-
+
+
Separate Storage Network for XenServer (Optional) - You can optionally set up a separate storage network. This should be done first on the host, before implementing the bonding steps below. This can be done using one or two available NICs. With two NICs bonding may be done as above. It is the administrator's responsibility to set up a separate storage network. - Give the storage network a different name-label than what will be given for other networks. - For the separate storage network to work correctly, it must be the only interface that can ping the primary storage device's IP address. For example, if eth0 is the management network NIC, ping -I eth0 <primary storage device IP> must fail. In all deployments, secondary storage devices must be pingable from the management network NIC or bond. If a secondary storage device has been placed on the storage network, it must also be pingable via the storage network NIC or bond on the hosts as well. - You can set up two separate storage networks as well. For example, if you intend to implement iSCSI multipath, dedicate two non-bonded NICs to multipath. Each of the two networks needs a unique name-label. - If no bonding is done, the administrator must set up and name-label the separate storage network on all hosts (masters and slaves). + You can optionally set up a separate storage network. This should be done first on the + host, before implementing the bonding steps below. This can be done using one or two + available NICs. With two NICs bonding may be done as above. It is the administrator's + responsibility to set up a separate storage network. + Give the storage network a different name-label than what will be given for other + networks. + For the separate storage network to work correctly, it must be the only interface that + can ping the primary storage device's IP address. For example, if eth0 is the + management network NIC, ping -I eth0 <primary storage device IP> must fail. In all + deployments, secondary storage devices must be pingable from the management network NIC or + bond. If a secondary storage device has been placed on the storage network, it must also be + pingable via the storage network NIC or bond on the hosts as well. + You can set up two separate storage networks as well. For example, if you intend to + implement iSCSI multipath, dedicate two non-bonded NICs to multipath. Each of the two + networks needs a unique name-label. + If no bonding is done, the administrator must set up and name-label the separate storage + network on all hosts (masters and slaves). Here is an example to set up eth5 to access a storage network on 172.16.0.0/24. # xe pif-list host-name-label='hostname' device=eth5 -uuid ( RO) : ab0d3dd4-5744-8fae-9693-a022c7a3471d - device ( RO): eth5 +uuid(RO): ab0d3dd4-5744-8fae-9693-a022c7a3471d +device ( RO): eth5 #xe pif-reconfigure-ip DNS=172.16.3.3 gateway=172.16.0.1 IP=172.16.0.55 mode=static netmask=255.255.255.0 uuid=ab0d3dd4-5744-8fae-9693-a022c7a3471d -
-
+
+
NIC Bonding for XenServer (Optional) - XenServer supports Source Level Balancing (SLB) NIC bonding. Two NICs can be bonded together to carry public, private, and guest traffic, or some combination of these. Separate storage networks are also possible. Here are some example supported configurations: + XenServer supports Source Level Balancing (SLB) NIC bonding. Two NICs can be bonded + together to carry public, private, and guest traffic, or some combination of these. Separate + storage networks are also possible. Here are some example supported configurations: - 2 NICs on private, 2 NICs on public, 2 NICs on storage - 2 NICs on private, 1 NIC on public, storage uses management network - 2 NICs on private, 2 NICs on public, storage uses management network - 1 NIC for private, public, and storage + + 2 NICs on private, 2 NICs on public, 2 NICs on storage + + + 2 NICs on private, 1 NIC on public, storage uses management network + + + 2 NICs on private, 2 NICs on public, storage uses management network + + + 1 NIC for private, public, and storage + All NIC bonding is optional. - XenServer expects all nodes in a cluster will have the same network cabling and same bonds implemented. In an installation the master will be the first host that was added to the cluster and the slave hosts will be all subsequent hosts added to the cluster. The bonds present on the master set the expectation for hosts added to the cluster later. The procedure to set up bonds on the master and slaves are different, and are described below. There are several important implications of this: + XenServer expects all nodes in a cluster will have the same network cabling and same + bonds implemented. In an installation the master will be the first host that was added to + the cluster and the slave hosts will be all subsequent hosts added to the cluster. The bonds + present on the master set the expectation for hosts added to the cluster later. The + procedure to set up bonds on the master and slaves are different, and are described below. + There are several important implications of this: - You must set bonds on the first host added to a cluster. Then you must use xe commands as below to establish the same bonds in the second and subsequent hosts added to a cluster. - Slave hosts in a cluster must be cabled exactly the same as the master. For example, if eth0 is in the private bond on the master, it must be in the management network for added slave hosts. + + You must set bonds on the first host added to a cluster. Then you must use xe + commands as below to establish the same bonds in the second and subsequent hosts added + to a cluster. + + + Slave hosts in a cluster must be cabled exactly the same as the master. For example, + if eth0 is in the private bond on the master, it must be in the management network for + added slave hosts. +
- Management Network Bonding - The administrator must bond the management network NICs prior to adding the host to &PRODUCT;. + Management Network Bonding + The administrator must bond the management network NICs prior to adding the host to + &PRODUCT;.
- Creating a Private Bond on the First Host in the Cluster - Use the following steps to create a bond in XenServer. These steps should be run on only the first host in a cluster. This example creates the cloud-private network with two physical NICs (eth0 and eth1) bonded into it. - - - Find the physical NICs that you want to bond together. - -# xe pif-list host-name-label='hostname' device=eth0 + Creating a Private Bond on the First Host in the Cluster + Use the following steps to create a bond in XenServer. These steps should be run on + only the first host in a cluster. This example creates the cloud-private network with two + physical NICs (eth0 and eth1) bonded into it. + + + Find the physical NICs that you want to bond together. + # xe pif-list host-name-label='hostname' device=eth0 # xe pif-list host-name-label='hostname' device=eth1 - These command shows the eth0 and eth1 NICs and their UUIDs. Substitute the ethX devices of your choice. Call the UUID's returned by the above command slave1-UUID and slave2-UUID. - - - Create a new network for the bond. For example, a new network with name "cloud-private". - This label is important. &PRODUCT; looks for a network by a name you configure. You must use the same name-label for all hosts in the cloud for the management network. - -# xe network-create name-label=cloud-private + These command shows the eth0 and eth1 NICs and their UUIDs. Substitute the ethX + devices of your choice. Call the UUID's returned by the above command slave1-UUID + and slave2-UUID. + + + Create a new network for the bond. For example, a new network with name + "cloud-private". + This label is important. &PRODUCT; looks for a network by a + name you configure. You must use the same name-label for all hosts in the cloud for + the management network. + # xe network-create name-label=cloud-private # xe bond-create network-uuid=[uuid of cloud-private created above] pif-uuids=[slave1-uuid],[slave2-uuid] - - - Now you have a bonded pair that can be recognized by &PRODUCT; as the management network. + + + Now you have a bonded pair that can be recognized by &PRODUCT; as the management + network.
- Public Network Bonding - Bonding can be implemented on a separate, public network. The administrator is responsible for creating a bond for the public network if that network will be bonded and will be separate from the management network. + Public Network Bonding + Bonding can be implemented on a separate, public network. The administrator is + responsible for creating a bond for the public network if that network will be bonded and + will be separate from the management network.
- Creating a Public Bond on the First Host in the Cluster - These steps should be run on only the first host in a cluster. This example creates the cloud-public network with two physical NICs (eth2 and eth3) bonded into it. - - - Find the physical NICs that you want to bond together. - -#xe pif-list host-name-label='hostname' device=eth2 + Creating a Public Bond on the First Host in the Cluster + These steps should be run on only the first host in a cluster. This example creates + the cloud-public network with two physical NICs (eth2 and eth3) bonded into it. + + + Find the physical NICs that you want to bond together. + #xe pif-list host-name-label='hostname' device=eth2 # xe pif-list host-name-label='hostname' device=eth3 - These command shows the eth2 and eth3 NICs and their UUIDs. Substitute the ethX devices of your choice. Call the UUID's returned by the above command slave1-UUID and slave2-UUID. - - - Create a new network for the bond. For example, a new network with name "cloud-public". - This label is important. &PRODUCT; looks for a network by a name you configure. You must use the same name-label for all hosts in the cloud for the public network. - -# xe network-create name-label=cloud-public + These command shows the eth2 and eth3 NICs and their UUIDs. Substitute the ethX + devices of your choice. Call the UUID's returned by the above command slave1-UUID + and slave2-UUID. + + + Create a new network for the bond. For example, a new network with name + "cloud-public". + This label is important. &PRODUCT; looks for a network by a + name you configure. You must use the same name-label for all hosts in the cloud for + the public network. + # xe network-create name-label=cloud-public # xe bond-create network-uuid=[uuid of cloud-public created above] pif-uuids=[slave1-uuid],[slave2-uuid] - - - Now you have a bonded pair that can be recognized by &PRODUCT; as the public network. + + + Now you have a bonded pair that can be recognized by &PRODUCT; as the public + network.
- Adding More Hosts to the Cluster - With the bonds (if any) established on the master, you should add additional, slave hosts. Run the following command for all additional hosts to be added to the cluster. This will cause the host to join the master in a single XenServer pool. - -# xe pool-join master-address=[master IP] master-username=root + Adding More Hosts to the Cluster + With the bonds (if any) established on the master, you should add additional, slave + hosts. Run the following command for all additional hosts to be added to the cluster. This + will cause the host to join the master in a single XenServer pool. + # xe pool-join master-address=[master IP] master-username=root master-password=[your password]
- Complete the Bonding Setup Across the Cluster - With all hosts added to the pool, run the cloud-setup-bond script. This script will complete the configuration and set up of the bonds across all hosts in the cluster. - - Copy the script from the Management Server in /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/cloud-setup-bonding.sh to the master host and ensure it is executable. - - Run the script: - # ./cloud-setup-bonding.sh - - - Now the bonds are set up and configured properly across the cluster. + Complete the Bonding Setup Across the Cluster + With all hosts added to the pool, run the cloud-setup-bond script. This script will + complete the configuration and set up of the bonds across all hosts in the cluster. + + + Copy the script from the Management Server in + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/cloud-setup-bonding.sh to the + master host and ensure it is executable. + + + Run the script: + # ./cloud-setup-bonding.sh + + + Now the bonds are set up and configured properly across the cluster.
-
-
- Upgrading XenServer Versions - This section tells how to upgrade XenServer software on &PRODUCT; hosts. The actual upgrade is described in XenServer documentation, but there are some additional steps you must perform before and after the upgrade. - Be sure the hardware is certified compatible with the new version of XenServer. - To upgrade XenServer: - +
+
+ Upgrading XenServer Versions + This section tells how to upgrade XenServer software on &PRODUCT; hosts. The actual + upgrade is described in XenServer documentation, but there are some additional steps you must + perform before and after the upgrade. + + Be sure the hardware is certified compatible with the new version of XenServer. + + To upgrade XenServer: + - Upgrade the database. On the Management Server node: - - - Back up the database: - -# mysqldump --user=root --databases cloud > cloud.backup.sql + Upgrade the database. On the Management Server node: + + + Back up the database: + # mysqldump --user=root --databases cloud > cloud.backup.sql # mysqldump --user=root --databases cloud_usage > cloud_usage.backup.sql - - - You might need to change the OS type settings for VMs running on the upgraded hosts. - - If you upgraded from XenServer 5.6 GA to XenServer 5.6 SP2, change any VMs that have the OS type CentOS 5.5 (32-bit), Oracle Enterprise Linux 5.5 (32-bit), or Red Hat Enterprise Linux 5.5 (32-bit) to Other Linux (32-bit). Change any VMs that have the 64-bit versions of these same OS types to Other Linux (64-bit). - If you upgraded from XenServer 5.6 SP2 to XenServer 6.0.2, change any VMs that have the OS type CentOS 5.6 (32-bit), CentOS 5.7 (32-bit), Oracle Enterprise Linux 5.6 (32-bit), Oracle Enterprise Linux 5.7 (32-bit), Red Hat Enterprise Linux 5.6 (32-bit) , or Red Hat Enterprise Linux 5.7 (32-bit) to Other Linux (32-bit). Change any VMs that have the 64-bit versions of these same OS types to Other Linux (64-bit). - If you upgraded from XenServer 5.6 to XenServer 6.0.2, do all of the above. - - - - Restart the Management Server and Usage Server. You only need to do this once for all clusters. - -# service cloud-management start + + + You might need to change the OS type settings for VMs running on the upgraded + hosts. + + + If you upgraded from XenServer 5.6 GA to XenServer 5.6 SP2, change any VMs + that have the OS type CentOS 5.5 (32-bit), Oracle Enterprise Linux 5.5 (32-bit), + or Red Hat Enterprise Linux 5.5 (32-bit) to Other Linux (32-bit). Change any VMs + that have the 64-bit versions of these same OS types to Other Linux + (64-bit). + + + If you upgraded from XenServer 5.6 SP2 to XenServer 6.0.2, change any VMs that + have the OS type CentOS 5.6 (32-bit), CentOS 5.7 (32-bit), Oracle Enterprise Linux + 5.6 (32-bit), Oracle Enterprise Linux 5.7 (32-bit), Red Hat Enterprise Linux 5.6 + (32-bit) , or Red Hat Enterprise Linux 5.7 (32-bit) to Other Linux (32-bit). + Change any VMs that have the 64-bit versions of these same OS types to Other Linux + (64-bit). + + + If you upgraded from XenServer 5.6 to XenServer 6.0.2, do all of the + above. + + + + + Restart the Management Server and Usage Server. You only need to do this once for + all clusters. + # service cloud-management start # service cloud-usage start - - + + - Disconnect the XenServer cluster from &PRODUCT;. - - Log in to the &PRODUCT; UI as root. - Navigate to the XenServer cluster, and click Actions – Unmanage. - Watch the cluster status until it shows Unmanaged. - + Disconnect the XenServer cluster from &PRODUCT;. + + + Log in to the &PRODUCT; UI as root. + + + Navigate to the XenServer cluster, and click Actions – Unmanage. + + + Watch the cluster status until it shows Unmanaged. + + - Log in to one of the hosts in the cluster, and run this command to clean up the VLAN: - # . /opt/xensource/bin/cloud-clean-vlan.sh + Log in to one of the hosts in the cluster, and run this command to clean up the + VLAN: + # . /opt/xensource/bin/cloud-clean-vlan.sh - Still logged in to the host, run the upgrade preparation script: - # /opt/xensource/bin/cloud-prepare-upgrade.sh - Troubleshooting: If you see the error "can't eject CD," log in to the VM and umount the CD, then run the script again. + Still logged in to the host, run the upgrade preparation script: + # /opt/xensource/bin/cloud-prepare-upgrade.sh + Troubleshooting: If you see the error "can't eject CD," log in to the + VM and umount the CD, then run the script again. - Upgrade the XenServer software on all hosts in the cluster. Upgrade the master first. - - - Live migrate all VMs on this host to other hosts. See the instructions for live migration in the Administrator's Guide. - Troubleshooting: You might see the following error when you migrate a VM: - -[root@xenserver-qa-2-49-4 ~]# xe vm-migrate live=true host=xenserver-qa-2-49-5 vm=i-2-8-VM + Upgrade the XenServer software on all hosts in the cluster. Upgrade the master + first. + + + Live migrate all VMs on this host to other hosts. See the instructions for live + migration in the Administrator's Guide. + Troubleshooting: You might see the following error when you migrate a VM: + [root@xenserver-qa-2-49-4 ~]# xe vm-migrate live=true host=xenserver-qa-2-49-5 vm=i-2-8-VM You attempted an operation on a VM which requires PV drivers to be installed but the drivers were not detected. vm: b6cf79c8-02ee-050b-922f-49583d9f1a14 (i-2-8-VM) - To solve this issue, run the following: - # /opt/xensource/bin/make_migratable.sh b6cf79c8-02ee-050b-922f-49583d9f1a14 - - Reboot the host. - Upgrade to the newer version of XenServer. Use the steps in XenServer documentation. - - After the upgrade is complete, copy the following files from the management server to this host, in the directory locations shown below: - - - - -
- - Copy this Management Server file... - ...to this location on the XenServer host - - - - - /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py - /opt/xensource/sm/NFSSR.py - - - /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/setupxenserver.sh - /opt/xensource/bin/setupxenserver.sh - - - /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/make_migratable.sh - /opt/xensource/bin/make_migratable.sh - - - /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/cloud-clean-vlan.sh - /opt/xensource/bin/cloud-clean-vlan.sh - - - - - - - Run the following script: - # /opt/xensource/bin/setupxenserver.sh - Troubleshooting: If you see the following error message, you can safely ignore it. - mv: cannot stat `/etc/cron.daily/logrotate': No such file or directory - - - Plug in the storage repositories (physical block devices) to the XenServer host: - # for pbd in `xe pbd-list currently-attached=false| grep ^uuid | awk '{print $NF}'`; do xe pbd-plug uuid=$pbd ; done - Note: If you add a host to this XenServer pool, you need to migrate all VMs on this host to other hosts, and eject this host from XenServer pool. - + To solve this issue, run the following: + # /opt/xensource/bin/make_migratable.sh b6cf79c8-02ee-050b-922f-49583d9f1a14 + + + Reboot the host. + + + Upgrade to the newer version of XenServer. Use the steps in XenServer + documentation. + + + After the upgrade is complete, copy the following files from the management server + to this host, in the directory locations shown below: + + + + + + + Copy this Management Server file... + ...to this location on the XenServer host + + + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py + /opt/xensource/sm/NFSSR.py + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/setupxenserver.sh + /opt/xensource/bin/setupxenserver.sh + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/make_migratable.sh + /opt/xensource/bin/make_migratable.sh + + + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/cloud-clean-vlan.sh + /opt/xensource/bin/cloud-clean-vlan.sh + + + + + + + Run the following script: + # /opt/xensource/bin/setupxenserver.sh + Troubleshooting: If you see the following error message, you can safely ignore + it. + mv: cannot stat `/etc/cron.daily/logrotate': No such file or directory + + + Plug in the storage repositories (physical block devices) to the XenServer + host: + # for pbd in `xe pbd-list currently-attached=false| grep ^uuid | awk '{print $NF}'`; do xe pbd-plug uuid=$pbd ; done + Note: If you add a host to this XenServer pool, you need to migrate all VMs on + this host to other hosts, and eject this host from XenServer pool. + + + + + Repeat these steps to upgrade every host in the cluster to the same version of + XenServer. + + + Run the following command on one host in the XenServer cluster to clean up the host + tags: + # for host in $(xe host-list | grep ^uuid | awk '{print $NF}') ; do xe host-param-clear uuid=$host param-name=tags; done; + + When copying and pasting a command, be sure the command has pasted as a single line + before executing. Some document viewers may introduce unwanted line breaks in copied + text. + + + + Reconnect the XenServer cluster to &PRODUCT;. + + + Log in to the &PRODUCT; UI as root. + + + Navigate to the XenServer cluster, and click Actions – Manage. + + + Watch the status to see that all the hosts come up. + + + + + After all hosts are up, run the following on one host in the cluster: + # /opt/xensource/bin/cloud-clean-vlan.sh + - - Repeat these steps to upgrade every host in the cluster to the same version of XenServer. - - Run the following command on one host in the XenServer cluster to clean up the host tags: - # for host in $(xe host-list | grep ^uuid | awk '{print $NF}') ; do xe host-param-clear uuid=$host param-name=tags; done; - When copying and pasting a command, be sure the command has pasted as a single line before executing. Some document viewers may introduce unwanted line breaks in copied text. - - - Reconnect the XenServer cluster to &PRODUCT;. - - Log in to the &PRODUCT; UI as root. - Navigate to the XenServer cluster, and click Actions – Manage. - Watch the status to see that all the hosts come up. - - - - After all hosts are up, run the following on one host in the cluster: - # /opt/xensource/bin/cloud-clean-vlan.sh - - - + diff --git a/docs/en-US/cloud-infrastructure-overview.xml b/docs/en-US/cloud-infrastructure-overview.xml index 32f2246eeb8..49a413871a5 100644 --- a/docs/en-US/cloud-infrastructure-overview.xml +++ b/docs/en-US/cloud-infrastructure-overview.xml @@ -25,15 +25,48 @@
Cloud Infrastructure Overview - The Management Server manages one or more zones (typically, datacenters) containing host computers where guest virtual machines will run. The cloud infrastructure is organized as follows: + The Management Server manages one or more zones (typically, + datacenters) containing host computers where guest virtual + machines will run. The cloud infrastructure is organized as follows: - Zone: Typically, a zone is equivalent to a single datacenter. A zone consists of one or more pods and secondary storage. - Pod: A pod is usually one rack of hardware that includes a layer-2 switch and one or more clusters. - Cluster: A cluster consists of one or more hosts and primary storage. - Host: A single compute node within a cluster. The hosts are where the actual cloud services run in the form of guest virtual machines. - Primary storage is associated with a cluster, and it stores the disk volumes for all the VMs running on hosts in that cluster. - Secondary storage is associated with a zone, and it stores templates, ISO images, and disk volume snapshots. + + + Zone: Typically, a zone is equivalent to a single + datacenter. A zone consists of one or more pods and secondary + storage. + + + + + Pod: A pod is usually one rack of hardware that includes a + layer-2 switch and one or more clusters. + + + + + Cluster: A cluster consists of one or more hosts and primary + storage. + + + + + Host: A single compute node within a cluster. The hosts are + where the actual cloud services run in the form of guest + virtual machines. + + + + + Primary storage is associated with a cluster, and it stores + the disk volumes for all the VMs running on hosts in that cluster. + + + + Secondary storage is associated with a zone, and it stores + templates, ISO images, and disk volume snapshots. + + diff --git a/docs/en-US/cloudplatform-api.xml b/docs/en-US/cloudstack-api.xml similarity index 98% rename from docs/en-US/cloudplatform-api.xml rename to docs/en-US/cloudstack-api.xml index 3c4a91481d0..891b19f580b 100644 --- a/docs/en-US/cloudplatform-api.xml +++ b/docs/en-US/cloudstack-api.xml @@ -22,7 +22,7 @@ under the License. --> -
+
&PRODUCT; API The &PRODUCT; API is a low level API that has been used to implement the &PRODUCT; web UIs. It is also a good basis for implementing other popular APIs such as EC2/S3 and emerging DMTF standards. Many &PRODUCT; API calls are asynchronous. These will return a Job ID immediately when called. This Job ID can be used to query the status of the job later. Also, status calls on impacted resources will provide some indication of their state. diff --git a/docs/en-US/cloudstack.xml b/docs/en-US/cloudstack.xml index 906eadc24a6..0b762a2da1f 100644 --- a/docs/en-US/cloudstack.xml +++ b/docs/en-US/cloudstack.xml @@ -23,20 +23,41 @@ --> - + + &PRODUCT; Complete Documentation + Apache CloudStack + 4.0.0-incubating + 1 + + + + Complete documentation for &PRODUCT;. + + + + + + + + + + + + - - + - - - - - - - + + + + + + + + + @@ -49,8 +70,11 @@ - + + + + - \ No newline at end of file + diff --git a/docs/en-US/cluster-add.xml b/docs/en-US/cluster-add.xml index 89f9bd2dc9d..3046c5e0dfd 100644 --- a/docs/en-US/cluster-add.xml +++ b/docs/en-US/cluster-add.xml @@ -26,6 +26,6 @@ Adding a Cluster You need to tell &PRODUCT; about the hosts that it will manage. Hosts exist inside clusters, so before you begin adding hosts to the cloud, you must add at least one cluster. - +
diff --git a/docs/en-US/configure-package-repository.xml b/docs/en-US/configure-package-repository.xml index 50b7720d3de..9ef2307b105 100644 --- a/docs/en-US/configure-package-repository.xml +++ b/docs/en-US/configure-package-repository.xml @@ -24,23 +24,46 @@
Configure package repository - &PRODUCT; is only distributed from source from the official mirrors. DEB and RPM packages are however build for your convience by third-parties - When installing &PRODUCT; it is recommended you use these package repositories for easy installation. + &PRODUCT; is only distributed from source from the official mirrors. + However, members of the CloudStack community may build convenience binaries + so that users can install Apache CloudStack without needing to build from + source. + + + If you didn't follow the steps to build your own packages from source + in the sections for or + you may find pre-built + DEB and RPM packages for your convience linked from the + downloads + page. + These repositories contain both the Management Server and KVM Hypervisor packages.
DEB package repository - You can add a DEB package repository to your apt sources with the following commands. Please note that currently only packages for Ubuntu 12.04 (precise) are being build. - echo "deb http://cloudstack.apt-get.eu/ubuntu $(lsb_release -s -c) 4.0" > /etc/apt/sources.list.d/cloudstack.list + You can add a DEB package repository to your apt sources with the following commands. Please note that only packages for Ubuntu 12.04 LTS (precise) are being built at this time. + Use your preferred editor and open (or create) /etc/apt/sources.list.d/cloudstack.list. Add the community provided repository to the file: +deb http://cloudstack.apt-get.eu/ubuntu precise 4.0 We now have to add the public key to the trusted keys. - wget -O - http://cloudstack.apt-get.eu/release.asc|apt-key add - + $ wget -O - http://cloudstack.apt-get.eu/release.asc|apt-key add - Now update your local apt cache. - apt-get update + $ apt-get update Your DEB package repository should now be configured and ready for use.
RPM package repository - TODO + There is a RPM package repository for &PRODUCT; so you can easily install on RHEL based platforms. + If you're using an RPM-based system, you'll want to add the Yum repository so that you can install &PRODUCT; with Yum. + Yum repository information is found under /etc/yum.repos.d. You'll see several .repo files in this directory, each one denoting a specific repository. + To add the &PRODUCT; repository, create /etc/yum.repos.d/cloudstack.repo and insert the following information. + +[cloudstack] +name=cloudstack +baseurl=http://cloudstack.apt-get.eu/rhel/4.0/ +enabled=1 +gpgcheck=0 + + Now you should be able to install CloudStack using Yum.
-
\ No newline at end of file +
diff --git a/docs/en-US/configuring-projects.xml b/docs/en-US/configuring-projects.xml index 0f84dd81454..af1fc5323e3 100644 --- a/docs/en-US/configuring-projects.xml +++ b/docs/en-US/configuring-projects.xml @@ -22,7 +22,7 @@ ]>
Configuring Projects - Before CloudPlatform users start using projects, the CloudPlatform administrator must set + Before &PRODUCT; users start using projects, the &PRODUCT; administrator must set up various systems to support them, including membership invitations, limits on project resources, and controls on who can create projects. diff --git a/docs/en-US/create-template-from-snapshot.xml b/docs/en-US/create-template-from-snapshot.xml index b212adcfba5..d9684226671 100644 --- a/docs/en-US/create-template-from-snapshot.xml +++ b/docs/en-US/create-template-from-snapshot.xml @@ -23,9 +23,6 @@ -->
Creating a Template from a Snapshot - Not supported by Oracle VM. - - If you do not want to stop the VM to use the Create Template menu item, as described in - ), you can create a template directly - from any snapshot through the &PRODUCT; UI. + + If you do not want to stop the VM in order to use the Create Template menu item (as described in ), you can create a template directly from any snapshot through the &PRODUCT; UI.
diff --git a/docs/en-US/create-vpn-customer-gateway.xml b/docs/en-US/create-vpn-customer-gateway.xml index bf56e36e8b9..8bcd488160c 100644 --- a/docs/en-US/create-vpn-customer-gateway.xml +++ b/docs/en-US/create-vpn-customer-gateway.xml @@ -188,4 +188,4 @@ Click OK. -
\ No newline at end of file +
diff --git a/docs/en-US/creating-vms.xml b/docs/en-US/creating-vms.xml index beb528f3908..86d89fd2e92 100644 --- a/docs/en-US/creating-vms.xml +++ b/docs/en-US/creating-vms.xml @@ -49,7 +49,7 @@ Select a zone.Select ISO Boot, and follow the steps in the wizard.Click Submit and your VM will be created and started. - (Oracle VM only) After ISO installation, the installer reboots into the operating system. Due to a known issue in OVM, the reboot will place the VM in the Stopped state. In the &PRODUCT; UI, detach the ISO from the VM (so that the VM will not boot from the ISO again), then click the Start button to restart the VM. + diff --git a/docs/en-US/database-replication.xml b/docs/en-US/database-replication.xml new file mode 100644 index 00000000000..718c34959da --- /dev/null +++ b/docs/en-US/database-replication.xml @@ -0,0 +1,136 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Database Replication (Optional) + &PRODUCT; supports database replication from one MySQL node to another. This is achieved using standard MySQL replication. You may want to do this as insurance against MySQL server or storage loss. MySQL replication is implemented using a master/slave model. The master is the node that the Management Servers are configured to use. The slave is a standby node that receives all write operations from the master and applies them to a local, redundant copy of the database. The following steps are a guide to implementing MySQL replication. + Creating a replica is not a backup solution. You should develop a backup procedure for the MySQL data that is distinct from replication. + + Ensure that this is a fresh install with no data in the master. + + Edit my.cnf on the master and add the following in the [mysqld] section below datadir. + +log_bin=mysql-bin +server_id=1 + + The server_id must be unique with respect to other servers. The recommended way to achieve this is to give the master an ID of 1 and each slave a sequential number greater than 1, so that the servers are numbered 1, 2, 3, etc. + + + Restart the MySQL service: + +# service mysqld restart + + + + Create a replication account on the master and give it privileges. We will use the "cloud-repl" user with the password "password". This assumes that master and slave run on the 172.16.1.0/24 network. + +# mysql -u root +mysql> create user 'cloud-repl'@'172.16.1.%' identified by 'password'; +mysql> grant replication slave on *.* TO 'cloud-repl'@'172.16.1.%'; +mysql> flush privileges; +mysql> flush tables with read lock; + + + Leave the current MySQL session running. + In a new shell start a second MySQL session. + + Retrieve the current position of the database. + +# mysql -u root +mysql> show master status; ++------------------+----------+--------------+------------------+ +| File | Position | Binlog_Do_DB | Binlog_Ignore_DB | ++------------------+----------+--------------+------------------+ +| mysql-bin.000001 | 412 | | | ++------------------+----------+--------------+------------------+ + + + Note the file and the position that are returned by your instance. + Exit from this session. + + Complete the master setup. Returning to your first session on the master, release the locks and exit MySQL. + +mysql> unlock tables; + + + + Install and configure the slave. On the slave server, run the following commands. + +# yum install mysql-server +# chkconfig mysqld on + + + + Edit my.cnf and add the following lines in the [mysqld] section below datadir. + +server_id=2 +innodb_rollback_on_timeout=1 +innodb_lock_wait_timeout=600 + + + + Restart MySQL. + +# service mysqld restart + + + + Instruct the slave to connect to and replicate from the master. Replace the IP address, password, log file, and position with the values you have used in the previous steps. + +mysql> change master to + -> master_host='172.16.1.217', + -> master_user='cloud-repl', + -> master_password='password', + -> master_log_file='mysql-bin.000001', + -> master_log_pos=412; + + + + Then start replication on the slave. + +mysql> start slave; + + + + Optionally, open port 3306 on the slave as was done on the master earlier. + This is not required for replication to work. But if you choose not to do this, you will need to do it when failover to the replica occurs. + + +
+ Failover + This will provide for a replicated database that can be used to implement manual failover for the Management Servers. &PRODUCT; failover from one MySQL instance to another is performed by the administrator. In the event of a database failure you should: + + Stop the Management Servers (via service cloud-management stop). + Change the replica's configuration to be a master and restart it. + Ensure that the replica's port 3306 is open to the Management Servers. + Make a change so that the Management Server uses the new database. The simplest process here is to put the IP address of the new database server into each Management Server's /etc/cloud/management/db.properties. + + Restart the Management Servers: + +# service cloud-management start + + + +
+
diff --git a/docs/en-US/dell62xx-hardware.xml b/docs/en-US/dell62xx-hardware.xml new file mode 100644 index 00000000000..8bc7770ce86 --- /dev/null +++ b/docs/en-US/dell62xx-hardware.xml @@ -0,0 +1,53 @@ + + +%BOOK_ENTITIES; +]> + +
+ Dell 62xx + The following steps show how a Dell 62xx is configured for zone-level layer-3 switching. + These steps assume VLAN 201 is used to route untagged private IPs for pod 1, and pod 1’s layer-2 + switch is connected to Ethernet port 1/g1. + The Dell 62xx Series switch supports up to 1024 VLANs. + + + Configure all the VLANs in the database. + vlan database +vlan 200-999 +exit + + + Configure Ethernet port 1/g1. + interface ethernet 1/g1 +switchport mode general +switchport general pvid 201 +switchport general allowed vlan add 201 untagged +switchport general allowed vlan add 300-999 tagged +exit + + + The statements configure Ethernet port 1/g1 as follows: + + + VLAN 201 is the native untagged VLAN for port 1/g1. + + + All VLANs (300-999) are passed to all the pod-level layer-2 switches. + + +
diff --git a/docs/en-US/dell62xx-layer2.xml b/docs/en-US/dell62xx-layer2.xml new file mode 100644 index 00000000000..1c0eea07203 --- /dev/null +++ b/docs/en-US/dell62xx-layer2.xml @@ -0,0 +1,49 @@ + + +%BOOK_ENTITIES; +]> + +
+ Dell 62xx + The following steps show how a Dell 62xx is configured for pod-level layer-2 + switching. + + + Configure all the VLANs in the database. + vlan database +vlan 300-999 +exit + + + VLAN 201 is used to route untagged private IP addresses for pod 1, and pod 1 is connected to this layer-2 switch. + interface range ethernet all +switchport mode general +switchport general allowed vlan add 300-999 tagged +exit + + + The statements configure all Ethernet ports to function as follows: + + + All ports are configured the same way. + + + All VLANs (300-999) are passed through all the ports of the layer-2 switch. + + +
diff --git a/docs/en-US/deployment-architecture-overview.xml b/docs/en-US/deployment-architecture-overview.xml index 1df0a5291fb..fba36eb85a3 100644 --- a/docs/en-US/deployment-architecture-overview.xml +++ b/docs/en-US/deployment-architecture-overview.xml @@ -24,10 +24,19 @@
Deployment Architecture Overview - A &PRODUCT; installation consists of two parts: the Management Server and the cloud infrastructure that it manages. When you set up and manage a &PRODUCT; cloud, you provision resources such as hosts, storage devices, and IP addresses into the Management Server, and the Management Server manages those resources. + A &PRODUCT; installation consists of two parts: the Management Server + and the cloud infrastructure that it manages. When you set up and + manage a &PRODUCT; cloud, you provision resources such as hosts, + storage devices, and IP addresses into the Management Server, and + the Management Server manages those resources. - The minimum production installation consists of one machine running the &PRODUCT; Management Server and another machine to act as the cloud infrastructure (in this case, a very simple infrastructure consisting of one host running hypervisor software). In a trial installation, a single machine can act as both the Management Server and the hypervisor host (using the KVM hypervisor). + The minimum production installation consists of one machine running + the &PRODUCT; Management Server and another machine to act as the + cloud infrastructure (in this case, a very simple infrastructure + consisting of one host running hypervisor software). In its smallest + deployment, a single machine can act as both the Management Server + and the hypervisor host (using the KVM hypervisor). @@ -35,7 +44,11 @@ basic-deployment.png: Basic two-machine deployment - A more full-featured installation consists of a highly-available multi-node Management Server installation and up to thousands of hosts using any of several advanced networking setups. For information about deployment options, see Choosing a Deployment Architecture. + + A more full-featured installation consists of a highly-available + multi-node Management Server installation and up to tens of thousands of + hosts using any of several advanced networking setups. For + information about deployment options, see Choosing a Deployment Architecture. diff --git a/docs/en-US/detach-move-volumes.xml b/docs/en-US/detach-move-volumes.xml index a902fdba432..fda6e66cede 100644 --- a/docs/en-US/detach-move-volumes.xml +++ b/docs/en-US/detach-move-volumes.xml @@ -26,7 +26,7 @@ This procedure is different from moving disk volumes from one storage pool to another. See VM Storage Migration A volume can be detached from a guest VM and attached to another guest. Both &PRODUCT; administrators and users can detach volumes from VMs and move them to other VMs. If the two VMs are in different clusters, and the volume is large, it may take several minutes for the volume to be moved to the new VM. - If the destination VM is running in the OVM hypervisor, the VM must be stopped before a new volume can be attached to it. + Log in to the &PRODUCT; UI as a user or admin. In the left navigation bar, click Storage, and choose Volumes in Select View. Alternatively, if you know which VM the volume is attached to, you can click Instances, click the VM name, and click View Volumes. 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 5b9964e5380..9d54f31dae9 100644 --- a/docs/en-US/developer-introduction.xml +++ b/docs/en-US/developer-introduction.xml @@ -22,9 +22,9 @@ under the License. --> -
- Introduction for Developers + + Introduction to the &PRODUCT; API -
+ diff --git a/docs/en-US/developer_guide.xml b/docs/en-US/developer_guide.xml deleted file mode 100644 index 18ef88a4c68..00000000000 --- a/docs/en-US/developer_guide.xml +++ /dev/null @@ -1,39 +0,0 @@ - - -%BOOK_ENTITIES; -]> - - - - - Developer Guide - - - - - - - - - - - - - diff --git a/docs/en-US/event-types.xml b/docs/en-US/event-types.xml index 56059e1a54c..5ce585763de 100644 --- a/docs/en-US/event-types.xml +++ b/docs/en-US/event-types.xml @@ -21,6 +21,7 @@ specific language governing permissions and limitations under the License. --> + Event Types @@ -216,4 +217,4 @@ - \ No newline at end of file + diff --git a/docs/en-US/external-fw-topology-req.xml b/docs/en-US/external-fw-topology-req.xml new file mode 100644 index 00000000000..ab81496a30a --- /dev/null +++ b/docs/en-US/external-fw-topology-req.xml @@ -0,0 +1,25 @@ + + +%BOOK_ENTITIES; +]> + +
+ External Firewall Topology Requirements + When external firewall integration is in place, the public IP VLAN must still be trunked to + the Hosts. This is required to support the Secondary Storage VM and Console Proxy VM. +
diff --git a/docs/en-US/external-guest-firewall-integration.xml b/docs/en-US/external-guest-firewall-integration.xml new file mode 100644 index 00000000000..0b34dca1065 --- /dev/null +++ b/docs/en-US/external-guest-firewall-integration.xml @@ -0,0 +1,201 @@ + + +%BOOK_ENTITIES; +]> + +
+ External Guest Firewall Integration for Juniper SRX (Optional) + + Available only for guests using advanced networking. + + &PRODUCT; provides for direct management of the Juniper SRX series of firewalls. This + enables &PRODUCT; to establish static NAT mappings from public IPs to guest VMs, and to use + the Juniper device in place of the virtual router for firewall services. You can have one or + more Juniper SRX per zone. This feature is optional. If Juniper integration is not provisioned, + &PRODUCT; will use the virtual router for these services. + The Juniper SRX can optionally be used in conjunction with an external load balancer. + External Network elements can be deployed in a side-by-side or inline configuration. + + + + + + parallel-mode.png: adding a firewall and load balancer in parallel mode. + + + &PRODUCT; requires the Juniper to be configured as follows: + + Supported SRX software version is 10.3 or higher. + + + + Install your SRX appliance according to the vendor's instructions. + + + Connect one interface to the management network and one interface to the public network. + Alternatively, you can connect the same interface to both networks and a use a VLAN for the + public network. + + + Make sure "vlan-tagging" is enabled on the private interface. + + + Record the public and private interface names. If you used a VLAN for the public + interface, add a ".[VLAN TAG]" after the interface name. For example, if you are using + ge-0/0/3 for your public interface and VLAN tag 301, your public interface name would be + "ge-0/0/3.301". Your private interface name should always be untagged because the + &PRODUCT; software automatically creates tagged logical interfaces. + + + Create a public security zone and a private security zone. By default, these will + already exist and will be called "untrust" and "trust". Add the public interface to the + public zone and the private interface to the private zone. Note down the security zone + names. + + + Make sure there is a security policy from the private zone to the public zone that + allows all traffic. + + + Note the username and password of the account you want the &PRODUCT; software to log + in to when it is programming rules. + + + Make sure the "ssh" and "xnm-clear-text" system services are enabled. + + + If traffic metering is desired: + + + a. Create an incoming firewall filter and an outgoing firewall filter. These filters + should be the same names as your public security zone name and private security zone + name respectively. The filters should be set to be "interface-specific". For example, + here is the configuration where the public zone is "untrust" and the private zone is + "trust": + root@cloud-srx# show firewall +filter trust { + interface-specific; +} +filter untrust { + interface-specific; +} + + + Add the firewall filters to your public interface. For example, a sample + configuration output (for public interface ge-0/0/3.0, public security zone untrust, and + private security zone trust) is: + ge-0/0/3 { + unit 0 { + family inet { + filter { + input untrust; + output trust; + } + address 172.25.0.252/16; + } + } +} + + + + + Make sure all VLANs are brought to the private interface of the SRX. + + + After the &PRODUCT; Management Server is installed, log in to the &PRODUCT; UI as + administrator. + + + In the left navigation bar, click Infrastructure. + + + In Zones, click View More. + + + Choose the zone you want to work with. + + + Click the Network tab. + + + In the Network Service Providers node of the diagram, click Configure. (You might have + to scroll down to see this.) + + + Click SRX. + + + Click the Add New SRX button (+) and provide the following: + + + IP Address: The IP address of the SRX. + + + Username: The user name of the account on the SRX that &PRODUCT; should use. + + + Password: The password of the account. + + + Public Interface. The name of the public interface on the SRX. For example, + ge-0/0/2. A ".x" at the end of the interface indicates the VLAN that is in use. + + + Private Interface: The name of the private interface on the SRX. For example, + ge-0/0/1. + + + Usage Interface: (Optional) Typically, the public interface is used to meter + traffic. If you want to use a different interface, specify its name here + + + Number of Retries: The number of times to attempt a command on the SRX before + failing. The default value is 2. + + + Timeout (seconds): The time to wait for a command on the SRX before considering it + failed. Default is 300 seconds. + + + Public Network: The name of the public network on the SRX. For example, + trust. + + + Private Network: The name of the private network on the SRX. For example, + untrust. + + + Capacity: The number of networks the device can handle + + + Dedicated: When marked as dedicated, this device will be dedicated to a single + account. When Dedicated is checked, the value in the Capacity field has no significance + implicitly, its value is 1 + + + + + Click OK. + + + Click Global Settings. Set the parameter external.network.stats.interval to indicate how + often you want &PRODUCT; to fetch network usage statistics from the Juniper SRX. If you + are not using the SRX to gather network usage statistics, set to 0. + + +
diff --git a/docs/en-US/external-guest-lb-integration.xml b/docs/en-US/external-guest-lb-integration.xml new file mode 100644 index 00000000000..5760f9559e6 --- /dev/null +++ b/docs/en-US/external-guest-lb-integration.xml @@ -0,0 +1,109 @@ + + +%BOOK_ENTITIES; +]> + +
+ External Guest Load Balancer Integration (Optional) + &PRODUCT; can optionally use a Citrix NetScaler or BigIP F5 load balancer to provide load + balancing services to guests. If this is not enabled, &PRODUCT; will use the software load + balancer in the virtual router. + To install and enable an external load balancer for &PRODUCT; management: + + + Set up the appliance according to the vendor's directions. + + + Connect it to the networks carrying public traffic and management traffic (these could + be the same network). + + + Record the IP address, username, password, public interface name, and private interface + name. The interface names will be something like "1.1" or "1.2". + + + Make sure that the VLANs are trunked to the management network interface. + + + After the &PRODUCT; Management Server is installed, log in as administrator to the + &PRODUCT; UI. + + + In the left navigation bar, click Infrastructure. + + + In Zones, click View More. + + + Choose the zone you want to work with. + + + Click the Network tab. + + + In the Network Service Providers node of the diagram, click Configure. (You might have + to scroll down to see this.) + + + Click NetScaler or F5. + + + Click the Add button (+) and provide the following: + For NetScaler: + + + IP Address: The IP address of the SRX. + + + Username/Password: The authentication credentials to access the device. &PRODUCT; + uses these credentials to access the device. + + + Type: The type of device that is being added. It could be F5 Big Ip Load Balancer, + NetScaler VPX, NetScaler MPX, or NetScaler SDX. For a comparison of the NetScaler types, + see the &PRODUCT; Administration Guide. + + + Public interface: Interface of device that is configured to be part of the public + network. + + + Private interface: Interface of device that is configured to be part of the private + network. + + + Number of retries. Number of times to attempt a command on the device before + considering the operation failed. Default is 2. + + + Capacity: The number of networks the device can handle. + + + Dedicated: When marked as dedicated, this device will be dedicated to a single + account. When Dedicated is checked, the value in the Capacity field has no significance + implicitly, its value is 1. + + + + + Click OK. + + + The installation and provisioning of the external load balancer is finished. You can proceed + to add VMs and NAT or load balancing rules. +
diff --git a/docs/en-US/extracting-source.xml b/docs/en-US/extracting-source.xml new file mode 100644 index 00000000000..97a40b66213 --- /dev/null +++ b/docs/en-US/extracting-source.xml @@ -0,0 +1,36 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Extracting source + + Extracting the &PRODUCT; release is relatively simple and can be done + with a single command as follows: + $ tar -jxvf apache-cloudstack-4.0.0-incubating-src.tar.bz2 + + + You can now move into the directory: + $ cd ./apache-cloudstack-4.0.0-incubating-src + +
diff --git a/docs/en-US/feature-overview.xml b/docs/en-US/feature-overview.xml index f0739cad327..a05078f8606 100644 --- a/docs/en-US/feature-overview.xml +++ b/docs/en-US/feature-overview.xml @@ -27,11 +27,8 @@ Multiple Hypervisor Support
- &PRODUCT; works with a variety of hypervisors. A single cloud deployment can contain multiple hypervisor implementations. You have the complete freedom to choose the right hypervisor for your workload. - - &PRODUCT; is designed to work with open source Xen and KVM hypervisors as well as - enterprise-grade hypervisors such as Citrix XenServer, VMware vSphere, and Oracle VM - (OVM). + &PRODUCT; works with a variety of hypervisors, and a single cloud deployment can contain multiple hypervisor implementations. The current release of &PRODUCT; supports pre-packaged enterprise solutions like Citrix XenServer and VMware vSphere, as well as KVM or Xen running on Ubuntu or CentOS. + Massively Scalable Infrastructure Management @@ -54,14 +51,31 @@ API and Extensibility - &PRODUCT; provides an API that gives programmatic access to all the management features available in the UI. The API is maintained and documented. This API enables the creation of command line tools and new user interfaces to suit particular needs. See the Developer’s Guide and API Reference, both available at http://docs.cloud.com/CloudStack_Documentation. + &PRODUCT; provides an API that gives programmatic access to all the + management features available in the UI. The API is maintained and + documented. This API enables the creation of command line tools and + new user interfaces to suit particular needs. See the Developer’s + Guide and API Reference, both available at + Apache CloudStack Guides + and + Apache CloudStack API Reference + respectively. - The &PRODUCT; pluggable allocation architecture allows the creation of new types of allocators for the selection of storage and Hosts. See the Allocator Implementation Guide (http://docs.cloudstack.org/CloudStack_Documentation/Allocator_Implementation_Guide). + The &PRODUCT; pluggable allocation architecture allows the creation + of new types of allocators for the selection of storage and Hosts. + See the Allocator Implementation Guide + (http://docs.cloudstack.org/CloudStack_Documentation/Allocator_Implementation_Guide). High Availability - &PRODUCT; has a number of features to increase the availability of the system. The Management Server itself may be deployed in a multi-node installation where the servers are load balanced. MySQL may be configured to use replication to provide for a manual failover in the event of database loss. For the hosts, &PRODUCT; supports NIC bonding and the use of separate networks for storage as well as iSCSI Multipath. + + &PRODUCT; has a number of features to increase the availability of the + system. The Management Server itself may be deployed in a multi-node + installation where the servers are load balanced. MySQL may be configured + to use replication to provide for a manual failover in the event of + database loss. For the hosts, &PRODUCT; supports NIC bonding and the use + of separate networks for storage as well as iSCSI Multipath.
diff --git a/docs/en-US/first_ms_node_install.xml b/docs/en-US/first_ms_node_install.xml index fcb4a864875..3c3e51acca1 100644 --- a/docs/en-US/first_ms_node_install.xml +++ b/docs/en-US/first_ms_node_install.xml @@ -25,34 +25,33 @@
Install the First Management Server - Download the &PRODUCT; Management Server onto the host where it will run from one of the following links. If your operating system is CentOS, use the download file for RHEL. - - Open-source community: http://sourceforge.net/projects/cloudstack/files/CloudStack Acton/ - Commercial customers: https://www.citrix.com/English/ss/downloads/. - Commercial customers will need a MyCitrix account. - - - - Install the &PRODUCT; packages. You should have a file in the form of “CloudStack-VERSION-N-OSVERSION.tar.gzâ€. Untar the file and then run the install.sh script inside it. Replace the file and directory names below with those you are using: - # tar xzf CloudStack-VERSION-N-OSVERSION.tar.gz -# cd CloudStack-VERSION-N-OSVERSION -# ./install.sh - - You should see a few messages as the installer prepares, followed by a list of choices. - - Choose M to install the Management Server software. - > M - - Wait for a message like “Complete! Done,†which indicates that the software was installed successfully. - - (RHEL or CentOS) When the installation is finished, run the following commands to start essential services (the commands might be different depending on your OS): - # service rpcbind start -# service nfs start -# chkconfig nfs on -# chkconfig rpcbind on - - - Continue to Install and Configure the Database. + + + Ensure you have configured your machine according to + + or + + as appropriate for your platform. + + + + + Install the &PRODUCT; management server packages by + issuing one of the following commands as appropriate: + # yum install cloud-client + # apt-get install cloud-client + + + + + (RPM-based distributions) When the installation is + finished, run the following commands to start essential + services: + # service rpcbind start +# service nfs start +# chkconfig nfs on +# chkconfig rpcbind on +
diff --git a/docs/en-US/generic-firewall-provisions.xml b/docs/en-US/generic-firewall-provisions.xml new file mode 100644 index 00000000000..53ae45a09e0 --- /dev/null +++ b/docs/en-US/generic-firewall-provisions.xml @@ -0,0 +1,37 @@ + + +%BOOK_ENTITIES; +]> + +
+ Generic Firewall Provisions + The hardware firewall is required to serve two purposes: + + + Protect the Management Servers. NAT and port forwarding should be configured to direct + traffic from the public Internet to the Management Servers. + + + Route management network traffic between multiple zones. Site-to-site VPN should be + configured between multiple zones. + + + To achieve the above purposes you must set up fixed configurations for the firewall. + Firewall rules and policies need not change as users are provisioned into the cloud. Any brand + of hardware firewall that supports NAT and site-to-site VPN can be used. +
diff --git a/docs/en-US/getting-release.xml b/docs/en-US/getting-release.xml new file mode 100644 index 00000000000..09f0a7b08fe --- /dev/null +++ b/docs/en-US/getting-release.xml @@ -0,0 +1,63 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Getting the release + + You can download the latest &PRODUCT; release from the + + Apache CloudStack project download page. + + + You'll notice several links under the 'Latest release' section. + + + + + + apache-cloudstack-4.0.0-incubating-src.tar.bz2 + - This is the link to the release itself. + + + + + PGP + - This is a detached cryptographic signature that can be used to help + verify the authenticity of the release. + + + + + MD5 + - An MD5 hash of the release to aid in verify the validity of the release download. + + + + + SHA512 + - A SHA512 hash of the release to aid in verify the validity of the release download. + + + +
diff --git a/docs/en-US/global-config.xml b/docs/en-US/global-config.xml index 8bc08035d9b..2f6ad105c0d 100644 --- a/docs/en-US/global-config.xml +++ b/docs/en-US/global-config.xml @@ -18,7 +18,7 @@ specific language governing permissions and limitations under the License. --> -
+ Setting Global Configuration Parameters &PRODUCT; provides parameters that you can set to control many aspects of the cloud. When &PRODUCT; is first installed, and periodically thereafter, you might need to modify these @@ -51,4 +51,4 @@ must click the name of the hypervisor first to display the editing screen. -
+ diff --git a/docs/en-US/globally-configured-limit.xml b/docs/en-US/globally-configured-limit.xml deleted file mode 100644 index ac71112b310..00000000000 --- a/docs/en-US/globally-configured-limit.xml +++ /dev/null @@ -1,100 +0,0 @@ - - -%BOOK_ENTITIES; -]> - - - -
- Globally Configured Limits - In a zone, the guest virtual network has a 24 bit CIDR by default. This limits the guest virtual network to 254 running instances. It can be adjusted as needed, but this must be done before any instances are created in the zone. For example, 10.1.1.0/22 would provide for ~1000 addresses. - The following table lists limits set in the Global Configuration: - - -
- - Parameter Name - Definition - - - - - - max.account.public.ips - Number of public IP addresses that can be owned by an account - - - - max.account.snapshots - Number of snapshots that can exist for an account - - - - - max.account.templates - Number of templates that can exist for an account - - - - max.account.user.vms - Number of virtual machine instances that can exist for an account - - - - max.account.volumes - Number of disk volumes that can exist for an account - - - - max.template.iso.size - Maximum size for a downloaded template or ISO in GB - - - - max.volume.size.gb - Maximum size for a volume in GB - - - network.throttling.rate - Default data transfer rate in megabits per second allowed per user (supported on XenServer) - - - snapshot.max.hourly - Maximum recurring hourly snapshots to be retained for a volume. If the limit is reached, early snapshots from the start of the hour are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring hourly snapshots can not be scheduled - - - - snapshot.max.daily - Maximum recurring daily snapshots to be retained for a volume. If the limit is reached, snapshots from the start of the day are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring daily snapshots can not be scheduled - - - snapshot.max.weekly - Maximum recurring weekly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the week are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring weekly snapshots can not be scheduled - - - - snapshot.max.monthly - Maximum recurring monthly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the month are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring monthly snapshots can not be scheduled. - - - - - To modify global configuration parameters, use the global configuration screen in the &PRODUCT; UI. See Setting Global Configuration Parameters - diff --git a/docs/en-US/globally-configured-limits.xml b/docs/en-US/globally-configured-limits.xml index 2445d1a7600..48a91f1b01e 100644 --- a/docs/en-US/globally-configured-limits.xml +++ b/docs/en-US/globally-configured-limits.xml @@ -5,96 +5,96 @@ ]> -
- Globally Configured Limits - In a zone, the guest virtual network has a 24 bit CIDR by default. This limits the guest virtual network to 254 running instances. It can be adjusted as needed, but this must be done before any instances are created in the zone. For example, 10.1.1.0/22 would provide for ~1000 addresses. - The following table lists limits set in the Global Configuration: - - -
- - Parameter Name - Definition - - - - - - max.account.public.ips - Number of public IP addresses that can be owned by an account - - - - max.account.snapshots - Number of snapshots that can exist for an account - - - - - max.account.templates - Number of templates that can exist for an account - - - - max.account.user.vms - Number of virtual machine instances that can exist for an account - - - - max.account.volumes - Number of disk volumes that can exist for an account - - - - max.template.iso.size - Maximum size for a downloaded template or ISO in GB - - - - max.volume.size.gb - Maximum size for a volume in GB - - - network.throttling.rate - Default data transfer rate in megabits per second allowed per user (supported on XenServer) - - - snapshot.max.hourly - Maximum recurring hourly snapshots to be retained for a volume. If the limit is reached, early snapshots from the start of the hour are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring hourly snapshots can not be scheduled - - - - snapshot.max.daily - Maximum recurring daily snapshots to be retained for a volume. If the limit is reached, snapshots from the start of the day are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring daily snapshots can not be scheduled - - - snapshot.max.weekly - Maximum recurring weekly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the week are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring weekly snapshots can not be scheduled - - - - snapshot.max.monthly - Maximum recurring monthly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the month are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring monthly snapshots can not be scheduled. - - - - - To modify global configuration parameters, use the global configuration screen in the &PRODUCT; UI. See Setting Global Configuration Parameters +
+ Globally Configured Limits + In a zone, the guest virtual network has a 24 bit CIDR by default. This limits the guest virtual network to 254 running instances. It can be adjusted as needed, but this must be done before any instances are created in the zone. For example, 10.1.1.0/22 would provide for ~1000 addresses. + The following table lists limits set in the Global Configuration: + + +
+ + Parameter Name + Definition + + + + + + max.account.public.ips + Number of public IP addresses that can be owned by an account + + + + max.account.snapshots + Number of snapshots that can exist for an account + + + + + max.account.templates + Number of templates that can exist for an account + + + + max.account.user.vms + Number of virtual machine instances that can exist for an account + + + + max.account.volumes + Number of disk volumes that can exist for an account + + + + max.template.iso.size + Maximum size for a downloaded template or ISO in GB + + + + max.volume.size.gb + Maximum size for a volume in GB + + + network.throttling.rate + Default data transfer rate in megabits per second allowed per user (supported on XenServer) + + + snapshot.max.hourly + Maximum recurring hourly snapshots to be retained for a volume. If the limit is reached, early snapshots from the start of the hour are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring hourly snapshots can not be scheduled + + + + snapshot.max.daily + Maximum recurring daily snapshots to be retained for a volume. If the limit is reached, snapshots from the start of the day are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring daily snapshots can not be scheduled + + + snapshot.max.weekly + Maximum recurring weekly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the week are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring weekly snapshots can not be scheduled + + + + snapshot.max.monthly + Maximum recurring monthly snapshots to be retained for a volume. If the limit is reached, snapshots from the beginning of the month are deleted so that newer ones can be saved. This limit does not apply to manual snapshots. If set to 0, recurring monthly snapshots can not be scheduled. + + + + + To modify global configuration parameters, use the global configuration screen in the &PRODUCT; UI. See Setting Global Configuration Parameters diff --git a/docs/en-US/guest-nw-usage-with-traffic-sentinel.xml b/docs/en-US/guest-nw-usage-with-traffic-sentinel.xml new file mode 100644 index 00000000000..eb42d641c4b --- /dev/null +++ b/docs/en-US/guest-nw-usage-with-traffic-sentinel.xml @@ -0,0 +1,73 @@ + + +%BOOK_ENTITIES; +]> + +
+ Guest Network Usage Integration for Traffic Sentinel + To collect usage data for a guest network, &PRODUCT; needs to pull the data from an external + network statistics collector installed on the network. Metering statistics for guest networks + are available through &PRODUCT;’s integration with inMon Traffic Sentinel. + Traffic Sentinel is a network traffic usage data collection package. &PRODUCT; can feed + statistics from Traffic Sentinel into its own usage records, providing a basis for billing users + of cloud infrastructure. Traffic Sentinel uses the traffic monitoring protocol sFlow. Routers + and switches generate sFlow records and provide them for collection by Traffic Sentinel, then + &PRODUCT; queries the Traffic Sentinel database to obtain this information + To construct the query, &PRODUCT; determines what guest IPs were in use during the current + query interval. This includes both newly assigned IPs and IPs that were assigned in a previous + time period and continued to be in use. &PRODUCT; queries Traffic Sentinel for network + statistics that apply to these IPs during the time period they remained allocated in &PRODUCT;. + The returned data is correlated with the customer account that owned each IP and the timestamps + when IPs were assigned and released in order to create billable metering records in &PRODUCT;. + When the Usage Server runs, it collects this data. + To set up the integration between &PRODUCT; and Traffic Sentinel: + + + On your network infrastructure, install Traffic Sentinel and configure it to gather + traffic data. For installation and configuration steps, see inMon documentation at Traffic Sentinel Documentation. + + + In the Traffic Sentinel UI, configure Traffic Sentinel to accept script querying from + guest users. &PRODUCT; will be the guest user performing the remote queries to gather + network usage for one or more IP addresses. + Click File > Users > Access Control > Reports Query, then select Guest from the + drop-down list. + + + On &PRODUCT;, add the Traffic Sentinel host by calling the &PRODUCT; API command + addTrafficMonitor. Pass in the URL of the Traffic Sentinel as protocol + host + port + (optional); for example, http://10.147.28.100:8080. For the addTrafficMonitor command + syntax, see the API Reference at API + Documentation. + For information about how to call the &PRODUCT; API, see the Developer’s Guide at + CloudStack API Developer's Guide. + + + Log in to the &PRODUCT; UI as administrator. + + + Select Configuration from the Global Settings page, and set the following: + direct.network.stats.interval: How often you want &PRODUCT; to query Traffic + Sentinel. + + +
diff --git a/docs/en-US/guest-traffic.xml b/docs/en-US/guest-traffic.xml index ebee6986857..16dfa41cf7b 100644 --- a/docs/en-US/guest-traffic.xml +++ b/docs/en-US/guest-traffic.xml @@ -24,13 +24,6 @@
Guest Traffic A network can carry guest traffic only between VMs within one zone. Virtual machines in different zones cannot communicate with each other using their IP addresses; they must communicate with each other by routing through a public IP address. - See a typical guest traffic setup given below: - - - - - guesttraffic.png: Depicts a guest traffic setup - The Management Server automatically creates a virtual router for each network. A virtual router is a special virtual machine that runs on the hosts. Each virtual router has three network interfaces. Its eth0 interface serves as the gateway for the guest traffic and has the IP address of 10.1.1.1. Its eth1 interface is used by the system to configure the virtual router. Its eth2 interface is assigned a public IP address for public traffic. The virtual router provides DHCP and will automatically assign an IP address for each guest VM within the IP range assigned for the network. The user can manually reconfigure guest VMs to assume different IP addresses. Source NAT is automatically configured in the virtual router to forward outbound traffic for all guest VMs diff --git a/docs/en-US/hardware-config-eg.xml b/docs/en-US/hardware-config-eg.xml new file mode 100644 index 00000000000..3174bfa8576 --- /dev/null +++ b/docs/en-US/hardware-config-eg.xml @@ -0,0 +1,29 @@ + + +%BOOK_ENTITIES; +]> + +
+ Example Hardware Configuration + This section contains an example configuration of specific switch models for zone-level + layer-3 switching. It assumes VLAN management protocols, such as VTP or GVRP, have been + disabled. The example scripts must be changed appropriately if you choose to use VTP or + GVRP. + + +
diff --git a/docs/en-US/hardware-firewall.xml b/docs/en-US/hardware-firewall.xml new file mode 100644 index 00000000000..df0568aa2c2 --- /dev/null +++ b/docs/en-US/hardware-firewall.xml @@ -0,0 +1,29 @@ + + +%BOOK_ENTITIES; +]> + +
+ Hardware Firewall + All deployments should have a firewall protecting the management server; see Generic + Firewall Provisions. Optionally, some deployments may also have a Juniper SRX firewall that will + be the default gateway for the guest networks; see . + + + +
diff --git a/docs/en-US/host-add-xenserver-kvm-ovm.xml b/docs/en-US/host-add-xenserver-kvm-ovm.xml index 710133211cb..4bbeefcbed4 100644 --- a/docs/en-US/host-add-xenserver-kvm-ovm.xml +++ b/docs/en-US/host-add-xenserver-kvm-ovm.xml @@ -21,68 +21,132 @@ specific language governing permissions and limitations under the License. --> -
- Adding a Host (XenServer, KVM, or OVM) - XenServer, KVM, and Oracle VM (OVM) hosts can be added to a cluster at any time. + Adding a Host (XenServer or KVM) + XenServer and KVM hosts can be added to a cluster at any time. +
+ Requirements for XenServer and KVM Hosts + + Make sure the hypervisor host does not have any VMs already running before you add it to + &PRODUCT;. + + Configuration requirements: + + + Each cluster must contain only hosts with the identical hypervisor. + + + For XenServer, do not put more than 8 hosts in a cluster. + + + For KVM, do not put more than 16 hosts in a cluster. + + + For hardware requirements, see the installation section for your hypervisor in the + &PRODUCT; Installation Guide.
- Requirements for XenServer, KVM, and OVM Hosts - Make sure the hypervisor host does not have any VMs already running before you add it to &PRODUCT;. - Configuration requirements: + XenServer Host Additional Requirements + If network bonding is in use, the administrator must cable the new host identically to + other hosts in the cluster. + For all additional hosts to be added to the cluster, run the following command. This + will cause the host to join the master in a XenServer pool. + # xe pool-join master-address=[master IP] master-username=root master-password=[your password] + + When copying and pasting a command, be sure the command has pasted as a single line + before executing. Some document viewers may introduce unwanted line breaks in copied + text. + + With all hosts added to the XenServer pool, run the cloud-setup-bond script. This script + will complete the configuration and setup of the bonds on the new hosts in the + cluster. + + + Copy the script from the Management Server in + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver/cloud-setup-bonding.sh to the + master host and ensure it is executable. + + + Run the script: + # ./cloud-setup-bonding.sh + + +
+
+ KVM Host Additional Requirements + + + If shared mountpoint storage is in use, the administrator should ensure that the new + host has all the same mountpoints (with storage mounted) as the other hosts in the + cluster. + + + Make sure the new host has the same network configuration (guest, private, and + public network) as other hosts in the cluster. + + +
+ +
+
+ Adding a XenServer or KVM Host + + + If you have not already done so, install the hypervisor software on the host. You will + need to know which version of the hypervisor software version is supported by &PRODUCT; + and what additional configuration is required to ensure the host will work with &PRODUCT;. + To find these installation details, see the appropriate section for your hypervisor in the + &PRODUCT; Installation Guide. + + + Log in to the &PRODUCT; UI as administrator. + + + In the left navigation, choose Infrastructure. In Zones, click View More, then click + the zone in which you want to add the host. + + + Click the Compute tab. In the Clusters node, click View All. + + + Click the cluster where you want to add the host. + + + Click View Hosts. + + + Click Add Host. + + + Provide the following information. - Each cluster must contain only hosts with the identical hypervisor. - For XenServer, do not put more than 8 hosts in a cluster. - For KVM, do not put more than 16 hosts in a cluster. + + Host Name. The DNS name or IP address of the host. + + + Username. Usually root. + + + Password. This is the password for the user from your XenServer or KVM + install). + + + Host Tags (Optional). Any labels that you use to categorize hosts for ease of + maintenance. For example, you can set to the cloud's HA tag (set in the ha.tag global + configuration parameter) if you want this host to be used only for VMs with the "high + availability" feature enabled. For more information, see HA-Enabled Virtual Machines + as well as HA for Hosts. + - For hardware requirements, see the installation section for your hypervisor in the &PRODUCT; Installation Guide. -
- XenServer Host Additional Requirements - If network bonding is in use, the administrator must cable the new host identically to other hosts in the cluster. - For all additional hosts to be added to the cluster, run the following command. This will cause the host to join the master in a XenServer pool. - # xe pool-join master-address=[master IP] master-username=root master-password=[your password] - When copying and pasting a command, be sure the command has pasted as a single line before executing. Some document viewers may introduce unwanted line breaks in copied text. - With all hosts added to the XenServer pool, run the cloud-setup-bond script. This script will complete the configuration and setup of the bonds on the new hosts in the cluster. - - Copy the script from the Management Server in /usr/lib64/cloud/agent/scripts/vm/hypervisor/xenserver/cloud-setup-bonding.sh to the master host and ensure it is executable. - Run the script: - # ./cloud-setup-bonding.sh - - -
-
- KVM Host Additional Requirements - - If shared mountpoint storage is in use, the administrator should ensure that the new host has all the same mountpoints (with storage mounted) as the other hosts in the cluster. - Make sure the new host has the same network configuration (guest, private, and public network) as other hosts in the cluster. - -
-
- OVM Host Additional Requirements - Before adding a used host in &PRODUCT;, as part of the cleanup procedure on the host, be sure to remove - /etc/ovs-agent/db/. - -
-
-
- Adding a XenServer, KVM, or OVM Host - - If you have not already done so, install the hypervisor software on the host. You will need to know which version of the hypervisor software version is supported by &PRODUCT; and what additional configuration is required to ensure the host will work with &PRODUCT;. To find these installation details, see - the appropriate section for your hypervisor in the &PRODUCT; Installation Guide. - Log in to the &PRODUCT; UI as administrator. - In the left navigation, choose Infrastructure. In Zones, click View More, then click the zone in which you want to add the host. - Click the Compute tab. In the Clusters node, click View All. - Click the cluster where you want to add the host. - Click View Hosts. - Click Add Host. - Provide the following information. - - Host Name. The DNS name or IP address of the host. - Username. Usually root. - Password. This is the password for the user named above (from your XenServer, KVM, or OVM install). - Host Tags (Optional). Any labels that you use to categorize hosts for ease of maintenance. For example, you can set to the cloud's HA tag (set in the ha.tag global configuration parameter) if you want this host to be used only for VMs with the "high availability" feature enabled. For more information, see HA-Enabled Virtual Machines as well as HA for Hosts. - - There may be a slight delay while the host is provisioned. It should automatically display in the UI. - Repeat for additional hosts. - -
+ There may be a slight delay while the host is provisioned. It should automatically + display in the UI. + + + Repeat for additional hosts. + + +
diff --git a/docs/en-US/hypervisor-host-install-agent.xml b/docs/en-US/hypervisor-host-install-agent.xml index d1b774a7a30..e5bfa37fb6d 100644 --- a/docs/en-US/hypervisor-host-install-agent.xml +++ b/docs/en-US/hypervisor-host-install-agent.xml @@ -27,8 +27,8 @@ To manage KVM instances on the host &PRODUCT; uses a Agent. This Agent communicates with the Management server and controls all the instances on the host.First we start by installing the agent:In RHEL or CentOS: - yum install cloud-agent + $ yum install cloud-agentIn Ubuntu: - apt-get install cloud-agent + $ apt-get install cloud-agentThe host is now ready to be added to a cluster. This is covered in a later section, see . It is recommended that you continue to read the documentation before adding the host! \ No newline at end of file diff --git a/docs/en-US/hypervisor-host-install-finish.xml b/docs/en-US/hypervisor-host-install-finish.xml new file mode 100644 index 00000000000..ff530c79038 --- /dev/null +++ b/docs/en-US/hypervisor-host-install-finish.xml @@ -0,0 +1,28 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Add the host to CloudStack + The host is now ready to be added to a cluster. This is covered in a later section, see . It is recommended that you continue to read the documentation before adding the host! +
diff --git a/docs/en-US/hypervisor-host-install-firewall.xml b/docs/en-US/hypervisor-host-install-firewall.xml index e99c88e4882..ae82fc47afa 100644 --- a/docs/en-US/hypervisor-host-install-firewall.xml +++ b/docs/en-US/hypervisor-host-install-firewall.xml @@ -37,23 +37,23 @@
Open ports in RHEL/CentOS RHEL and CentOS use iptables for firewalling the system, you can open extra ports by executing the following iptable commands: - iptables -I INPUT -p tcp -m tcp --dport 22 -j ACCEPT - iptables -I INPUT -p tcp -m tcp --dport 1798 -j ACCEPT - iptables -I INPUT -p tcp -m tcp --dport 16509 -j ACCEPT - iptables -I INPUT -p tcp -m tcp --dport 5900:6100 -j ACCEPT - iptables -I INPUT -p tcp -m tcp --dport 49152:492160 -j ACCEPT + $ iptables -I INPUT -p tcp -m tcp --dport 22 -j ACCEPT + $ iptables -I INPUT -p tcp -m tcp --dport 1798 -j ACCEPT + $ iptables -I INPUT -p tcp -m tcp --dport 16509 -j ACCEPT + $ iptables -I INPUT -p tcp -m tcp --dport 5900:6100 -j ACCEPT + $ iptables -I INPUT -p tcp -m tcp --dport 49152:49216 -j ACCEPT These iptable settings are not persistent accross reboots, we have to save them first. - iptables-save > /etc/sysconfig/iptables + $ iptables-save > /etc/sysconfig/iptables
Open ports in Ubuntu The default firewall under Ubuntu is UFW (Uncomplicated FireWall), which is a Python wrapper around iptables. To open the required ports, execute the following commands: - ufw allow proto tcp from any to any port 22 - ufw allow proto tcp from any to any port 1798 - ufw allow proto tcp from any to any port 16509 - ufw allow proto tcp from any to any port 5900:6100 - ufw allow proto tcp from any to any port 49152:492160 + $ ufw allow proto tcp from any to any port 22 + $ ufw allow proto tcp from any to any port 1798 + $ ufw allow proto tcp from any to any port 16509 + $ ufw allow proto tcp from any to any port 5900:6100 + $ ufw allow proto tcp from any to any port 49152:49216 By default UFW is not enabled on Ubuntu. Executing these commands with the firewall disabled does not enable the firewall.
- \ No newline at end of file + diff --git a/docs/en-US/hypervisor-host-install-libvirt.xml b/docs/en-US/hypervisor-host-install-libvirt.xml index 15cfde2efa7..34e66783600 100644 --- a/docs/en-US/hypervisor-host-install-libvirt.xml +++ b/docs/en-US/hypervisor-host-install-libvirt.xml @@ -24,32 +24,23 @@
Install and Configure libvirt - &PRODUCT; uses libvirt for managing virtual machines. Therefor it is vital that libvirt is configured correctly. + &PRODUCT; uses libvirt for managing virtual machines. Therefore it is vital that libvirt is configured correctly. Libvirt is a dependency of cloud-agent and should already be installed. - Install libvirt - On RHEL or CentOS: - yum install libvirt - On Ubuntu: - apt-get install libvirt-bin - - - In order to have live migration working libvirt has to listen for unsecured TCP connections. - vi /etc/libvirt/libvirtd.conf + In order to have live migration working libvirt has to listen for unsecured TCP connections. We also need to turn off libvirts attempt to use Multicast DNS advertising. Both of these settings are in /etc/libvirt/libvirtd.conf Set the following paramaters: listen_tls = 0 listen_tcp = 1 tcp_port = 16059 auth_tcp = "none" + mdns_adv = 0 Turning on "listen_tcp" in libvirtd.conf is not enough, we have to change the parameters as well: - On RHEL or CentOS: - vi /etc/sysconfig/libvirtd + On RHEL or CentOS modify /etc/sysconfig/libvirtd: Uncomment the following line: #LIBVIRTD_ARGS="--listen" - On Ubuntu: - vi /etc/init/libvirt-bin.conf + On Ubuntu: modify /etc/init/libvirt-bin.conf Change the following line (at the end of the file): exec /usr/sbin/libvirtd -d to (just add -l) @@ -58,9 +49,9 @@ Restart libvirt In RHEL or CentOS: - service libvirtd restart + $ service libvirtd restart In Ubuntu: - service libvirt-bin restart + $ service libvirt-bin restart -
\ No newline at end of file + diff --git a/docs/en-US/hypervisor-host-install-overview.xml b/docs/en-US/hypervisor-host-install-overview.xml index 187abea8e4e..716b43ddf91 100644 --- a/docs/en-US/hypervisor-host-install-overview.xml +++ b/docs/en-US/hypervisor-host-install-overview.xml @@ -23,11 +23,11 @@ -->
- Hypervisor Host Installation Overview - This section describes installing a Hypervisor host. This is targeted towards hosts running Linux Kernel Virtual Machine (KVM) + KVM Installation Overview + If you want to use the Linux Kernel Virtual Machine (KVM) hypervisor to run guest virtual machines, install KVM on the host(s) in your cloud. The material in this section doesn't duplicate KVM installation docs. It provides the &PRODUCT;-specific steps that are needed to prepare a KVM host to work with &PRODUCT;. Before continuing, make sure that you have applied the latest updates to your host. It is NOT recommended to run services on this host not controlled by &PRODUCT;. - The procedure for installing the Hypervisor Host is: + The procedure for installing a KVM Hypervisor Host is: Prepare the Operating System Install and configure libvirt diff --git a/docs/en-US/hypervisor-host-install-prepare-os.xml b/docs/en-US/hypervisor-host-install-prepare-os.xml index e2e32e709ae..44852f21c2d 100644 --- a/docs/en-US/hypervisor-host-install-prepare-os.xml +++ b/docs/en-US/hypervisor-host-install-prepare-os.xml @@ -29,12 +29,12 @@ Log in to your OS as root. Check for a fully qualified hostname. - hostname --fqdn + $ hostname --fqdn This should return a fully qualified hostname such as "kvm1.lab.example.org". If it does not, edit /etc/hosts so that it does. Make sure that the machine can reach the Internet. - ping www.cloudstack.org + $ ping www.cloudstack.org Turn on NTP for time synchronization. @@ -42,9 +42,9 @@ Install NTP On RHEL or CentOS: - yum install ntp + $ yum install ntp On Ubuntu: - apt-get install openntpd + $ apt-get install openntpd diff --git a/docs/en-US/hypervisor-host-install-security-policies.xml b/docs/en-US/hypervisor-host-install-security-policies.xml index 5fd6925a8c0..03da04b6eb3 100644 --- a/docs/en-US/hypervisor-host-install-security-policies.xml +++ b/docs/en-US/hypervisor-host-install-security-policies.xml @@ -32,10 +32,10 @@ Check to see whether SELinux is installed on your machine. If not, you can skip this section. In RHEL or CentOS, SELinux is installed and enabled by default. You can verify this with: - rpm -qa | grep selinux + $ rpm -qa | grep selinux - Set the SELINUX variable in /etc/selinux/config to "permissive". This ensures that the permissive setting will be maintained after a system reboot. + Set the SELINUX variable in /etc/selinux/config to "permissive". This ensures that the permissive setting will be maintained after a system reboot. In RHEL or CentOS: vi /etc/selinux/config Change the following line @@ -45,7 +45,7 @@ Then set SELinux to permissive starting immediately, without requiring a system reboot. - setenforce permissive + $ setenforce permissive @@ -55,14 +55,14 @@ Check to see whether AppArmor is installed on your machine. If not, you can skip this section. In Ubuntu AppArmor is installed and enabled by default. You can verify this with: - dpkg --list 'apparmor' + $ dpkg --list 'apparmor' Disable the AppArmor profiles for libvirt - ln -s /etc/apparmor.d/usr.sbin.libvirtd /etc/apparmor.d/disable/ - ln -s /etc/apparmor.d/usr.lib.libvirt.virt-aa-helper /etc/apparmor.d/disable/ - apparmor_parser -R /etc/apparmor.d/usr.sbin.libvirtd - apparmor_parser -R /etc/apparmor.d/usr.lib.libvirt.virt-aa-helper + $ ln -s /etc/apparmor.d/usr.sbin.libvirtd /etc/apparmor.d/disable/ + $ ln -s /etc/apparmor.d/usr.lib.libvirt.virt-aa-helper /etc/apparmor.d/disable/ + $ apparmor_parser -R /etc/apparmor.d/usr.sbin.libvirtd + $ apparmor_parser -R /etc/apparmor.d/usr.lib.libvirt.virt-aa-helper diff --git a/docs/en-US/hypervisor-installation.xml b/docs/en-US/hypervisor-installation.xml index 8bfc0c09c9b..b0fc9f46ddb 100644 --- a/docs/en-US/hypervisor-installation.xml +++ b/docs/en-US/hypervisor-installation.xml @@ -26,4 +26,6 @@ Hypervisor Installation - \ No newline at end of file + + + diff --git a/docs/en-US/hypervisor-kvm-install-flow.xml b/docs/en-US/hypervisor-kvm-install-flow.xml index e2544c19251..76e03ef7919 100644 --- a/docs/en-US/hypervisor-kvm-install-flow.xml +++ b/docs/en-US/hypervisor-kvm-install-flow.xml @@ -24,11 +24,13 @@
KVM Hypervisor Host Installation + + - +
diff --git a/docs/en-US/hypervisor-kvm-requirements.xml b/docs/en-US/hypervisor-kvm-requirements.xml new file mode 100644 index 00000000000..c42db86a2b8 --- /dev/null +++ b/docs/en-US/hypervisor-kvm-requirements.xml @@ -0,0 +1,48 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ System Requirements for KVM Hypervisor Hosts + KVM is included with a variety of Linux-based operating systems. Although you are not required to run these distributions, the following are recommended: + + CentOS / RHEL: 6.3 + Ubuntu: 12.04(.1) + + The main requirement for KVM hypervisors is the libvirt and Qemu version. No matter what + Linux distribution you are using, make sure the following requirements are met: + + libvirt: 0.9.4 or higher + Qemu/KVM: 1.0 or higher + + In addition, the following hardware requirements apply: + + Within a single cluster, the hosts must be of the same distribution version. + All hosts within a cluster must be homogenous. The CPUs must be of the same type, count, and feature flags. + Must support HVM (Intel-VT or AMD-V enabled) + 64-bit x86 CPU (more cores results in better performance) + 4 GB of memory + At least 1 NIC + When you deploy &PRODUCT;, the hypervisor host must not have any VMs already running + +
diff --git a/docs/en-US/hypervisor-support-for-primarystorage.xml b/docs/en-US/hypervisor-support-for-primarystorage.xml index 23c8eb5cd88..7c2596eac29 100644 --- a/docs/en-US/hypervisor-support-for-primarystorage.xml +++ b/docs/en-US/hypervisor-support-for-primarystorage.xml @@ -37,7 +37,6 @@ VMware vSphere Citrix XenServer KVM - Oracle VM
@@ -47,28 +46,24 @@ VMDKVHDQCOW2 - RAW iSCSI support VMFS Clustered LVM Yes, via Shared Mountpoint - Yes, via OCFS2M Fiber Channel support VMFS Yes, via Existing SR Yes, via Shared Mountpoint - No NFS support Y Y Y - Y @@ -76,7 +71,6 @@ Y Y Y - Y @@ -84,7 +78,6 @@ NFS and iSCSI NFS NFS - No @@ -92,8 +85,8 @@ XenServer uses a clustered LVM system to store VM images on iSCSI and Fiber Channel volumes and does not support over-provisioning in the hypervisor. The storage server itself, however, can support thin-provisioning. As a result the &PRODUCT; can still support storage over-provisioning by running on thin-provisioned storage volumes.KVM supports "Shared Mountpoint" storage. A shared mountpoint is a file system path local to each server in a given cluster. The path must be the same across all Hosts in the cluster, for example /mnt/primary1. This shared mountpoint is assumed to be a clustered filesystem such as OCFS2. In this case the &PRODUCT; does not attempt to mount or unmount the storage as is done with NFS. The &PRODUCT; requires that the administrator insure that the storage is available - Oracle VM supports both iSCSI and NFS storage. When iSCSI is used with OVM, the &PRODUCT; administrator is responsible for setting up iSCSI on the host, including re-mounting the storage after the host recovers from a failure such as a network outage. With other hypervisors, &PRODUCT; takes care of mounting the iSCSI target on the host whenever it discovers a connection with an iSCSI server and unmounting the target when it discovers the connection is down. + With NFS storage, &PRODUCT; manages the overprovisioning. In this case the global configuration parameter storage.overprovisioning.factor controls the degree of overprovisioning. This is independent of hypervisor type. - Local storage is an option for primary storage for vSphere, XenServer, Oracle VM, and KVM. When the local disk option is enabled, a local disk storage pool is automatically created on each host. To use local storage for the System Virtual Machines (such as the Virtual Router), set system.vm.use.local.storage to true in global configuration. + Local storage is an option for primary storage for vSphere, XenServer, and KVM. When the local disk option is enabled, a local disk storage pool is automatically created on each host. To use local storage for the System Virtual Machines (such as the Virtual Router), set system.vm.use.local.storage to true in global configuration.&PRODUCT; supports multiple primary storage pools in a Cluster. For example, you could provision 2 NFS servers in primary storage. Or you could provision 1 iSCSI LUN initially and then add a second iSCSI LUN when the first approaches capacity. 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/images/parallel-mode.png b/docs/en-US/images/parallel-mode.png new file mode 100644 index 00000000000..3b67a17af9d Binary files /dev/null and b/docs/en-US/images/parallel-mode.png differ diff --git a/docs/en-US/images/vmware-increase-ports.png b/docs/en-US/images/vmware-increase-ports.png new file mode 100644 index 00000000000..fe968153262 Binary files /dev/null and b/docs/en-US/images/vmware-increase-ports.png differ diff --git a/docs/en-US/images/vmware-iscsi-datastore.png b/docs/en-US/images/vmware-iscsi-datastore.png new file mode 100644 index 00000000000..9f6b33f01ed Binary files /dev/null and b/docs/en-US/images/vmware-iscsi-datastore.png differ diff --git a/docs/en-US/images/vmware-iscsi-general.png b/docs/en-US/images/vmware-iscsi-general.png new file mode 100644 index 00000000000..863602b9eb7 Binary files /dev/null and b/docs/en-US/images/vmware-iscsi-general.png differ diff --git a/docs/en-US/images/vmware-iscsi-initiator-properties.png b/docs/en-US/images/vmware-iscsi-initiator-properties.png new file mode 100644 index 00000000000..1fab03143b1 Binary files /dev/null and b/docs/en-US/images/vmware-iscsi-initiator-properties.png differ diff --git a/docs/en-US/images/vmware-iscsi-initiator.png b/docs/en-US/images/vmware-iscsi-initiator.png new file mode 100644 index 00000000000..a9a8301d74d Binary files /dev/null and b/docs/en-US/images/vmware-iscsi-initiator.png differ diff --git a/docs/en-US/images/vmware-iscsi-target-add.png b/docs/en-US/images/vmware-iscsi-target-add.png new file mode 100644 index 00000000000..f016da7956d Binary files /dev/null and b/docs/en-US/images/vmware-iscsi-target-add.png differ diff --git a/docs/en-US/images/vmware-mgt-network-properties.png b/docs/en-US/images/vmware-mgt-network-properties.png new file mode 100644 index 00000000000..9141af9c42f Binary files /dev/null and b/docs/en-US/images/vmware-mgt-network-properties.png differ diff --git a/docs/en-US/images/vmware-nexus-add-cluster.png b/docs/en-US/images/vmware-nexus-add-cluster.png new file mode 100644 index 00000000000..7c1dd73f775 Binary files /dev/null and b/docs/en-US/images/vmware-nexus-add-cluster.png differ diff --git a/docs/en-US/images/vmware-nexus-port-profile.png b/docs/en-US/images/vmware-nexus-port-profile.png new file mode 100644 index 00000000000..19b264f7a0a Binary files /dev/null and b/docs/en-US/images/vmware-nexus-port-profile.png differ diff --git a/docs/en-US/images/vmware-physical-network.png b/docs/en-US/images/vmware-physical-network.png new file mode 100644 index 00000000000..a7495c77b14 Binary files /dev/null and b/docs/en-US/images/vmware-physical-network.png differ diff --git a/docs/en-US/images/vmware-vswitch-properties.png b/docs/en-US/images/vmware-vswitch-properties.png new file mode 100644 index 00000000000..bc247d276d6 Binary files /dev/null and b/docs/en-US/images/vmware-vswitch-properties.png differ diff --git a/docs/en-US/install-usage-server.xml b/docs/en-US/install-usage-server.xml new file mode 100644 index 00000000000..9dde5523f5e --- /dev/null +++ b/docs/en-US/install-usage-server.xml @@ -0,0 +1,61 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Installing the Usage Server (Optional) + You can optionally install the Usage Server once the Management Server is configured properly. The Usage Server takes data from the events in the system and enables usage-based billing for accounts. + When multiple Management Servers are present, the Usage Server may be installed on any number of them. The Usage Servers will coordinate usage processing. A site that is concerned about availability should install Usage Servers on at least two Management Servers. +
+ Requirements for Installing the Usage Server + + The Management Server must be running when the Usage Server is installed. + The Usage Server must be installed on the same server as a Management Server. + +
+
+ Steps to Install the Usage Server + + + Run ./install.sh. + +# ./install.sh + + You should see a few messages as the installer prepares, followed by a list of choices. + + + Choose "S" to install the Usage Server. + + > S + + + + Once installed, start the Usage Server with the following command. + +# service cloud-usage start + + + + The Administration Guide discusses further configuration of the Usage Server. +
+
diff --git a/docs/en-US/installation.xml b/docs/en-US/installation.xml index 35f1c681dc8..5fc550edad6 100644 --- a/docs/en-US/installation.xml +++ b/docs/en-US/installation.xml @@ -29,5 +29,4 @@ - diff --git a/docs/en-US/kvm-topology-req.xml b/docs/en-US/kvm-topology-req.xml new file mode 100644 index 00000000000..0dff491b364 --- /dev/null +++ b/docs/en-US/kvm-topology-req.xml @@ -0,0 +1,24 @@ + + +%BOOK_ENTITIES; +]> + +
+ KVM Topology Requirements + The Management Servers communicate with KVM hosts on port 22 (ssh). +
diff --git a/docs/en-US/layer2-switch.xml b/docs/en-US/layer2-switch.xml new file mode 100644 index 00000000000..acef5a7c207 --- /dev/null +++ b/docs/en-US/layer2-switch.xml @@ -0,0 +1,41 @@ + + +%BOOK_ENTITIES; +]> + +
+ Layer-2 Switch + The layer-2 switch is the access switching layer inside the pod. + + + It should trunk all VLANs into every computing host. + + + It should switch traffic for the management network containing computing and storage + hosts. The layer-3 switch will serve as the gateway for the management network. + + + + Example Configurations + This section contains example configurations for specific switch models for pod-level + layer-2 switching. It assumes VLAN management protocols such as VTP or GVRP have been + disabled. The scripts must be changed appropriately if you choose to use VTP or GVRP. + + + +
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/log-in-root-admin.xml b/docs/en-US/log-in-root-admin.xml index b8f8204193e..0243bd645fe 100644 --- a/docs/en-US/log-in-root-admin.xml +++ b/docs/en-US/log-in-root-admin.xml @@ -27,7 +27,7 @@ Open your favorite Web browser and go to this URL. Substitute the IP address of your own Management Server: http://<management-server-ip-address>:8080/client - On a fresh Management Server installation, a guided tour splash screen appears. On later visits, you’ll see a login screen where you can enter a user ID and password and proceed to your Dashboard. + After logging into a fresh Management Server installation, a guided tour splash screen appears. On later visits, you’ll be taken directly into the Dashboard. If you see the first-time splash screen, choose one of the following. diff --git a/docs/en-US/manage-cloud.xml b/docs/en-US/manage-cloud.xml index 06d4e3ff85e..d35667382e5 100644 --- a/docs/en-US/manage-cloud.xml +++ b/docs/en-US/manage-cloud.xml @@ -21,11 +21,12 @@ specific language governing permissions and limitations under the License. --> + - Managing the Cloud - - - + Managing the Cloud + + + diff --git a/docs/en-US/management-server-install-client.xml b/docs/en-US/management-server-install-client.xml index 93273ce3f34..7e81ec735fc 100644 --- a/docs/en-US/management-server-install-client.xml +++ b/docs/en-US/management-server-install-client.xml @@ -21,20 +21,33 @@ specific language governing permissions and limitations under the License. --> -
- Install the Management Server on the First Host - The first step in installation, whether you are installing the Management Server on one host or many, is to install the software on a single node. - - If you are planning to install the Management Server on multiple nodes for high availability, do not proceed to the additional nodes yet. That step will come later. - The &PRODUCT; Management server can be installed using either RPM or DEB packages. These packages will depend on everything you need to run the Management server. -
- Install on CentOS/RHEL - We start by installing the required packages: - yum install cloud-client -
-
- Install on Ubuntu - apt-get install cloud-client -
-
+ Install the Management Server on the First Host + The first step in installation, whether you are installing the Management Server on one host + or many, is to install the software on a single node. + + If you are planning to install the Management Server on multiple nodes for high + availability, do not proceed to the additional nodes yet. That step will come later. + + The &PRODUCT; Management server can be installed using either RPM or DEB packages. These + packages will depend on everything you need to run the Management server. +
+ Downloading vhd-util + This procedure is required only for installations where XenServer is installed on the hypervisor hosts. + Before setting up the Management Server, download vhd-util from vhd-util. + If the Management Server is RHEL or CentOS, copy vhd-util to + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver. + If the Management Server is Ubuntu, copy vhd-util to + /usr/lib/cloud/common/scripts/vm/hypervisor/xenserver/vhd-util. +
+
+ Install on CentOS/RHEL + We start by installing the required packages: + yum install cloud-client +
+
+ Install on Ubuntu + apt-get install cloud-client +
+ \ No newline at end of file diff --git a/docs/en-US/management-server-install-db-external.xml b/docs/en-US/management-server-install-db-external.xml index e77380fc54c..3bba45f3ee1 100644 --- a/docs/en-US/management-server-install-db-external.xml +++ b/docs/en-US/management-server-install-db-external.xml @@ -21,96 +21,120 @@ specific language governing permissions and limitations under the License. --> -
- Install the Database on a Separate Node - This section describes how to install MySQL on a standalone machine, separate from the Management Server. - This technique is intended for a deployment that includes several Management Server nodes. - If you have a single-node Management Server deployment, you will typically use the same node for MySQL. - See . - - - The management server doesn't require a specific distribution for the MySQL node. - You can use a distribution or Operating System of your choice. - Using the same distribution as the management server is recommended, but not required. - See . - - - - - Install MySQL from the package repository from your distribution: - On RHEL or CentOS: - yum install mysql-server - On Ubuntu: - apt-get install mysql-server - - Edit the MySQL configuration (/etc/my.cnf or /etc/mysql/my.cnf, depending on your OS) - and insert the following lines in the [mysqld] section. You can put these lines below the datadir - line. The max_connections parameter should be set to 350 multiplied by the number of Management - Servers you are deploying. This example assumes two Management Servers. - - On Ubuntu you can also create a file /etc/mysql/conf.d/cloudstack.cnf and add these directives there. Don't forget to add [mysqld] on the first line of the file. - - -innodb_rollback_on_timeout=1 + Install the Database on a Separate Node + This section describes how to install MySQL on a standalone machine, separate from the + Management Server. This technique is intended for a deployment that includes several Management + Server nodes. If you have a single-node Management Server deployment, you will typically use the + same node for MySQL. See . + + The management server doesn't require a specific distribution for the MySQL node. You can + use a distribution or Operating System of your choice. Using the same distribution as the + management server is recommended, but not required. See . + + + + Install MySQL from the package repository from your distribution: + On RHEL or CentOS: + yum install mysql-server + On Ubuntu: + apt-get install mysql-server + + + Edit the MySQL configuration (/etc/my.cnf or /etc/mysql/my.cnf, depending on your OS) + and insert the following lines in the [mysqld] section. You can put these lines below the + datadir line. The max_connections parameter should be set to 350 multiplied by the number of + Management Servers you are deploying. This example assumes two Management Servers. + + On Ubuntu, you can also create /etc/mysql/conf.d/cloudstack.cnf file and add these + directives there. Don't forget to add [mysqld] on the first line of the file. + + innodb_rollback_on_timeout=1 innodb_lock_wait_timeout=600 max_connections=700 log-bin=mysql-bin binlog-format = 'ROW' -bind-address = 0.0.0.0 - +bind-address = 0.0.0.0 + + + Start or restart MySQL to put the new configuration into effect. + On RHEL/CentOS, MySQL doesn't automatically start after installation. Start it + manually. + service mysqld start + On Ubuntu, restart MySQL. + service mysqld restart + + + (CentOS and RHEL only; not required on Ubuntu) + + On RHEL and CentOS, MySQL does not set a root password by default. It is very strongly + recommended that you set a root password as a security precaution. + + Run the following command to secure your installation. You can answer "Y" to all + questions except "Disallow root login remotely?". Remote root login is required to set up + the databases. + mysql_secure_installation + + + If a firewall is present on the system, open TCP port 3306 so external MySQL connections + can be established. + On Ubuntu, UFW is the default firewall. Open the port with this command: + ufw allow mysql + On RHEL/CentOS: + + + Edit the /etc/sysconfig/iptables file and add the following line at the beginning of + the INPUT chain. + -A INPUT -p tcp --dport 3306 -j ACCEPT - On RHEL/CentOS MySQL doesn't start after installation, start it manually. - service mysqld start + Now reload the iptables rules. + service iptables restart + + + + + Return to the root shell on your first Management Server. + + + Set up the database. The following command creates the cloud user on the + database. + + + In dbpassword, specify the password to be assigned to the cloud user. You can choose + to provide no password. - - On RHEL and CentOS, MySQL does not set a root password by default. It is very strongly recommended that you set a root password as a security precaution. Run the following commands, and substitute your own desired root password. This step is not required on Ubuntu as it asks for a root password during installation. - - Run this command to secure your installation. You can answer "Y" to all questions except to "Disallow root login remotely?". This is required to set up the databases. - mysql_secure_installation - - If a firewall is present on the system, open TCP port 3306 so external MySQL connections can be established. - - - On RHEL/CentOS: - - - Edit the /etc/sysconfig/iptables file and add the following line at the beginning of the INPUT chain. - -A INPUT -p tcp --dport 3306 -j ACCEPT - - - Now reload the iptables rules. - service iptables restart - - - - - On Ubuntu: - UFW is the default firewall on Ubuntu, open the port with this command: - ufw allow mysql - - + In deploy-as, specify the username and password of the user deploying the database. + In the following command, it is assumed the root user is deploying the database and + creating the cloud user. - Set up the database. The following command creates the cloud user on the database. - - This command should be run on the first Management server node! - - - In dbpassword, specify the password to be assigned to the cloud user. You can choose to provide no password. - In deploy-as, specify the username and password of the user deploying the database. In the following command, it is assumed the root user is deploying the database and creating the cloud user. - (Optional) For encryption_type, use file or web to indicate the technique used to pass in the database encryption password. Default: file. See About Password and Key Encryption. - (Optional) For management_server_key, substitute the default key that is used to encrypt confidential parameters in the &PRODUCT; properties file. Default: password. It is highly recommended that you replace this with a more secure value. See About Password and Key Encryption. - (Optional) For database_key, substitute the default key that is used to encrypt confidential parameters in the &PRODUCT; database. Default: password. It is highly recommended that you replace this with a more secure value. See About Password and Key Encryption. - - cloud-setup-databases cloud:<dbpassword>@<ip address mysql server> \ - --deploy-as=root:<password> \ - -e <encryption_type> \ - -m <management_server_key> \ - -k <database_key> - When this script is finished, you should see a message like “Successfully initialized the database.†+ (Optional) For encryption_type, use file or web to indicate the technique used to + pass in the database encryption password. Default: file. See . - + + (Optional) For management_server_key, substitute the default key that is used to + encrypt confidential parameters in the &PRODUCT; properties file. Default: password. It + is highly recommended that you replace this with a more secure value. See About Password + and Key Encryption. + + + (Optional) For database_key, substitute the default key that is used to encrypt + confidential parameters in the &PRODUCT; database. Default: password. It is highly + recommended that you replace this with a more secure value. See . + + + cloud-setup-databases cloud:<dbpassword>@<ip address mysql server> \ +--deploy-as=root:<password> \ +-e <encryption_type> \ +-m <management_server_key> \ +-k <database_key> + When this script is finished, you should see a message like “Successfully initialized + the database.†+ +
diff --git a/docs/en-US/management-server-install-db-local.xml b/docs/en-US/management-server-install-db-local.xml index ae8cfd1edca..3e09c554df0 100644 --- a/docs/en-US/management-server-install-db-local.xml +++ b/docs/en-US/management-server-install-db-local.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -21,56 +21,105 @@ specific language governing permissions and limitations under the License. --> -
- Install the Database on the Management Server Node - This section describes how to install MySQL on the same machine with the Management Server. This technique is intended for a simple deployment that has a single Management Server node. If you have a multi-node Management Server deployment, you will typically use a separate node for MySQL. See . - - - Install MySQL from the package repository from your distribution: - On RHEL or CentOS: - yum install mysql-server - On Ubuntu: - apt-get install mysql-server - - - Edit the MySQL configuration (/etc/my.cnf or /etc/mysql/my.cnf, depending on your OS) and insert the following lines in the [mysqld] section. You can put these lines below the datadir line. The max_connections parameter should be set to 350 multiplied by the number of Management Servers you are deploying. This example assumes one Management Server. - - On Ubuntu you can also create a file /etc/mysql/conf.d/cloudstack.cnf and add these directives there. Don't forget to add [mysqld] on the first line of the file. - - -innodb_rollback_on_timeout=1 + Install the Database on the Management Server Node + This section describes how to install MySQL on the same machine with the Management Server. + This technique is intended for a simple deployment that has a single Management Server node. If + you have a multi-node Management Server deployment, you will typically use a separate node for + MySQL. See . + + + Install MySQL from the package repository from your distribution: + On RHEL or CentOS: + yum install mysql-server + On Ubuntu: + apt-get install mysql-server + + + Edit the MySQL configuration (/etc/my.cnf or /etc/mysql/my.cnf, depending on your OS) + and insert the following lines in the [mysqld] section. You can put these lines below the + datadir line. The max_connections parameter should be set to 350 multiplied by the number of + Management Servers you are deploying. This example assumes one Management Server. + + On Ubuntu, you can also create a file /etc/mysql/conf.d/cloudstack.cnf and add these + directives there. Don't forget to add [mysqld] on the first line of the file. + + innodb_rollback_on_timeout=1 innodb_lock_wait_timeout=600 max_connections=350 log-bin=mysql-bin -binlog-format = 'ROW' - +binlog-format = 'ROW' + + + Start or restart MySQL to put the new configuration into effect. + On RHEL/CentOS, MySQL doesn't automatically start after installation. Start it + manually. + service mysqld start + On Ubuntu, restart MySQL. + service mysqld restart + + + (CentOS and RHEL only; not required on Ubuntu) + + On RHEL and CentOS, MySQL does not set a root password by default. It is very strongly + recommended that you set a root password as a security precaution. + + Run the following command to secure your installation. You can answer "Y" to all + questions. + mysql_secure_installation + + + Set up the database. The following command creates the "cloud" user on the + database. + + + In dbpassword, specify the password to be assigned to the "cloud" user. You can + choose to provide no password although that is not recommended. - On RHEL/CentOS MySQL doesn't start after installation, start it manually. - service mysqld start + In deploy-as, specify the username and password of the user deploying the database. + In the following command, it is assumed the root user is deploying the database and + creating the "cloud" user. - - On RHEL and CentOS, MySQL does not set a root password by default. It is very strongly recommended that you set a root password as a security precaution. Run the following commands, and substitute your own desired root password. This step is not required on Ubuntu as it asks for a root password during installation. - - Run this command to secure your installation. Since we are running MySQL locally you can answer "Y" to all questions. - mysql_secure_installation + (Optional) For encryption_type, use file or web to indicate the technique used to + pass in the database encryption password. Default: file. See . - Set up the database. The following command creates the "cloud" user on the database. - - In dbpassword, specify the password to be assigned to the "cloud" user. You can choose to provide no password although that is not recommended. - In deploy-as, specify the username and password of the user deploying the database. In the following command, it is assumed the root user is deploying the database and creating the "cloud" user. - (Optional) For encryption_type, use file or web to indicate the technique used to pass in the database encryption password. Default: file. See About Password and Key Encryption. - (Optional) For management_server_key, substitute the default key that is used to encrypt confidential parameters in the &PRODUCT; properties file. Default: password. It is highly recommended that you replace this with a more secure value. See About Password and Key Encryption. - (Optional) For database_key, substitute the default key that is used to encrypt confidential parameters in the &PRODUCT; database. Default: password. It is highly recommended that you replace this with a more secure value. See About Password and Key Encryption. - - cloud-setup-databases cloud:<dbpassword>@localhost \ - --deploy-as=root:<password> \ - -e <encryption_type> \ - -m <management_server_key> \ - -k <database_key> - When this script is finished, you should see a message like “Successfully initialized the database.†+ + (Optional) For management_server_key, substitute the default key that is used to + encrypt confidential parameters in the &PRODUCT; properties file. Default: password. It + is highly recommended that you replace this with a more secure value. See . - + + (Optional) For database_key, substitute the default key that is used to encrypt + confidential parameters in the &PRODUCT; database. Default: password. It is highly + recommended that you replace this with a more secure value. See . + + + cloud-setup-databases cloud:<dbpassword>@localhost \ +--deploy-as=root:<password> \ +-e <encryption_type> \ +-m <management_server_key> \ +-k <database_key> + When this script is finished, you should see a message like “Successfully initialized + the database.†+ + + If you are running the KVM hypervisor on the same machine with the Management Server, + edit /etc/sudoers and add the following line: + Defaults:cloud !requiretty + + This type of single-machine setup is recommended only for a trial installation. + + + + Now that the database is set up, you can finish configuring the OS for the Management + Server. This command will set up iptables, sudoers, and start the Management Server. + # cloud-setup-management + You should see the message “&PRODUCT; Management Server setup is done.†+ +
diff --git a/docs/en-US/management-server-install-db.xml b/docs/en-US/management-server-install-db.xml index 24e638ad005..9d41af2562b 100644 --- a/docs/en-US/management-server-install-db.xml +++ b/docs/en-US/management-server-install-db.xml @@ -24,11 +24,11 @@
Install the database server - The &PRODUCT; management server uses a MySQL database server to store it's data. - When you are installing the management server on a single node you can install the MySQL server locally. - When using a multi-node installation the MySQL database has to run on an external node. + The &PRODUCT; management server uses a MySQL database server to store its data. + When you are installing the management server on a single node, you can install the MySQL server locally. + For an installation that has multiple management server nodes, we assume the MySQL database also runs on a separate node. - &PRODUCT; has been tested with MySQL 5.1 and 5.5, both should work fine. These versions are included in RHEL/CentOS and Ubuntu. + &PRODUCT; has been tested with MySQL 5.1 and 5.5. These versions are included in RHEL/CentOS and Ubuntu. -
\ No newline at end of file + diff --git a/docs/en-US/management-server-install-flow.xml b/docs/en-US/management-server-install-flow.xml index 33bcac9c85b..cf14857364f 100644 --- a/docs/en-US/management-server-install-flow.xml +++ b/docs/en-US/management-server-install-flow.xml @@ -28,6 +28,7 @@ + diff --git a/docs/en-US/management-server-install-multi-node.xml b/docs/en-US/management-server-install-multi-node.xml index db4bca5f83e..e61f6230ff0 100644 --- a/docs/en-US/management-server-install-multi-node.xml +++ b/docs/en-US/management-server-install-multi-node.xml @@ -21,54 +21,52 @@ specific language governing permissions and limitations under the License. --> -
- Prepare and Start Additional Management Servers - For your second and subsequent Management Servers, you will install the Management Server software, connect it to the database, and set up the OS for the Management Server. - - - Perform the steps in . - - Download the Management Server onto the additional host where it will run. Get the software from the following link. - https://www.citrix.com/English/ss/downloads/ -FIXME - You will need a MyCitrix account. - - Install the packages. You should have a file in the form of “&PRODUCT;-VERSION-N-OSVERSION.tar.gzâ€. Untar the file and then run the install.sh script inside it. Replace the file and directory names below with those you are using: - -# tar xzf &PRODUCT;-VERSION-N-OSVERSION.tar.gz -# cd &PRODUCT;-VERSION-N-OSVERSION -# ./install.sh - - You should see a few messages as the installer prepares, followed by a list of choices. - - Choose M to install the Management Server software. - > M - - Wait for a message like “Complete! Done,†which indicates that the software was installed successfully. - - (RHEL or CentOS) When the installation is finished, run the following commands to start essential services (the commands might be different depending on your OS): - -# service rpcbind start -# service nfs start -# chkconfig nfs on -# chkconfig rpcbind on - - - Configure the database client. Note the absence of the --deploy-as argument in this case. - (For more details about the arguments to this command, see .) - - # cloud-setup-databases cloud:<dbpassword>@<dbhost> -e <encryption_type> -m <management_server_key> -k <database_key> - - - (Trial installations only) If you are running the hypervisor on the same machine with the Management Server, edit /etc/sudoers and add the following line: - Defaults:cloud !requiretty - - Configure the OS and start the Management Server: - # cloud-setup-management - The Management Server on this node should now be running. - - Repeat these steps on each additional Management Server. - Be sure to configure a load balancer for the Management Servers. See Management Server Load Balancing. - -
+ Prepare and Start Additional Management Servers + For your second and subsequent Management Servers, you will install the Management Server + software, connect it to the database, and set up the OS for the Management Server. + + + Perform the steps in and or as + appropriate. + + + This step is required only for installations where XenServer is installed on the hypervisor hosts. + Download vhd-util from vhd-util + If the Management Server is RHEL or CentOS, copy vhd-util to + /usr/lib64/cloud/common/scripts/vm/hypervisor/xenserver. + If the Management Server is Ubuntu, copy vhd-util to + /usr/lib/cloud/common/scripts/vm/hypervisor/xenserver/vhd-util. + + + Ensure that necessary services are started and set to start on boot. + # service rpcbind start +# service nfs start +# chkconfig nfs on +# chkconfig rpcbind on + + + + + Configure the database client. Note the absence of the --deploy-as argument in this + case. (For more details about the arguments to this command, see .) + # cloud-setup-databases cloud:dbpassword@dbhost -e encryption_type -m management_server_key -k database_key + + + + Configure the OS and start the Management Server: + # cloud-setup-management + The Management Server on this node should now be running. + + + Repeat these steps on each additional Management Server. + + + Be sure to configure a load balancer for the Management Servers. See Management Server + Load Balancing. + + + \ 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-overview.xml b/docs/en-US/management-server-install-overview.xml index 5bc6f1ba8f2..5f46b0099bd 100644 --- a/docs/en-US/management-server-install-overview.xml +++ b/docs/en-US/management-server-install-overview.xml @@ -23,19 +23,22 @@ -->
- Management Server Installation Overview - This section describes installing the Management Server. There are two slightly different installation flows, depending on how many Management Server nodes will be in your cloud: - - A single Management Server node, with MySQL on the same node. - Multiple Management Server nodes, with MySQL on a node separate from the Management Servers. - - In either case, each machine must meet the system requirements described in System Requirements. - For the sake of security, be sure the public Internet can not access port 8096 or port 8250 on the Management Server. - - The procedure for installing the Management Server is: - - - Prepare the Operating System + Management Server Installation Overview + This section describes installing the Management Server. There are two slightly different installation flows, depending on how many Management Server nodes will be in your cloud: + + A single Management Server node, with MySQL on the same node. + Multiple Management Server nodes, with MySQL on a node separate from the Management Servers. + + In either case, each machine must meet the system requirements described in System Requirements. + For the sake of security, be sure the public Internet can not access port 8096 or port 8250 on the Management Server. + The procedure for installing the Management Server is: + + + Prepare the Operating System + + + (XenServer only) Download and install vhd-util. + Install the First Management Server Install and Configure the MySQL database Prepare NFS Shares diff --git a/docs/en-US/management-server-install-systemvm.xml b/docs/en-US/management-server-install-systemvm.xml index c2c12129ef6..df2c3738abf 100644 --- a/docs/en-US/management-server-install-systemvm.xml +++ b/docs/en-US/management-server-install-systemvm.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -21,36 +21,50 @@ specific language governing permissions and limitations under the License. --> -
- Prepare the System VM Template - Secondary storage must be seeded with a template that is used for &PRODUCT; system VMs. - When copying and pasting a command, be sure the command has pasted as a single line before executing. Some document viewers may introduce unwanted line breaks in copied text. - - On the Management Server, run one or more of the following cloud-install-sys-tmplt commands to retrieve and decompress the system VM template. Run the command for each hypervisor type that you expect end users to run in this Zone. - 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. - This process will require approximately 5 GB of free space on the local file system and up to 30 minutes each time it runs. - - For XenServer: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2 -h xenserver -s <optional-management-server-secret-key> -F - - For vSphere: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova -h vmware -s <optional-management-server-secret-key> -F - - For KVM: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 -h kvm -s <optional-management-server-secret-key> -F - - + Prepare the System VM Template + Secondary storage must be seeded with a template that is used for &PRODUCT; system + VMs. + + When copying and pasting a command, be sure the command has pasted as a single line before + executing. Some document viewers may introduce unwanted line breaks in copied text. + + + + On the Management Server, run one or more of the following cloud-install-sys-tmplt + commands to retrieve and decompress the system VM template. Run the command for each + hypervisor type that you expect end users to run in this Zone. + 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 . + This process will require approximately 5 GB of free space on the local file system and + up to 30 minutes each time it runs. + + + For XenServer: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2 -h xenserver -s <optional-management-server-secret-key> -F - If you are using a separate NFS server, perform this step. If you are using the Management Server as the NFS server, you MUST NOT perform this step. - When the script has finished, unmount secondary storage and remove the created directory. - -# umount /mnt/secondary -# rmdir /mnt/secondary - + + For vSphere: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/burbank/burbank-systemvm-08012012.ova -h vmware -s <optional-management-server-secret-key> -F - Repeat these steps for each secondary storage server. + + For KVM: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 -h kvm -s <optional-management-server-secret-key> -F - + + + + If you are using a separate NFS server, perform this step. If you are using the + Management Server as the NFS server, you MUST NOT perform this step. + When the script has finished, unmount secondary storage and remove the created + directory. + # umount /mnt/secondary +# rmdir /mnt/secondary + + + Repeat these steps for each secondary storage server. + +
diff --git a/docs/en-US/management-server-lb.xml b/docs/en-US/management-server-lb.xml new file mode 100644 index 00000000000..85a86221c80 --- /dev/null +++ b/docs/en-US/management-server-lb.xml @@ -0,0 +1,61 @@ + + +%BOOK_ENTITIES; +]> + +
+ Setting Zone VLAN and Running VM Maximums + &PRODUCT; can use a load balancer to provide a virtual IP for multiple Management + Servers. The administrator is responsible for creating the load balancer rules for the + Management Servers. The application requires persistence or stickiness across multiple sessions. + The following chart lists the ports that should be load balanced and whether or not persistence + is required. + Even if persistence is not required, enabling it is permitted. + + +
+ + Source Port + Destination Port + Protocol + Persistence Required? + + + + + 80 or 443 + 8080 (or 20400 with AJP) + HTTP (or AJP) + Yes + + + 8250 + 8250 + TCP + Yes + + + 8096 + 8096 + HTTP + No + + + + + diff --git a/docs/en-US/management-server-overview.xml b/docs/en-US/management-server-overview.xml index ed301424651..b8e2d53f052 100644 --- a/docs/en-US/management-server-overview.xml +++ b/docs/en-US/management-server-overview.xml @@ -23,36 +23,54 @@ -->
- Management Server Overview - The Management Server is the &PRODUCT; software that manages cloud resources. By interacting with the Management Server through its UI or API, you can configure and manage your cloud infrastructure. - - The Management Server runs on a dedicated server or VM. It controls allocation of virtual machines to hosts and assigns storage and IP addresses to the virtual machine instances. The Management Server runs in a Tomcat container and requires a MySQL database for persistence. - - The machine must meet the system requirements described in System Requirements. - - The Management Server: - - - - Provides the web user interface for the administrator and a reference user interface for end users. - - - Provides the APIs for &PRODUCT;. - - - Manages the assignment of guest VMs to particular hosts. - - - Manages the assignment of public and private IP addresses to particular accounts. - - - Manages the allocation of storage to guests as virtual disks. - - - Manages snapshots, templates, and ISO images, possibly replicating them across data centers. - - - Provides a single point of configuration for the cloud. - - + Management Server Overview + + The Management Server is the &PRODUCT; software that manages cloud + resources. By interacting with the Management Server through its UI or + API, you can configure and manage your cloud infrastructure. + + + The Management Server runs on a dedicated server or VM. It controls + allocation of virtual machines to hosts and assigns storage and IP + addresses to the virtual machine instances. The Management Server + runs in a Tomcat container and requires a MySQL database for persistence. + + + The machine must meet the system requirements described in System + Requirements. + + The Management Server: + + + + + Provides the web user interface for the administrator and a + reference user interface for end users. + + + + Provides the APIs for &PRODUCT;. + + + Manages the assignment of guest VMs to particular hosts. + + + + Manages the assignment of public and private IP addresses to + particular accounts. + + + + Manages the allocation of storage to guests as virtual disks. + + + + Manages snapshots, templates, and ISO images, possibly + replicating them across data centers. + + + + Provides a single point of configuration for the cloud. + +
diff --git a/docs/en-US/manual-live-migration.xml b/docs/en-US/manual-live-migration.xml index 677cfc46527..225f0ba3317 100644 --- a/docs/en-US/manual-live-migration.xml +++ b/docs/en-US/manual-live-migration.xml @@ -30,7 +30,7 @@ The destination host must be in the same cluster as the original host.The VM must not be using local disk storage.The destination host must have enough available capacity. If not, the VM will remain in the "migrating" state until memory becomes available. - (OVM) If the VM is running on the OVM hypervisor, it must not have an ISO attached. Live migration of a VM with attached ISO is not supported in OVM. + To manually live migrate a virtual machine 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/minimum-system-requirements.xml b/docs/en-US/minimum-system-requirements.xml index 1bbe1e2db85..0e497dd33f1 100644 --- a/docs/en-US/minimum-system-requirements.xml +++ b/docs/en-US/minimum-system-requirements.xml @@ -33,10 +33,7 @@ Operating system: - Preferred: RHEL 6.2+ 64-bit (https://access.redhat.com/downloads) or CentOS 6.2+ 64-bit (http://isoredirect.centos.org/centos/6/isos/x86_64/). - Also supported (v3.0.3 and greater): RHEL and CentOS 5.4-5.x 64-bit - It is highly recommended that you purchase a RHEL support license. - Citrix support can not be responsible for helping fix issues with the underlying OS. + Preferred: CentOS/RHEL 6.3+ or Ubuntu 12.04(.1) 64-bit x86 CPU (more cores results in better performance) @@ -51,29 +48,26 @@ Host/Hypervisor System Requirements The host is where the cloud services run in the form of guest virtual machines. Each host is one machine that meets the following requirements: - Must be 64-bit and must support HVM (Intel-VT or AMD-V enabled). + Must support HVM (Intel-VT or AMD-V enabled). 64-bit x86 CPU (more cores results in better performance) Hardware virtualization support required 4 GB of memory 36 GB of local disk At least 1 NIC - Statically allocated IP Address + If DHCP is used for hosts, ensure that no conflict occurs between DHCP server used for these hosts and the DHCP router created by &PRODUCT;. Latest hotfixes applied to hypervisor software When you deploy &PRODUCT;, the hypervisor host must not have any VMs already running + All hosts within a cluster must be homogenous. The CPUs must be of the same type, count, and feature flags. Hosts have additional requirements depending on the hypervisor. See the requirements listed at the top of the Installation section for your chosen hypervisor: - - Citrix XenServer Installation - VMware vSphere Installation and Configuration - KVM Installation and Configuration - Oracle VM (OVM) Installation and Configuration - - - - Be sure you fulfill the additional hypervisor requirements and installation steps provided in this Guide. Hypervisor hosts must be properly prepared to work with CloudStack. For example, the requirements for XenServer are listed under Citrix XenServer Installation. - - - - - - + + Be sure you fulfill the additional hypervisor requirements and installation steps provided in this Guide. Hypervisor hosts must be properly prepared to work with CloudStack. For example, the requirements for XenServer are listed under Citrix XenServer Installation. + + + + + + + + + diff --git a/docs/en-US/network-offerings.xml b/docs/en-US/network-offerings.xml index 0713be845db..7386e109883 100644 --- a/docs/en-US/network-offerings.xml +++ b/docs/en-US/network-offerings.xml @@ -24,7 +24,6 @@
Network Offerings For the most up-to-date list of supported network services, see the &PRODUCT; UI or call listNetworkServices. - A network offering is a named set of network services, such as: DHCP @@ -41,9 +40,7 @@ When creating a new VM, the user chooses one of the available network offerings, and that determines which network services the VM can use. The &PRODUCT; administrator can create any number of custom network offerings, in addition to the default network offerings provided by &PRODUCT;. By creating multiple custom network offerings, you can set up your cloud to offer different classes of service on a single multi-tenant physical network. For example, while the underlying physical wiring may be the same for two tenants, tenant A may only need simple firewall protection for their website, while tenant B may be running a web server farm and require a scalable firewall solution, load balancing solution, and alternate networks for accessing the database backend. If you create load balancing rules while using a network service offering that includes an external load balancer device such as NetScaler, and later change the network service offering to one that uses the &PRODUCT; virtual router, you must create a firewall rule on the virtual router for each of your existing load balancing rules so that they continue to function. - When creating a new virtual network, the &PRODUCT; administrator chooses which network offering to enable for that network. Each virtual network is associated with one network offering. A virtual network can be upgraded or downgraded by changing its associated network offering. If you do this, be sure to reprogram the physical network to match. &PRODUCT; also has internal network offerings for use by &PRODUCT; system VMs. These network offerings are not visible to users but can be modified by administrators. - - +
diff --git a/docs/en-US/network-setup.xml b/docs/en-US/network-setup.xml new file mode 100644 index 00000000000..ceee190d4ca --- /dev/null +++ b/docs/en-US/network-setup.xml @@ -0,0 +1,35 @@ + + +%BOOK_ENTITIES; +]> + + + Network Setup + Achieving the correct networking setup is crucial to a successful &PRODUCT; + installation. This section contains information to help you make decisions and follow the right + procedures to get your network set up correctly. + + + + + + + + + + diff --git a/docs/en-US/networks-for-users-overview.xml b/docs/en-US/networks-for-users-overview.xml new file mode 100644 index 00000000000..19602c48b2a --- /dev/null +++ b/docs/en-US/networks-for-users-overview.xml @@ -0,0 +1,35 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Overview of Setting Up Networking for Users + People using cloud infrastructure have a variety of needs and preferences when it comes to the networking services provided by the cloud. As a &PRODUCT; administrator, you can do the following things to set up networking for your users: + + Set up physical networks in zones + Set up several different providers for the same service on a single physical network (for example, both Cisco and Juniper firewalls) + Bundle different types of network services into network offerings, so users can choose the desired network services for any given virtual machine + Add new network offerings as time goes on so end users can upgrade to a better class of service on their network + Provide more ways for a network to be accessed by a user, such as through a project of which the user is a member + +
diff --git a/docs/en-US/networks.xml b/docs/en-US/networks.xml index d4ed76d4d0c..a7b9ea12466 100644 --- a/docs/en-US/networks.xml +++ b/docs/en-US/networks.xml @@ -45,4 +45,4 @@ - + \ No newline at end of file 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/Book_Info_Admin.xml b/docs/en-US/offerings.xml similarity index 54% rename from docs/en-US/Book_Info_Admin.xml rename to docs/en-US/offerings.xml index 6bf89b328c8..10252fd8af4 100644 --- a/docs/en-US/Book_Info_Admin.xml +++ b/docs/en-US/offerings.xml @@ -22,25 +22,10 @@ under the License. --> - - Apache CloudStack 4.0 - Administrator's Guide - Revised September 11, 2012 01:32 am Pacific - - - - - If you have already installed &PRODUCT; or you want to learn more about the ongoing - operation and maintenance of a &PRODUCT;-powered cloud, read this documentation. It - will help you start using, configuring, and managing the ongoing operation of your cloud. - - - - - - - - - - - + + Service Offerings + In this chapter we discuss compute, disk, and system service offerings. Network offerings + are discussed in the section on setting up networking for users. + + + 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/ovm-install.xml b/docs/en-US/ovm-install.xml new file mode 100644 index 00000000000..fa4a86b0776 --- /dev/null +++ b/docs/en-US/ovm-install.xml @@ -0,0 +1,29 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Installing OVM for &PRODUCT; + TODO + +
diff --git a/docs/en-US/ovm-requirements.xml b/docs/en-US/ovm-requirements.xml new file mode 100644 index 00000000000..70a8920a8ac --- /dev/null +++ b/docs/en-US/ovm-requirements.xml @@ -0,0 +1,28 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ System Requirements for OVM + TODO +
diff --git a/docs/en-US/plugin-niciranvp-features.xml b/docs/en-US/plugin-niciranvp-features.xml index cdcda9e2aa6..b67323d56d2 100644 --- a/docs/en-US/plugin-niciranvp-features.xml +++ b/docs/en-US/plugin-niciranvp-features.xml @@ -22,8 +22,8 @@ -->
Features of the Nicira NVP Plugin - In CloudStack release 4.0.x this plugin supports the Connectivity service. This service is responsible for creating Layer 2 networks supporting the networks created by Guests. In other words when an tennant creates a new network, instead of the traditional VLAN a logical network will be created by sending the appropriate calls to the Nicira NVP Controller. + In CloudStack release 4.0.0-incubating this plugin supports the Connectivity service. This service is responsible for creating Layer 2 networks supporting the networks created by Guests. In other words when an tennant creates a new network, instead of the traditional VLAN a logical network will be created by sending the appropriate calls to the Nicira NVP Controller. The plugin has been tested with Nicira NVP versions 2.1.0, 2.2.0 and 2.2.1 - In CloudStack 4.0.x only the XenServer hypervisor is supported for use in combination with Nicira NVP - In CloudStack 4.0.x the UI components for this plugin are not complete, configuration is done by sending commands to the API -
\ No newline at end of file + In CloudStack 4.0.0-incubating only the XenServer hypervisor is supported for use in combination with Nicira NVP + In CloudStack 4.0.0-incubating the UI components for this plugin are not complete, configuration is done by sending commands to the API +
diff --git a/docs/en-US/plugin-niciranvp-provider.xml b/docs/en-US/plugin-niciranvp-provider.xml index d81db99d9c0..80fb2273238 100644 --- a/docs/en-US/plugin-niciranvp-provider.xml +++ b/docs/en-US/plugin-niciranvp-provider.xml @@ -27,7 +27,7 @@ addNetworkServiceProvider - name = "NiciraNVP" + name = "NiciraNvp" physicalnetworkid = <the uuid of the physical network> diff --git a/docs/en-US/plugin-niciranvp-revisions.xml b/docs/en-US/plugin-niciranvp-revisions.xml index 6e455cafaf7..b8e6935c5d1 100644 --- a/docs/en-US/plugin-niciranvp-revisions.xml +++ b/docs/en-US/plugin-niciranvp-revisions.xml @@ -36,7 +36,7 @@ - Documentation created for 4.0.x version of the NVP Plugin + Documentation created for 4.0.0-incubating version of the NVP Plugin diff --git a/docs/en-US/prepare-system-vm-template.xml b/docs/en-US/prepare-system-vm-template.xml index 160cea426ed..22674d47952 100644 --- a/docs/en-US/prepare-system-vm-template.xml +++ b/docs/en-US/prepare-system-vm-template.xml @@ -1,5 +1,5 @@ - %BOOK_ENTITIES; ]> @@ -21,37 +21,54 @@ specific language governing permissions and limitations under the License. --> -
- Prepare the System VM Template - Secondary storage must be seeded with a template that is used for &PRODUCT; system VMs. - When copying and pasting a command, be sure the command has pasted as a single line before executing. Some document viewers may introduce unwanted line breaks in copied text. - - On the Management Server, run one or more of the following cloud-install-sys-tmplt commands to retrieve and decompress the system VM template. Run the command for each hypervisor type that you expect end users to run in this Zone. - 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. - This process will require approximately 5 GB of free space on the local file system and up to 30 minutes each time it runs. - - For XenServer: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2 -h xenserver -s <optional-management-server-secret-key> -F - - For vSphere: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.ova -h vmware -s <optional-management-server-secret-key> -F - - For KVM: - # /usr/lib64/cloud/agent/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 -h kvm -s <optional-management-server-secret-key> -F - - - - If you are using a separate NFS server, perform this step. If you are using the Management - Server as the NFS server, you MUST NOT perform this step. - When the script has finished, unmount secondary storage and remove the created directory. - -# umount /mnt/secondary -# rmdir /mnt/secondary - - - Repeat these steps for each secondary storage server. - - + Prepare the System VM Template + Secondary storage must be seeded with a template that is used for &PRODUCT; system VMs. + Citrix provides you with the necessary binary package of the system VM. + + When copying and pasting a command, be sure the command has pasted as a single line before + executing. Some document viewers may introduce unwanted line breaks in copied text. + + + + On the Management Server, run one or more of the following cloud-install-sys-tmplt + commands to retrieve and decompress the system VM template. Run the command for each + hypervisor type that you expect end users to run in this Zone. + 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 . + This process will require approximately 5 GB of free space on the local file system and + up to 30 minutes each time it runs. + + + For XenServer: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.vhd.bz2 -h xenserver -s <optional-management-server-secret-key> -F + + + For vSphere: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.ova -h vmware -s <optional-management-server-secret-key> -F + + + For KVM: + # /usr/lib64/cloud/common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://download.cloud.com/templates/acton/acton-systemvm-02062012.qcow2.bz2 -h kvm -s <optional-management-server-secret-key> -F + + + + + If you are using a separate NFS server, perform this step. + + Do not perform this step if you are using the Management Server as the NFS + server. + + When the script has finished, unmount secondary storage and remove the created + directory. + # umount /mnt/secondary +# rmdir /mnt/secondary + + + Repeat these steps for each secondary storage server. + +
diff --git a/docs/en-US/primary-storage.xml b/docs/en-US/primary-storage.xml index de4005e38d8..4ab37ef6f17 100644 --- a/docs/en-US/primary-storage.xml +++ b/docs/en-US/primary-storage.xml @@ -24,11 +24,11 @@
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/query-filter.xml b/docs/en-US/query-filter.xml index fa5ea6344c1..1c0e493972d 100644 --- a/docs/en-US/query-filter.xml +++ b/docs/en-US/query-filter.xml @@ -24,8 +24,8 @@
Query Filter -The query filter is used to find a mapped user in the external LDAP server. The query filter should uniquely map the CloudPlatform user to LDAP user for a meaningful authentication. For more information about query filter syntax, consult the documentation for your LDAP server. -The CloudPlatform query filter wildcards are: +The query filter is used to find a mapped user in the external LDAP server. The query filter should uniquely map the &PRODUCT; user to LDAP user for a meaningful authentication. For more information about query filter syntax, consult the documentation for your LDAP server. +The &PRODUCT; query filter wildcards are:
@@ -51,9 +51,9 @@ The following examples assume you are using Active Directory, and refer to user attributes from the Active Directory schema. -If the CloudPlatform user name is the same as the LDAP user ID: +If the &PRODUCT; user name is the same as the LDAP user ID:(uid=%u) -If the CloudPlatform user name is the LDAP display name: +If the &PRODUCT; user name is the LDAP display name:(displayName=%u)To find a user by email address:(mail=%e) diff --git a/docs/en-US/Book_Info_Build_All.xml b/docs/en-US/removing-hosts.xml similarity index 58% rename from docs/en-US/Book_Info_Build_All.xml rename to docs/en-US/removing-hosts.xml index 7243149ee20..468f36ecd3f 100644 --- a/docs/en-US/Book_Info_Build_All.xml +++ b/docs/en-US/removing-hosts.xml @@ -22,23 +22,9 @@ under the License. --> - - CloudStack Guide - Revised September 18, 2012 10:48 am Pacific - Apache CloudStack (incubating) - 3.0 - 1 - - - Complete technical documentation for Apache CloudStack. - - - - - - - - - - - +
+ Removing Hosts + Hosts can be removed from the cloud as needed. The procedure to remove a host depends on the hypervisor type. + + +
diff --git a/docs/en-US/roles.xml b/docs/en-US/roles.xml index 473e37b77f9..775e30b25f5 100644 --- a/docs/en-US/roles.xml +++ b/docs/en-US/roles.xml @@ -25,7 +25,7 @@
Roles - The CloudPlatform API supports three access roles: + The &PRODUCT; API supports three access roles: Root Admin. Access to all features of the cloud, including both virtual and physical resource management. Domain Admin. Access to only the virtual resources of the clouds that belong to the administrator’s domain. diff --git a/docs/en-US/runtime-behavior-of-primary-storage.xml b/docs/en-US/runtime-behavior-of-primary-storage.xml index c6563907131..479ebce1ce1 100644 --- a/docs/en-US/runtime-behavior-of-primary-storage.xml +++ b/docs/en-US/runtime-behavior-of-primary-storage.xml @@ -24,7 +24,7 @@
Runtime Behavior of Primary Storage - Root volumes are created automatically when a virtual machine is created. Root volumes are deleted when the VM is destroyed. Data volumes can be created and dynamically attached to VMs (although, when the Oracle VM hypervisor is used, the VM must be stopped before an additional volume can be attached). Data volumes are not deleted when VMs are destroyed. + Root volumes are created automatically when a virtual machine is created. Root volumes are deleted when the VM is destroyed. Data volumes can be created and dynamically attached to VMs. Data volumes are not deleted when VMs are destroyed. Administrators should monitor the capacity of primary storage devices and add additional primary storage as needed. See the Advanced Installation Guide. Administrators add primary storage to the system by creating a &PRODUCT; storage pool. Each storage pool is associated with a cluster.
diff --git a/docs/en-US/runtime-internal-comm-req.xml b/docs/en-US/runtime-internal-comm-req.xml new file mode 100644 index 00000000000..f4539dd0307 --- /dev/null +++ b/docs/en-US/runtime-internal-comm-req.xml @@ -0,0 +1,39 @@ + + +%BOOK_ENTITIES; +]> + +
+ Runtime Internal Communications Requirements + + + The Management Servers communicate with each other to coordinate tasks. This + communication uses TCP on ports 8250 and 9090. + + + The console proxy VMs connect to all hosts in the zone over the management traffic + network. Therefore the management traffic network of any given pod in the zone must have + connectivity to the management traffic network of all other pods in the zone. + + + The secondary storage VMs and console proxy VMs connect to the Management Server on + port 8250. If you are using multiple Management Servers, the load balanced IP address of the + Management Servers on port 8250 must be reachable. + + +
diff --git a/docs/en-US/secondary-storage.xml b/docs/en-US/secondary-storage.xml index 98ea0dc236b..4a01c27f72d 100644 --- a/docs/en-US/secondary-storage.xml +++ b/docs/en-US/secondary-storage.xml @@ -25,9 +25,6 @@
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. - - - - +
diff --git a/docs/en-US/security-groups.xml b/docs/en-US/security-groups.xml index 07b9f79bdd1..b6eecc3eed8 100644 --- a/docs/en-US/security-groups.xml +++ b/docs/en-US/security-groups.xml @@ -28,6 +28,7 @@ ======= Security Groups + >>>>>>> master diff --git a/docs/en-US/security-req.xml b/docs/en-US/security-req.xml new file mode 100644 index 00000000000..a4869b43a70 --- /dev/null +++ b/docs/en-US/security-req.xml @@ -0,0 +1,24 @@ + + +%BOOK_ENTITIES; +]> + +
+ Security Requirements + The public Internet must not be able to access port 8096 or port 8250 on the Management Server. +
diff --git a/docs/en-US/set-zone-vlan-run-vm-max.xml b/docs/en-US/set-zone-vlan-run-vm-max.xml new file mode 100644 index 00000000000..2159b753ce7 --- /dev/null +++ b/docs/en-US/set-zone-vlan-run-vm-max.xml @@ -0,0 +1,65 @@ + + +%BOOK_ENTITIES; +]> + +
+ Setting Zone VLAN and Running VM Maximums + In the external networking case, every VM in a zone must have a unique guest IP address. + There are two variables that you need to consider in determining how to configure &PRODUCT; + to support this: how many Zone VLANs do you expect to have and how many VMs do you expect to + have running in the Zone at any one time. + Use the following table to determine how to configure &PRODUCT; for your + deployment. + + +
+ + guest.vlan.bits + Maximum Running VMs per Zone + Maximum Zone VLANs + + + + + 12 + 4096 + 4094 + + + 11 + 8192 + 2048 + + + 10 + 16384 + 1024 + + + 10 + 32768 + 512 + + + + + Based on your deployment's needs, choose the appropriate value of guest.vlan.bits. Set it as + described in Edit the Global Configuration Settings (Optional) section and restart the + Management Server. + 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/source-prereqs.xml b/docs/en-US/source-prereqs.xml new file mode 100644 index 00000000000..6c2bc2a3cb8 --- /dev/null +++ b/docs/en-US/source-prereqs.xml @@ -0,0 +1,42 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Prerequisites for building Apache CloudStack + + There are a number of prerequisites needed to build &PRODUCT;. This + document assumes compilation on a Linux system that uses RPMs or DEBs + for package management. + + + The minimum bootstrapped prerequisites for building &PRODUCT; includes + the following: + + ant + maven (version 3) + Java (Java 6/OpenJDK 1.6) + rpmbuild or dpkg-dev + + +
diff --git a/docs/en-US/source.xml b/docs/en-US/source.xml new file mode 100644 index 00000000000..3cb4af2321f --- /dev/null +++ b/docs/en-US/source.xml @@ -0,0 +1,47 @@ + + +%BOOK_ENTITIES; +]> + + + + + Building from Source + The official &PRODUCT; release is always in source code form. While there may + exist convenience binaries in various forms from a number of places, the + source is the canonical release will be source. In this document we'll cover + acquiring the source release, building that into binary, deployable packages. + + + While building and deploying directly from source is certainly possible, the reality + of Infrastructure-as-a-Service cloud computing implies a need to deploy packages on + a potentially large number of systems, which RPMs and DEBs fill nicely. + + + Building and deploying directly from source is thus outside the scope of this + document, but is documented in the INSTALL.md file in the release. + + + + + + + + diff --git a/docs/en-US/ssl.xml b/docs/en-US/ssl.xml new file mode 100644 index 00000000000..9aeb2f91aa8 --- /dev/null +++ b/docs/en-US/ssl.xml @@ -0,0 +1,29 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ SSL (Optional) + &PRODUCT; provides HTTP access in its default installation. There are a number of technologies and sites which choose to implement SSL. As a result, we have left &PRODUCT; to expose HTTP under the assumption that a site will implement its typical practice. + &PRODUCT; uses Tomcat as its servlet container. For sites that would like &PRODUCT; to terminate the SSL session, Tomcat’s SSL access may be enabled. Tomcat SSL configuration is described at http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html. +
diff --git a/docs/en-US/storage-nw-topology-req.xml b/docs/en-US/storage-nw-topology-req.xml new file mode 100644 index 00000000000..a594babea37 --- /dev/null +++ b/docs/en-US/storage-nw-topology-req.xml @@ -0,0 +1,28 @@ + + +%BOOK_ENTITIES; +]> + +
+ Storage Network Topology Requirements + The secondary storage NFS export is mounted by the secondary storage VM. Secondary storage + traffic goes over the management traffic network, even if there is a separate storage network. + Primary storage traffic goes over the storage network, if available. If you choose to place + secondary storage NFS servers on the storage network, you must make sure there is a route from + the management traffic network to the storage network. +
diff --git a/docs/en-US/storage.xml b/docs/en-US/storage.xml index 49ebed9c42a..580fe59e1e1 100644 --- a/docs/en-US/storage.xml +++ b/docs/en-US/storage.xml @@ -30,4 +30,3 @@ - diff --git a/docs/en-US/system-reserved-ip-addresses.xml b/docs/en-US/system-reserved-ip-addresses.xml index 7f4981726ea..7ae9fa8df9f 100644 --- a/docs/en-US/system-reserved-ip-addresses.xml +++ b/docs/en-US/system-reserved-ip-addresses.xml @@ -31,9 +31,9 @@ Provide private IPs for the system in each pod and provision them in &PRODUCT;. For KVM and XenServer, the recommended number of private IPs per pod is one per host. If you expect a pod to grow, add enough private IPs now to accommodate the growth. In a zone that uses advanced networking: - For vSphere with advanced networking, we recommend provisioning enough private IPs for your total number of customers, plus enough for the required &PRODUCT; System VMs. Typically, about 10 additional IPs are required for the System VMs. For more information about System VMs, see Working with System Virtual Machines in the Administrator's Guide. + For zones with advanced networking, we recommend provisioning enough private IPs for your total number of customers, plus enough for the required &PRODUCT; System VMs. Typically, about 10 additional IPs are required for the System VMs. For more information about System VMs, see Working with System Virtual Machines in the Administrator's Guide. When advanced networking is being used, the number of private IP addresses available in each pod varies depending on which hypervisor is running on the nodes in that pod. Citrix XenServer and KVM use link-local addresses, which in theory provide more than 65,000 private IP addresses within the address block. As the pod grows over time, this should be more than enough for any reasonable number of hosts as well as IP addresses for guest virtual routers. VMWare ESXi, by contrast uses any administrator-specified subnetting scheme, and the typical administrator provides only 255 IPs per pod. Since these are shared by physical machines, the guest virtual router, and other entities, it is possible to run out of private IPs when scaling up a pod whose nodes are running ESXi. - To ensure adequate headroom to scale private IP space in an ESXi pod that uses advanced networking, use one or more of the following techniques: + To ensure adequate headroom to scale private IP space in an ESXi pod that uses advanced networking, use one or both of the following techniques: Specify a larger CIDR block for the subnet. A subnet mask with a /20 suffix will provide more than 4,000 IP addresses. Create multiple pods, each with its own subnet. For example, if you create 10 pods and each pod has 255 IPs, this will provide 2,550 IP addresses. diff --git a/docs/en-US/tagging-resources.xml b/docs/en-US/tagging-resources.xml new file mode 100644 index 00000000000..31ee3825e4a --- /dev/null +++ b/docs/en-US/tagging-resources.xml @@ -0,0 +1,69 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Using Tags to Organize Resources in the Cloud + A tag is a key-value pair that stores metadata about a resource in the cloud. Tags are + useful for categorizing resources. For example, you can tag a user VM with a + value that indicates the user's city of residence. In this case, the key would + be "city" and the value might be "Toronto" or "Tokyo." You can then request + &PRODUCT; to find all resources that have a given tag; for example, VMs for + users in a given city. + You can tag a user virtual machine, volume, snapshot, guest network, template, + ISO, firewall rule, port forwarding rule, public IP address, security group, + load balancer rule, project, VPC, network ACL, or static route. You can not tag + a remote access VPN. + You can work with tags through the UI or through the API commands createTags, + deleteTags, and listTags. You can define multiple tags for each resource. There + is no limit on the number of tags you can define. Each tag can be up to 255 + characters long. Users can define tags on the resources they own, and + administrators can define tags on any resources in the cloud. + An optional input parameter, "tags," exists on many of the list* API commands. + The following example shows how to use this new parameter to find all the volumes + having tag region=canada OR tag city=Toronto: + command=listVolumes + &listAll=true + &tags[0].key=region + &tags[0].value=canada + &tags[1].key=city + &tags[1].value=Toronto + The following API commands have the "tags" input parameter: + + listVirtualMachines + listVolumes + listSnapshots + listNetworks + listTemplates + listIsos + listFirewallRules + listPortForwardingRules + listPublicIpAddresses + listSecurityGroups + listLoadBalancerRules + listProjects + listVPCs + listNetworkACLs + listStaticRoutes + +
diff --git a/docs/en-US/time-zones.xml b/docs/en-US/time-zones.xml index c187ad397d7..6b3b64ed85c 100644 --- a/docs/en-US/time-zones.xml +++ b/docs/en-US/time-zones.xml @@ -24,7 +24,7 @@ Time Zones - The following time zone identifiers are accepted by &PRODUCT;. There are several places that have a time zone as a required or optional parameter. These include scheduling recurring snapshots, creating a user, and specifying the usage time zone in the Configuration table. . + The following time zone identifiers are accepted by &PRODUCT;. There are several places that have a time zone as a required or optional parameter. These include scheduling recurring snapshots, creating a user, and specifying the usage time zone in the Configuration table. @@ -134,5 +134,4 @@ - - + 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/topology-req.xml b/docs/en-US/topology-req.xml new file mode 100644 index 00000000000..65c9c2ea5c6 --- /dev/null +++ b/docs/en-US/topology-req.xml @@ -0,0 +1,31 @@ + + +%BOOK_ENTITIES; +]> + +
+ Topology Requirements + + + + + + + + +
diff --git a/docs/en-US/troubleshooting-lb-rules-fails.xml b/docs/en-US/troubleshooting-lb-rules-fails.xml index c507178e831..62955341e23 100644 --- a/docs/en-US/troubleshooting-lb-rules-fails.xml +++ b/docs/en-US/troubleshooting-lb-rules-fails.xml @@ -30,7 +30,7 @@ Cause - Load balancing rules were created while using a network service offering that includes an external load balancer device such as NetScaler, and later the network service offering changed to one that uses the CloudPlatform virtual router. + Load balancing rules were created while using a network service offering that includes an external load balancer device such as NetScaler, and later the network service offering changed to one that uses the &PRODUCT; virtual router. Solution diff --git a/docs/en-US/troubleshooting.xml b/docs/en-US/troubleshooting.xml index 1fe03475528..570d02e4315 100644 --- a/docs/en-US/troubleshooting.xml +++ b/docs/en-US/troubleshooting.xml @@ -21,13 +21,14 @@ specific language governing permissions and limitations under the License. --> + Troubleshooting - - - + + + 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 90% 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 index c4bf37f6bbe..764d18825b8 100644 --- a/docs/en-US/troubleshooting-maintenance-mode-not-working-on-vCenter.xml +++ b/docs/en-US/troublesht-mtn-mode-not-working-on-vCenter.xml @@ -30,7 +30,7 @@ Cause - The CloudPlatform administrator UI was used to place the host in scheduled maintenance mode. This mode is separate from vCenter's maintenance mode. + The &PRODUCT; administrator UI was used to place the host in scheduled maintenance mode. This mode is separate from vCenter's maintenance mode. Solution diff --git a/docs/en-US/upload-existing-volume-to-vm.xml b/docs/en-US/upload-existing-volume-to-vm.xml index 5966ce68de1..86dc8e54758 100644 --- a/docs/en-US/upload-existing-volume-to-vm.xml +++ b/docs/en-US/upload-existing-volume-to-vm.xml @@ -59,10 +59,10 @@ KVM QCOW2 - + diff --git a/docs/en-US/upload-template.xml b/docs/en-US/upload-template.xml index 9f0ae019ccd..f270c899a53 100644 --- a/docs/en-US/upload-template.xml +++ b/docs/en-US/upload-template.xml @@ -23,7 +23,7 @@ -->
Uploading Templates - If you are uploading a template that was created using vSphere Client, be sure the OVA file does not contain an ISO. If it does, the deployment of VMs from the template will fail. + vSphere Templates and ISOsIf you are uploading a template that was created using vSphere Client, be sure the OVA file does not contain an ISO. If it does, the deployment of VMs from the template will fail. Templates are uploaded based on a URL. HTTP is the supported access protocol. Templates are frequently large files. You can optionally gzip them to decrease upload times. To upload a template: @@ -44,7 +44,7 @@ If the operating system of the stopped VM is listed, choose it. If the OS type of the stopped VM is not listed, choose Other. - Generally you should not choose an older version of the OS than the version in the image. For example, choosing CentOS 5.4 to support a CentOS 6.2 image will in general not work. In those cases you should choose Other. + You should not choose an older version of the OS than the version in the image. For example, choosing CentOS 5.4 to support a CentOS 6.2 image will in general not work. In those cases you should choose Other. Hypervisor: The supported hypervisors are listed. Select the desired one. 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/user-services-overview.xml b/docs/en-US/user-services-overview.xml index 95761217fbf..12504e6ca4e 100644 --- a/docs/en-US/user-services-overview.xml +++ b/docs/en-US/user-services-overview.xml @@ -5,35 +5,68 @@ ]> - User Services Overview - In addition to the physical and logical infrastructure of your cloud, and the &PRODUCT; software and servers, you also need a layer of user services so that people can actually make use of the cloud. This means not just a user UI, but a set of options and resources that users can choose from, such as templates for creating virtual machines, disk storage, and more. If you are running a commercial service, you will be keeping track of what services and resources users are consuming and charging them for that usage. Even if you do not charge anything for people to use your cloud – say, if the users are strictly internal to your organization, or just friends who are sharing your cloud – you can still keep track of what services they use and how much of them. -
- Service Offerings, Disk Offerings, Network Offerings, and Templates - A user creating a new instance can make a variety of choices about its characteristics and capabilities. &PRODUCT; provides several ways to present users with choices when creating a new instance: - - Service Offerings, defined by the &PRODUCT; administrator, provide a choice of CPU speed, number of CPUs, RAM size, tags on the root disk, and other choices. See Creating a New Compute Offering. - Disk Offerings, defined by the &PRODUCT; administrator, provide a choice of disk size for primary data storage. See Creating a New Disk Offering. - Network Offerings, defined by the &PRODUCT; administrator, describe the feature set that is available to end users from the virtual router or external networking devices on a given guest network. See Network Offerings. - Templates, defined by the &PRODUCT; administrator or by any &PRODUCT; user, are the base OS images that the user can choose from when creating a new instance. For example, &PRODUCT; includes CentOS as a template. See Working with Templates. - - In addition to these choices that are provided for users, there is another type of service offering which is available only to the &PRODUCT; root administrator, and is used for configuring virtual infrastructure resources. For more information, see Upgrading a Virtual Router with System Service Offerings. -
-
\ No newline at end of file + User Services Overview + In addition to the physical and logical infrastructure of your cloud, + and the &PRODUCT; software and servers, you also need a layer of user + services so that people can actually make use of the cloud. This means + not just a user UI, but a set of options and resources that users can + choose from, such as templates for creating virtual machines, disk + storage, and more. If you are running a commercial service, you will be + keeping track of what services and resources users are consuming and + charging them for that usage. Even if you do not charge anything for + people to use your cloud – say, if the users are strictly internal to your + organization, or just friends who are sharing your cloud – you can still + keep track of what services they use and how much of them. + +
+ Service Offerings, Disk Offerings, Network Offerings, and Templates + A user creating a new instance can make a variety of choices about + its characteristics and capabilities. &PRODUCT; provides several ways to + present users with choices when creating a new instance: + + + Service Offerings, defined by the &PRODUCT; administrator, + provide a choice of CPU speed, number of CPUs, RAM size, tags on the + root disk, and other choices. See Creating a New Compute Offering. + + Disk Offerings, defined by the &PRODUCT; administrator, + provide a choice of disk size for primary data storage. See Creating a + New Disk Offering. + + Network Offerings, defined by the &PRODUCT; administrator, + describe the feature set that is available to end users from the virtual + router or external networking devices on a given guest network. See + Network Offerings. + + Templates, defined by the &PRODUCT; administrator or by + any &PRODUCT; user, are the base OS images that the user can choose + from when creating a new instance. For example, &PRODUCT; includes + CentOS as a template. See Working with Templates. + + + In addition to these choices that are provided for users, there is + another type of service offering which is available only to the &PRODUCT; + root administrator, and is used for configuring virtual infrastructure + resources. For more information, see Upgrading a Virtual Router with + System Service Offerings. + +
+ diff --git a/docs/en-US/using-multiple-guest-networks.xml b/docs/en-US/using-multiple-guest-networks.xml index 7a8ea48e975..4e7da1e187f 100644 --- a/docs/en-US/using-multiple-guest-networks.xml +++ b/docs/en-US/using-multiple-guest-networks.xml @@ -26,7 +26,7 @@ In zones that use advanced networking, additional networks for guest traffic may be added at any time after the initial installation. You can also customize the domain name associated with the network by specifying a DNS suffix for each network. A VM's networks are defined at VM creation time. A VM cannot add or remove networks after it has been created, although the user can go into the guest and remove the IP address from the NIC on a particular network. Each VM has just one default network. The virtual router's DHCP reply will set the guest's default gateway as that for the default network. Multiple non-default networks may be added to a guest in addition to the single, required default network. The administrator can control which networks are available as the default network. - Additional networks can either be available to all accounts or be assigned to a specific account. Networks that are available to all accounts are zone-wide. Any user with access to the zone can create a VM with access to that network. These zone-wide networks provide little or no isolation between guests. Networks that are assigned to a specific account provide strong isolation. + Additional networks can either be available to all accounts or be assigned to a specific account. Networks that are available to all accounts are zone-wide. Any user with access to the zone can create a VM with access to that network. These zone-wide networks provide little or no isolation between guests.Networks that are assigned to a specific account provide strong isolation. diff --git a/docs/en-US/using-netscaler-load-balancers.xml b/docs/en-US/using-netscaler-load-balancers.xml index 7febb8248a3..c2044de527b 100644 --- a/docs/en-US/using-netscaler-load-balancers.xml +++ b/docs/en-US/using-netscaler-load-balancers.xml @@ -34,7 +34,7 @@ NetScaler ADC Type Description of Capabilities - &PRODUCT; 3.0.3 Supported Features + &PRODUCT; Supported Features
diff --git a/docs/en-US/using-swift-for-secondary-storage.xml b/docs/en-US/using-swift-for-secondary-storage.xml index bf238ca6466..329cf81de08 100644 --- a/docs/en-US/using-swift-for-secondary-storage.xml +++ b/docs/en-US/using-swift-for-secondary-storage.xml @@ -24,6 +24,6 @@
Using Swift for Secondary Storage - CloudPlatform supports OpenStack Object Storage ( Swift) for secondary storage. When using Swift, you configure Swift storage for the entire CloudPlatform, then set up NFS secondary storage for each zone as usual. The NFS storage in each zone acts as a staging area through which all templates and other secondary storage data pass before being forwarded to Swift. The Swift storage acts as a cloud-wide resource, making templates and other data available to any zone in the cloud. There is no hierarchy in the Swift storage, just one Swift container per storage object. Any secondary storage in the whole cloud can pull a container from Swift at need. It is not necessary to copy templates and snapshots from one zone to another, as would be required when using zone NFS alone. Everything is available everywhere + &PRODUCT; supports OpenStack Object Storage ( Swift) for secondary storage. When using Swift, you configure Swift storage for the entire &PRODUCT;, then set up NFS secondary storage for each zone as usual. The NFS storage in each zone acts as a staging area through which all templates and other secondary storage data pass before being forwarded to Swift. The Swift storage acts as a cloud-wide resource, making templates and other data available to any zone in the cloud. There is no hierarchy in the Swift storage, just one Swift container per storage object. Any secondary storage in the whole cloud can pull a container from Swift at need. It is not necessary to copy templates and snapshots from one zone to another, as would be required when using zone NFS alone. Everything is available everywhere Swift storage must be set up before you add NFS secondary storage to zones. This is accomplished through some additional configuration steps on a fresh Management Server installation, before you add the first zone. The procedure is described in Adding a Zone in the Advanced Installation Guide.
diff --git a/docs/en-US/vcenter-maintenance-mode.xml b/docs/en-US/vcenter-maintenance-mode.xml index 2ed71625def..d36dd7cdb44 100644 --- a/docs/en-US/vcenter-maintenance-mode.xml +++ b/docs/en-US/vcenter-maintenance-mode.xml @@ -33,8 +33,8 @@ First use vCenter to exit the vCenter maintenance mode. This makes the host ready for &PRODUCT; to reactivate it. - Then use &PRODUCT;'s administrator UI to cancel the &PRODUCT; maintenance mode. - When the host comes back online, the VMs that were migrated off of it are migrated back to it and new VMs can be added. + Then use &PRODUCT;'s administrator UI to cancel the &PRODUCT; maintenance mode + When the host comes back online, the VMs that were migrated off of it may be migrated back to it manually and new VMs can be added. diff --git a/docs/en-US/verifying-source.xml b/docs/en-US/verifying-source.xml new file mode 100644 index 00000000000..f8bd102379d --- /dev/null +++ b/docs/en-US/verifying-source.xml @@ -0,0 +1,82 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ Verifying the downloaded release + + There are a number of mechanisms to check the authenticity and validity of a + downloaded release. + +
+ Getting the KEYS + + To enable you to verify the GPG signature, you will need to download the + KEYS + file. + + + You next need to import those keys, which you can do by running the following command: + # gpg --import KEYS + +
+
+ GPG + + The &PRODUCT; project provides a detached GPG signature of the release. + To check the signature, run the following command: + $ gpg --verify apache-cloudstack-4.0.0-incubating-src.tar.bz2.asc + + + If the signature is valid you will see a line of output that contains 'Good signature'. + +
+
+ MD5 + + In addition to the cryptographic signature, &PRODUCT; has an MD5 checksum + that you can use to verify the download matches the release. + You can verify this hash by executing the following command: + $ gpg --print-md MD5 apache-cloudstack-4.0.0-incubating-src.tar.bz2 | diff - apache-cloudstack-4.0.0-incubating-src.tar.bz2.md5 + + + If this successfully completes you should see no output. If there is any output from them, + then there is a difference between the hash you generated locally and the hash that has been + pulled from the server. + +
+
+ SHA512 + + In addition to the MD5 hash, the &PRODUCT; project provides a SHA512 + cryptographic hash to aid in assurance of the validity of the downloaded + release. You can verify this hash by executing the following command: + $ gpg --print-md SHA512 apache-cloudstack-4.0.0-incubating-src.tar.bz2 | diff - apache-cloudstack-4.0.0-incubating-src.tar.bz2.sha + + + If this command successfully completes you should see no output. If there is any output from them, + then there is a difference between the hash you generated locally and the hash that has been + pulled from the server. + +
+
diff --git a/docs/en-US/vlan-allocation-eg.xml b/docs/en-US/vlan-allocation-eg.xml new file mode 100644 index 00000000000..3ffd1666730 --- /dev/null +++ b/docs/en-US/vlan-allocation-eg.xml @@ -0,0 +1,71 @@ + + +%BOOK_ENTITIES; +]> + +
+ VLAN Allocation Example + VLANs are required for public and guest traffic. The following is an example of a VLAN + allocation scheme: + + +
+ + VLAN IDs + Traffic type + Scope + + + + + less than 500 + Management traffic. Reserved for administrative purposes. + &PRODUCT; software can access this, hypervisors, system VMs. + + + 500-599 + VLAN carrying public traffic. + &PRODUCT; accounts. + + + 600-799 + VLANs carrying guest traffic. + &PRODUCT; accounts. Account-specific VLAN is chosen from this + pool. + + + 800-899 + VLANs carrying guest traffic. + &PRODUCT; accounts. Account-specific VLAN chosen by &PRODUCT; admin to assign + to that account. + + + 900-999 + VLAN carrying guest traffic + &PRODUCT; accounts. Can be scoped by project, domain, or all + accounts. + + + greater than 1000 + Reserved for future use + + + + + + diff --git a/docs/en-US/vm-lifecycle.xml b/docs/en-US/vm-lifecycle.xml index da526a5193b..15d9f7df590 100644 --- a/docs/en-US/vm-lifecycle.xml +++ b/docs/en-US/vm-lifecycle.xml @@ -29,7 +29,7 @@ - basic_deployment.png: Basic two-machine CloudStack deployment + basic-deployment.png: Basic two-machine &PRODUCT; deploymentOnce a virtual machine is destroyed, it cannot be recovered. All the resources used by the virtual machine will be reclaimed by the system. This includes the virtual machine’s IP address.A stop will attempt to gracefully shut down the operating system, which typically involves terminating all the running applications. If the operation system cannot be stopped, it will be forcefully terminated. This has the same effect as pulling the power cord to a physical machine. diff --git a/docs/en-US/vmware-install.xml b/docs/en-US/vmware-install.xml new file mode 100644 index 00000000000..736b122fd0f --- /dev/null +++ b/docs/en-US/vmware-install.xml @@ -0,0 +1,631 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ VMware vSphere Installation and Configuration + If you want to use the VMware vSphere hypervisor to run guest virtual machines, install vSphere on the host(s) in your cloud. + +
+ Preparation Checklist for VMware + For a smoother installation, gather the following information before you start: + + Information listed in + Information listed in + +
+ vCenter Checklist + You will need the following information about vCenter. + + + + + +
+ + vCenter Requirement + Value + Notes + + + + + vCenter User + + This user must have admin privileges. + + + vCenter User Password + + Password for the above user. + + + vCenter Datacenter Name + + Name of the datacenter. + + + vCenter Cluster Name + + Name of the cluster. + + + + + +
+ Networking Checklist for VMware + You will need the following information about VLAN. + + + + + +
+ + VLAN Information + Value + Notes + + + + + ESXi VLAN + + VLAN on which all your ESXi hypervisors reside. + + + ESXI VLAN IP Address + + IP Address Range in the ESXi VLAN. One address per Virtual Router is used from this range. + + + ESXi VLAN IP Gateway + + + + + ESXi VLAN Netmask + + + + + Management Server VLAN + + VLAN on which the &PRODUCT; Management server is installed. + + + Public VLAN + + VLAN for the Public Network. + + + Public VLAN Gateway + + + + + Public VLAN Netmask + + + + + Public VLAN IP Address Range + + Range of Public IP Addresses available for &PRODUCT; use. These addresses will be used for virtual router on &PRODUCT; to route private traffic to external networks. + + + VLAN Range for Customer use + + A contiguous range of non-routable VLANs. One VLAN will be assigned for each customer. + + + + + + +
+ vSphere Installation Steps + + If you haven't already, you'll need to download and purchase vSphere from the VMware Website (https://www.vmware.com/tryvmware/index.php?p=vmware-vsphere&lp=1) and install it by following the VMware vSphere Installation Guide. + + Following installation, perform the following configuration, which are described in the next few sections: + + + + +
+ + Required + Optional + + + + + ESXi host setup + NIC bonding + + + Configure host physical networking, virtual switch, vCenter Management Network, and extended port range + Multipath storage + + + Prepare storage for iSCSI + + + + Configure clusters in vCenter and add hosts to them, or add hosts without clusters to vCenter + + + + + + + + +
+ ESXi Host setup + All ESXi hosts should enable CPU hardware virtualization support in BIOS. Please note hardware virtualization support is not enabled by default on most servers. +
+
+ Physical Host Networking + You should have a plan for cabling the vSphere hosts. Proper network configuration is required before adding a vSphere host to &PRODUCT;. To configure an ESXi host, you can use vClient to add it as standalone host to vCenter first. Once you see the host appearing in the vCenter inventory tree, click the host node in the inventory tree, and navigate to the Configuration tab. + + + + + + vsphereclient.png: vSphere client + + + In the host configuration tab, click the "Hardware/Networking" link to bring up the networking configuration page as above. +
+ Configure Virtual Switch + A default virtual switch vSwitch0 is created. &PRODUCT; requires all ESXi hosts in the cloud to use the same set of virtual switch names. If you change the default virtual switch name, you will need to configure one or more &PRODUCT; configuration variables as well. +
+ Separating Traffic + &PRODUCT; allows you to use vCenter to configure three separate networks per ESXi host. These networks are identified by the name of the vSwitch they are connected to. The allowed networks for configuration are public (for traffic to/from the public internet), guest (for guest-guest traffic), and private (for management and usually storage traffic). You can use the default virtual switch for all three, or create one or two other vSwitches for those traffic types. + If you want to separate traffic in this way you should first create and configure vSwitches in vCenter according to the vCenter instructions. Take note of the vSwitch names you have used for each traffic type. You will configure &PRODUCT; to use these vSwitches. +
+
+ Increasing Ports + By default a virtual switch on ESXi hosts is created with 56 ports. We recommend setting it to 4088, the maximum number of ports allowed. To do that, click the "Properties..." link for virtual switch (note this is not the Properties link for Networking). + + + + + + vsphereclient.png: vSphere client + + + In vSwitch properties dialog, select the vSwitch and click Edit. You should see the following dialog: + + + + + + vsphereclient.png: vSphere client + + + In this dialog, you can change the number of switch ports. After you've done that, ESXi hosts are required to reboot in order for the setting to take effect. +
+
+
+ Configure vCenter Management Network + In the vSwitch properties dialog box, you may see a vCenter management network. This same network will also be used as the &PRODUCT; management network. &PRODUCT; requires the vCenter management network to be configured properly. Select the management network item in the dialog, then click Edit. + + + + + + vsphereclient.png: vSphere client + + + Make sure the following values are set: + + VLAN ID set to the desired ID + vMotion enabled. + Management traffic enabled. + + If the ESXi hosts have multiple VMKernel ports, and ESXi is not using the default value "Management Network" as the management network name, you must follow these guidelines to configure the management network port group so that &PRODUCT; can find it: + + Use one label for the management network port across all ESXi hosts. + In the &PRODUCT; UI, go to Configuration - Global Settings and set vmware.management.portgroup to the management network label from the ESXi hosts. + +
+
+ Extend Port Range for &PRODUCT; Console Proxy + (Applies only to VMware vSphere version 4.x) + You need to extend the range of firewall ports that the console proxy works with on the hosts. This is to enable the console proxy to work with VMware-based VMs. The default additional port range is 59000-60000. To extend the port range, log in to the VMware ESX service console on each host and run the following commands: + +esxcfg-firewall -o 59000-60000,tcp,in,vncextras +esxcfg-firewall -o 59000-60000,tcp,out,vncextras + +
+
+ Configure NIC Bonding for vSphere + NIC bonding on vSphere hosts may be done according to the vSphere installation guide. +
+
+ +
+ Storage Preparation for vSphere (iSCSI only) + Use of iSCSI requires preparatory work in vCenter. You must add an iSCSI target and create an iSCSI datastore. + If you are using NFS, skip this section. +
+ Enable iSCSI initiator for ESXi hosts + + + In vCenter, go to hosts and Clusters/Configuration, and click Storage Adapters link. You will see: + + + + + + vsphereclient.png: vSphere client + + + + + Select iSCSI software adapter and click Properties. + + + + + + vsphereclient.png: vSphere client + + + + + Click the Configure... button. + + + + + + vsphereclient.png: vSphere client + + + + Check Enabled to enable the initiator. + Click OK to save. + +
+
+ Add iSCSI target + Under the properties dialog, add the iSCSI target info: + + + + + + vsphereclient.png: vSphere client + + + Repeat these steps for all ESXi hosts in the cluster. +
+
+ Create an iSCSI datastore + You should now create a VMFS datastore. Follow these steps to do so: + + Select Home/Inventory/Datastores. + Right click on the datacenter node. + Choose Add Datastore... command. + Follow the wizard to create a iSCSI datastore. + + This procedure should be done on one host in the cluster. It is not necessary to do this on all hosts. + + + + + + vsphereclient.png: vSphere client + + +
+
+ Multipathing for vSphere (Optional) + Storage multipathing on vSphere nodes may be done according to the vSphere installation guide. +
+
+
+ Add Hosts or Configure Clusters (vSphere) + Use vCenter to create a vCenter cluster and add your desired hosts to the cluster. You will later add the entire cluster to &PRODUCT;. (see ). +
+ diff --git a/docs/en-US/vmware-requirements.xml b/docs/en-US/vmware-requirements.xml new file mode 100644 index 00000000000..207a4566de8 --- /dev/null +++ b/docs/en-US/vmware-requirements.xml @@ -0,0 +1,80 @@ + + +%BOOK_ENTITIES; +]> + + + +
+ System Requirements for vSphere Hosts +
+ Software requirements: + + + vSphere and vCenter, both version 4.1 or 5.0. + vSphere Standard is recommended. Note however that customers need to consider the CPU constraints in place with vSphere licensing. See http://www.vmware.com/files/pdf/vsphere_pricing.pdf and discuss with your VMware sales representative. + vCenter Server Standard is recommended. + + Be sure all the hotfixes provided by the hypervisor vendor are applied. Track the release of hypervisor patches through your hypervisor vendor's support channel, and apply patches as soon as possible after they are released. &PRODUCT; will not track or notify you of required hypervisor patches. It is essential that your hosts are completely up to date with the provided hypervisor patches. The hypervisor vendor is likely to refuse to support any system that is not up to date with patches. + + Apply All Necessary HotfixesThe lack of up-do-date hotfixes can lead to data corruption and lost VMs. +
+
+ Hardware requirements: + + The host must be certified as compatible with vSphere. See the VMware Hardware Compatibility Guide at http://www.vmware.com/resources/compatibility/search.php. + All hosts must be 64-bit and must support HVM (Intel-VT or AMD-V enabled). + All hosts within a cluster must be homogenous. That means the CPUs must be of the same type, count, and feature flags. + 64-bit x86 CPU (more cores results in better performance) + Hardware virtualization support required + 4 GB of memory + 36 GB of local disk + At least 1 NIC + Statically allocated IP Address + +
+
+ vCenter Server requirements: + + Processor - 2 CPUs 2.0GHz or higher Intel or AMD x86 processors. Processor requirements may be higher if the database runs on the same machine. + Memory - 3GB RAM. RAM requirements may be higher if your database runs on the same machine. + Disk storage - 2GB. Disk requirements may be higher if your database runs on the same machine. + Microsoft SQL Server 2005 Express disk requirements. The bundled database requires up to 2GB free disk space to decompress the installation archive. + Networking - 1Gbit or 10Gbit. + + For more information, see "vCenter Server and the vSphere Client Hardware Requirements" at http://pubs.vmware.com/vsp40/wwhelp/wwhimpl/js/html/wwhelp.htm#href=install/c_vc_hw.html. +
+
+ Other requirements: + + VMware vCenter Standard Edition 4.1 or 5.0 must be installed and available to manage the vSphere hosts. + vCenter must be configured to use the standard port 443 so that it can communicate with the &PRODUCT; Management Server. + You must re-install VMware ESXi if you are going to re-use a host from a previous install. + &PRODUCT; requires VMware vSphere 4.1 or 5.0. VMware vSphere 4.0 is not supported. + All hosts must be 64-bit and must support HVM (Intel-VT or AMD-V enabled). All hosts within a cluster must be homogenous. That means the CPUs must be of the same type, count, and feature flags. + The &PRODUCT; management network must not be configured as a separate virtual network. The &PRODUCT; management network is the same as the vCenter management network, and will inherit its configuration. See . + &PRODUCT; requires ESXi. ESX is not supported. + All resources used for &PRODUCT; must be used for &PRODUCT; only. &PRODUCT; cannot share instance of ESXi or storage with other management consoles. Do not share the same storage volumes that will be used by &PRODUCT; with a different set of ESXi servers that are not managed by &PRODUCT;. + Put all target ESXi hypervisors in a cluster in a separate Datacenter in vCenter. + The cluster that will be managed by &PRODUCT; should not contain any VMs. Do not run the management server, vCenter or any other VMs on the cluster that is designated for &PRODUCT; use. Create a separate cluster for use of &PRODUCT; and make sure that they are no VMs in this cluster. + All the required VLANS must be trunked into all network switches that are connected to the ESXi hypervisor hosts. These would include the VLANS for Management, Storage, vMotion, and guest VLANs. The guest VLAN (used in Advanced Networking; see Network Setup) is a contiguous range of VLANs that will be managed by &PRODUCT;. + +
+
diff --git a/docs/en-US/vmware-topology-req.xml b/docs/en-US/vmware-topology-req.xml new file mode 100644 index 00000000000..cf6ae4d455e --- /dev/null +++ b/docs/en-US/vmware-topology-req.xml @@ -0,0 +1,38 @@ + + +%BOOK_ENTITIES; +]> + +
+ VMware Topology Requirements + + + The Management Server and secondary storage VMs must be able to access vCenter and all + ESXi hosts in the zone. To allow the necessary access through the firewall, keep port 443 + open. + + + The Management Servers communicate with VMware vCenter servers on port 443 + (HTTPs). + + + The Management Servers communicate with the System VMs on port 3922 (ssh) on the + management traffic network. + + +
diff --git a/docs/en-US/volume-status.xml b/docs/en-US/volume-status.xml index c2e58a544c6..35802f98253 100644 --- a/docs/en-US/volume-status.xml +++ b/docs/en-US/volume-status.xml @@ -23,7 +23,14 @@ -->
- Volume Status - When a snapshot operation is triggered by means of a recurring snapshot policy, a snapshot is skipped if a volume has remained inactive since its last snapshot was taken. A volume is considered to be inactive if it is either detached or attached to a VM that is not running. &PRODUCT; ensures that at least one snapshot is taken since the volume last became inactive. - When a snapshot is taken manually, a snapshot is always created regardless of whether a volume has been active or not. + Volume Status + When a snapshot operation is triggered by means of a recurring snapshot + policy, a snapshot is skipped if a volume has remained inactive since its + last snapshot was taken. A volume is considered to be inactive if it is + either detached or attached to a VM that is not running. &PRODUCT; ensures + that at least one snapshot is taken since the volume last became inactive. + + When a snapshot is taken manually, a snapshot is always created + regardless of whether a volume has been active or not. +
diff --git a/docs/en-US/whats-new.xml b/docs/en-US/whats-new.xml index 44ec5183d6a..77b3ec3df22 100644 --- a/docs/en-US/whats-new.xml +++ b/docs/en-US/whats-new.xml @@ -22,13 +22,21 @@ under the License. --> -
- What's New in 3.0.x? - The following describes any new major features of each CloudPlatform version as it applies to API usage. - - - - - - -
+ + What's New in the API? + 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/en-US/windows-installation.xml b/docs/en-US/windows-installation.xml index 27f90f374d2..bcecc8071f6 100644 --- a/docs/en-US/windows-installation.xml +++ b/docs/en-US/windows-installation.xml @@ -23,7 +23,8 @@ -->
Windows OS Installation - Download the installer, CloudInstanceManager.msi, from the Download page and run the installer in - the newly created Windows VM. + Download the installer, CloudInstanceManager.msi, from + Download page + and run the installer in the newly created Windows VM. +
diff --git a/docs/en-US/work-with-usage.xml b/docs/en-US/work-with-usage.xml index 40130c88212..00a7fb5df81 100644 --- a/docs/en-US/work-with-usage.xml +++ b/docs/en-US/work-with-usage.xml @@ -21,6 +21,7 @@ specific language governing permissions and limitations under the License. --> + Working with Usage The Usage Server is an optional, separately-installed part of &PRODUCT; that provides aggregated usage records which you can use to create billing integration for &PRODUCT;. The Usage Server works by taking data from the events log and creating summary usage records that you can access using the listUsageRecords API call. diff --git a/docs/en-US/working-with-hosts.xml b/docs/en-US/working-with-hosts.xml index 9bb524dd74a..83cd8b2bdc6 100644 --- a/docs/en-US/working-with-hosts.xml +++ b/docs/en-US/working-with-hosts.xml @@ -26,7 +26,7 @@ Working With Hosts
Adding Hosts - Additional hosts can be added at any time to provide more capacity for guest VMs. For requirements and instructions, see the Installation Guide. + Additional hosts can be added at any time to provide more capacity for guest VMs. For requirements and instructions, see .
diff --git a/docs/en-US/working-with-snapshots.xml b/docs/en-US/working-with-snapshots.xml index 1d8dbd97369..82456dd6e9e 100644 --- a/docs/en-US/working-with-snapshots.xml +++ b/docs/en-US/working-with-snapshots.xml @@ -23,11 +23,9 @@ -->
Working with Snapshots - (Supported for the following hypervisors: XenServer, - VMware vSphere, and KVM) - &PRODUCT; supports snapshots of disk volumes. Snapshots are a point-in-time capture of virtual machine disks. Memory and CPU states are not captured. If you are using the Oracle VM hypervisor, you can not take snapshots, since OVM does not support them. - Snapshots may be taken for volumes, including both root and data disks (except when the Oracle VM hypervisor is used, which does not support snapshots). The administrator places a limit on the number of stored snapshots per user. Users can create new volumes from the snapshot for recovery of particular files and they can create templates from snapshots to boot from a restored disk. + (Supported for the following hypervisors: XenServer, VMware vSphere, and KVM) + &PRODUCT; supports snapshots of disk volumes. Snapshots are a point-in-time capture of virtual machine disks. Memory and CPU states are not captured. + Snapshots may be taken for volumes, including both root and data disks. The administrator places a limit on the number of stored snapshots per user. Users can create new volumes from the snapshot for recovery of particular files and they can create templates from snapshots to boot from a restored disk. Users can create snapshots manually or by setting up automatic recurring snapshot policies. Users can also create disk volumes from snapshots, which may be attached to a VM like any other disk volume. Snapshots of both root disks and data disks are supported. However, &PRODUCT; does not currently support booting a VM from a recovered root disk. A disk recovered from snapshot of a root disk is treated as a regular data disk; the data on recovered disk can be accessed by attaching the disk to a VM. A completed snapshot is copied from primary storage to secondary storage, where it is stored until deleted or purged by newer snapshot. diff --git a/docs/en-US/working-with-usage-data.xml b/docs/en-US/working-with-usage-data.xml index 95d83640e34..56a929fd6c1 100644 --- a/docs/en-US/working-with-usage-data.xml +++ b/docs/en-US/working-with-usage-data.xml @@ -22,7 +22,7 @@ under the License. --> -
+ Working With Usage Data The Usage Server provides aggregated usage records which you can use to create billing integration for the &PRODUCT; platform. The Usage Server works by taking data from the events log and creating summary usage records that you can access using the listUsageRecords API call. The usage records show the amount of resources, such as VM run time or template storage space, consumed by guest instances. In the special case of bare metal instances, no template storage resources are consumed, but records showing zero usage are still included in the Usage Server's output. @@ -31,4 +31,4 @@ -
+ diff --git a/docs/en-US/working-with-volumes.xml b/docs/en-US/working-with-volumes.xml index 1a9d297265a..ab567d2d0ca 100644 --- a/docs/en-US/working-with-volumes.xml +++ b/docs/en-US/working-with-volumes.xml @@ -23,16 +23,27 @@ -->
- Working With Volumes - A volume provides storage to a guest VM. The volume can provide for a root disk or an additional data disk. &PRODUCT; supports additional volumes for guest VMs. - Volumes are created for a specific hypervisor type. A volume that has been attached to guest using one hypervisor type (e.g, XenServer) may not be attached to a guest that is using another hypervisor type (e.g. vSphere, Oracle VM, KVM). This is because the different hypervisors use different disk image formats. - &PRODUCT; defines a volume as a unit of storage available to a guest VM. Volumes are either root disks or data disks. The root disk has “/†in the file system and is usually the boot device. Data disks provide for additional storage (e.g. As “/opt†or “D:â€). Every guest VM has a root disk, and VMs can also optionally have a data disk. End users can mount multiple data disks to guest VMs. Users choose data disks from the disk offerings created by administrators. The user can create a template from a volume as well; this is the standard procedure for private template creation. Volumes are hypervisor-specific: a volume from one hypervisor type may not be used on a guest of another hypervisor type. - - - - - - - + Using Swift for Secondary Storage + A volume provides storage to a guest VM. The volume can provide for + a root disk or an additional data disk. &PRODUCT; supports additional + volumes for guest VMs. + + Volumes are created for a specific hypervisor type. A volume that has + been attached to guest using one hypervisor type (e.g, XenServer) may not + be attached to a guest that is using another hypervisor type (e.g. + vSphere, KVM). This is because the different hypervisors use + different disk image formats. + + &PRODUCT; defines a volume as a unit of storage available to a guest + VM. Volumes are either root disks or data disks. The root disk has "/" + in the file system and is usually the boot device. Data disks provide + for additional storage (e.g. As "/opt" or "D:"). Every guest VM has a root + disk, and VMs can also optionally have a data disk. End users can mount + multiple data disks to guest VMs. Users choose data disks from the disk + offerings created by administrators. The user can create a template from + a volume as well; this is the standard procedure for private template + creation. Volumes are hypervisor-specific: a volume from one hypervisor + type may not be used on a guest of another hypervisor type. +
diff --git a/docs/en-US/xenserver-topology-req.xml b/docs/en-US/xenserver-topology-req.xml new file mode 100644 index 00000000000..12b9b077fe7 --- /dev/null +++ b/docs/en-US/xenserver-topology-req.xml @@ -0,0 +1,24 @@ + + +%BOOK_ENTITIES; +]> + +
+ XenServer Topology Requirements + The Management Servers communicate with XenServer hosts on ports 22 (ssh), 80 (HTTP), and 443 (HTTPs). +
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/docs/publican-release-notes.cfg b/docs/publican-release-notes.cfg index cabf1ea3c88..b6af40663bc 100644 --- a/docs/publican-release-notes.cfg +++ b/docs/publican-release-notes.cfg @@ -20,7 +20,7 @@ xml_lang: en-US type: Book -docname: release-notes +docname: Release_Notes brand: cloudstack chunk_first: 0 chunk_section_depth: 0 diff --git a/packaging/centos63/cloud-agent.rc b/packaging/centos63/cloud-agent.rc new file mode 100755 index 00000000000..084b71543a8 --- /dev/null +++ b/packaging/centos63/cloud-agent.rc @@ -0,0 +1,121 @@ +#!/bin/bash + +# chkconfig: 35 99 10 +# description: Cloud Agent + +# 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. + +# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well + +. /etc/rc.d/init.d/functions + +whatami=cloud-agent + +# set environment variables + +SHORTNAME="$whatami" +PIDFILE=/var/run/"$whatami".pid +LOCKFILE=/var/lock/subsys/"$SHORTNAME" +LOGFILE=/var/log/cloud/agent/agent.log +PROGNAME="Cloud Agent" +CLASS="com.cloud.agent.AgentShell" +JSVC=`which jsvc 2>/dev/null`; + +# exit if we don't find jsvc +if [ -z "$JSVC" ]; then + echo no jsvc found in path; + exit 1; +fi + +unset OPTIONS +[ -r /etc/sysconfig/"$SHORTNAME" ] && source /etc/sysconfig/"$SHORTNAME" + +# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT) +JDK_DIRS="/usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm" + +for jdir in $JDK_DIRS; do + if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then + JAVA_HOME="$jdir" + fi +done +export JAVA_HOME + +SCP="" +DCP="" +ACP=`ls /usr/share/cloud/java/* | tr '\n' ':'` +JCP="/usr/share/java/commons-daemon.jar" + +# We need to append the JSVC daemon JAR to the classpath +# AgentShell implements the JSVC daemon methods +export CLASSPATH="$SCP:$DCP:$ACP:$JCP:/etc/cloud/agent:/usr/lib64/cloud/agent" + +start() { + echo -n $"Starting $PROGNAME: " + if hostname --fqdn >/dev/null 2>&1 ; then + $JSVC -cp "$CLASSPATH" -pidfile "$PIDFILE" $CLASS + RETVAL=$? + echo + else + failure + echo + echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr + RETVAL=9 + fi + [ $RETVAL = 0 ] && touch ${LOCKFILE} + return $RETVAL +} + +stop() { + echo -n $"Stopping $PROGNAME: " + $JSVC -pidfile "$PIDFILE" -stop $CLASS + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE} +} + + +# See how we were called. +case "$1" in + start) + start + ;; + stop) + stop + ;; + status) + status -p ${PIDFILE} $SHORTNAME + RETVAL=$? + ;; + restart) + stop + sleep 3 + start + ;; + condrestart) + if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then + stop + sleep 3 + start + fi + ;; + *) + echo $"Usage: $whatami {start|stop|restart|condrestart|status|help}" + RETVAL=3 +esac + +exit $RETVAL diff --git a/packaging/centos63/cloud-ipallocator.rc b/packaging/centos63/cloud-ipallocator.rc new file mode 100755 index 00000000000..ffeffa342c8 --- /dev/null +++ b/packaging/centos63/cloud-ipallocator.rc @@ -0,0 +1,98 @@ +#!/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. + +# chkconfig: 35 99 10 +# description: Cloud Agent + +# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well + +. /etc/rc.d/init.d/functions + +whatami=cloud-external-ipallocator + +# set environment variables + +SHORTNAME="$whatami" +PIDFILE=/var/run/"$whatami".pid +LOCKFILE=/var/lock/subsys/"$SHORTNAME" +LOGFILE=/var/log/cloud/ipallocator/ipallocator.log +PROGNAME="External IPAllocator" + +unset OPTIONS +[ -r /etc/sysconfig/"$SHORTNAME" ] && source /etc/sysconfig/"$SHORTNAME" +DAEMONIZE=/usr/bin/cloud-daemonize +PROG=/usr/bin/cloud-external-ipallocator.py +OPTIONS=8083 + +start() { + echo -n $"Starting $PROGNAME: " + if hostname --fqdn >/dev/null 2>&1 ; then + daemon --check=$SHORTNAME --pidfile=${PIDFILE} "$DAEMONIZE" \ + -n "$SHORTNAME" -p "$PIDFILE" -l "$LOGFILE" "$PROG" $OPTIONS + RETVAL=$? + echo + else + failure + echo + echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr + RETVAL=9 + fi + [ $RETVAL = 0 ] && touch ${LOCKFILE} + return $RETVAL +} + +stop() { + echo -n $"Stopping $PROGNAME: " + killproc -p ${PIDFILE} $SHORTNAME # -d 10 $SHORTNAME + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE} +} + + +# See how we were called. +case "$1" in + start) + start + ;; + stop) + stop + ;; + status) + status -p ${PIDFILE} $SHORTNAME + RETVAL=$? + ;; + restart) + stop + sleep 3 + start + ;; + condrestart) + if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then + stop + sleep 3 + start + fi + ;; + *) + echo $"Usage: $whatami {start|stop|restart|condrestart|status|help}" + RETVAL=3 +esac + +exit $RETVAL + diff --git a/packaging/centos63/cloud-management.rc b/packaging/centos63/cloud-management.rc new file mode 100755 index 00000000000..48c2ab44a62 --- /dev/null +++ b/packaging/centos63/cloud-management.rc @@ -0,0 +1,107 @@ +#!/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. +# +# cloud-management This shell script takes care of starting and stopping Tomcat +# +# chkconfig: - 80 20 +# +### BEGIN INIT INFO +# Provides: tomcat6 +# Required-Start: $network $syslog +# Required-Stop: $network $syslog +# Default-Start: +# Default-Stop: +# Description: Release implementation for Servlet 2.5 and JSP 2.1 +# Short-Description: start and stop tomcat +### END INIT INFO +# +# - originally written by Henri Gomez, Keith Irwin, and Nicolas Mailhot +# - heavily rewritten by Deepak Bhole and Jason Corley +# + +if [ -r /etc/rc.d/init.d/functions ]; then + . /etc/rc.d/init.d/functions +fi +if [ -r /lib/lsb/init-functions ]; then + . /lib/lsb/init-functions +fi + + +NAME="$(basename $0)" +stop() { + SHUTDOWN_WAIT="30" + count="0" + if [ -f /var/run/cloud-management.pid ]; then + pid=`cat /var/run/cloud-management.pid` + kill $pid &>/dev/null + until [ "$(ps --pid $pid | grep -c $pid)" -eq "0" ] || \ + [ "$count" -gt "$SHUTDOWN_WAIT" ] + do + sleep 1 + let count="${count}+1" + done + if [ "$(ps --pid $pid | grep -c $pid)" -eq "0" ]; then + log_success_msg "Stopping cloud-management:" + else + log_failure_msg "Stopping cloud-management:" + fi + else + echo "Cannot find PID file of Cloud-management" + log_failure_msg "Stopping cloud-management:" + fi +} + +set_ulimit() { + fd_limit=`ulimit -n` + if [ "$fd_limit" != "4096" ]; then + user=`whoami` + if [ $user == "root" ]; then + ulimit -n 4096 + fi + fi +} + +handle_pid_file() { + if [ "$1" -ne 0 ] ; then + echo "The pid file locates at /var/run/cloud-management.pid and lock file at /var/lock/subsys/cloud-management. + Starting cloud-management will take care of them or you can manually clean up." + fi +} + +# See how we were called. +case "$1" in + status) + status ${NAME} + RETVAL=$? + handle_pid_file $RETVAL + ;; + stop) + stop + ;; + restart) + stop + set start + set_ulimit + . /etc/rc.d/init.d/tomcat6 + ;; + *) + set_ulimit + . /etc/rc.d/init.d/tomcat6 +esac + +exit $RETVAL diff --git a/tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces b/packaging/centos63/cloud-management.sysconfig similarity index 73% rename from tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces rename to packaging/centos63/cloud-management.sysconfig index f65507911ab..15df8cdab92 100644 --- a/tools/devcloud/basebuild/puppet-devcloudinitial/files/interfaces +++ b/packaging/centos63/cloud-management.sysconfig @@ -15,19 +15,9 @@ # specific language governing permissions and limitations # under the License. -# The loopback network interface -auto lo -iface lo inet loopback +# This file is loaded in /etc/init.d/vmopsmanagement +# ATM we only do two things here: -# 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 +dummy=1 ; export TOMCAT_CFG=/etc/cloud/management/tomcat6.conf ; . /etc/cloud/management/tomcat6.conf +#-------------------------- diff --git a/packaging/centos63/cloud.spec b/packaging/centos63/cloud.spec new file mode 100644 index 00000000000..d828e673c97 --- /dev/null +++ b/packaging/centos63/cloud.spec @@ -0,0 +1,312 @@ +# 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. + +%define __os_install_post %{nil} +%global debug_package %{nil} + +# DISABLE the post-percentinstall java repacking and line number stripping +# we need to find a way to just disable the java repacking and line number stripping, but not the autodeps + +Name: cloud +Summary: CloudStack IaaS Platform +#http://fedoraproject.org/wiki/PackageNamingGuidelines#Pre-Release_packages +%if "%{?_prerelease}" != "" +%define _maventag %{_ver}-SNAPSHOT +Release: %{_rel}%{dist} +%else +%define _maventag %{_ver} +Release: %{_rel}%{dist} +%endif +Version: %{_ver} +License: ASL 2.0 +Vendor: Apache CloudStack +Packager: Apache CloudStack +Group: System Environment/Libraries +# FIXME do groups for every single one of the subpackages +Source0: %{name}-%{_maventag}.tgz +BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build + +BuildRequires: java-1.6.0-openjdk-devel +BuildRequires: tomcat6 +BuildRequires: ws-commons-util +BuildRequires: jpackage-utils +BuildRequires: gcc +BuildRequires: glibc-devel +BuildRequires: /usr/bin/mkisofs +BuildRequires: MySQL-python +#BuildRequires: maven => 3.0.0 + +%description +CloudStack is a highly-scalable elastic, open source, +intelligent IaaS cloud implementation. + +%package management-server +Summary: CloudStack management server UI +Requires: tomcat6 +Requires: java >= 1.6.0 +Requires: python +Requires: bash +Requires: bzip2 +Requires: gzip +Requires: unzip +Requires: /sbin/mount.nfs +Requires: openssh-clients +Requires: nfs-utils +Requires: wget +Requires: mysql-connector-java +Requires: ws-commons-util +Requires: jpackage-utils +Requires: sudo +Requires: /sbin/service +Requires: /sbin/chkconfig +Requires: /usr/bin/ssh-keygen +Requires: mkisofs +Requires: MySQL-python +Requires: python-paramiko +Requires: ipmitool +Requires: %{name}-setup = %{_ver} +Group: System Environment/Libraries +%description management-server +The CloudStack management server is the central point of coordination, +management, and intelligence in CloudStack. + +%package setup +Summary: CloudStack database setup scripts +Requires: java >= 1.6.0 +Requires: python +Requires: MySQL-python +Requires: %{name}-python = %{_ver} +Group: System Environment/Libraries +%description setup +The scripts and commands used to setup and configure the database + +%package python +Summary: CloudStack Python library +# FIXME nuke the archdependency +Requires: python +Group: System Environment/Libraries +%description python +The CloudStack Python library contains a few Python modules that the +CloudStack uses. + +%package agent +Summary: CloudStack Agent for KVM hypervisors +Requires: java >= 1.6.0 +Requires: %{name}-python = %{_ver} +Requires: libvirt +Requires: bridge-utils +Requires: ebtables +Requires: jsvc +Requires: jna +Group: System Environment/Libraries +%description agent +The CloudStack agent for KVM hypervisors + +%prep +echo Doing CloudStack build + +%setup -q -n %{name}-%{_maventag} + +%build + +# this fixes the /usr/com bug on centos5 +%define _localstatedir /var +%define _sharedstatedir /var/lib +cp packaging/centos63/replace.properties build/replace.properties +echo VERSION=%{_maventag} >> build/replace.properties +echo PACKAGE=%{name} >> build/replace.properties +mvn package -Dsystemvm + +%install +[ ${RPM_BUILD_ROOT} != "/" ] && rm -rf ${RPM_BUILD_ROOT} +mkdir -p ${RPM_BUILD_ROOT}%{_bindir} +mkdir -p ${RPM_BUILD_ROOT}%{_datadir}/%{name}/setup +mkdir -p ${RPM_BUILD_ROOT}/usr/share/%{name}/management/ +ln -sf /usr/share/tomcat6/bin ${RPM_BUILD_ROOT}/usr/share/%{name}/management/bin +ln -sf /etc/cloud/management ${RPM_BUILD_ROOT}/usr/share/%{name}/management/conf +ln -sf /usr/share/tomcat6/lib ${RPM_BUILD_ROOT}/usr/share/%{name}/management/lib +ln -sf /var/log/cloud/management ${RPM_BUILD_ROOT}/usr/share/%{name}/management/logs +ln -sf /var/cache/cloud/management/temp ${RPM_BUILD_ROOT}/usr/share/%{name}/management/temp +ln -sf /var/cache/cloud/management/work ${RPM_BUILD_ROOT}/usr/share/%{name}/management/work +mkdir -p ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client +mkdir -p ${RPM_BUILD_ROOT}/var/log/%{name}/management +mkdir -p ${RPM_BUILD_ROOT}/var/log/%{name}/agent +mkdir -p ${RPM_BUILD_ROOT}/var/log/%{name}/awsapi +mkdir -p ${RPM_BUILD_ROOT}/var/log/%{name}/ipallocator +mkdir -p ${RPM_BUILD_ROOT}/var/cache/%{name}/management/work +mkdir -p ${RPM_BUILD_ROOT}/var/cache/%{name}/management/temp +mkdir -p ${RPM_BUILD_ROOT}/var/lib/%{name}/mnt +mkdir -p ${RPM_BUILD_ROOT}/var/lib/%{name}/management +mkdir -p ${RPM_BUILD_ROOT}/etc/%{name}/management +mkdir -p ${RPM_BUILD_ROOT}/etc/%{name}/management/Catalina/localhost/client +mkdir -p ${RPM_BUILD_ROOT}/etc/rc.d/init.d +mkdir -p ${RPM_BUILD_ROOT}/etc/sysconfig +mkdir -p ${RPM_BUILD_ROOT}/etc/%{name}/management/Catalina/localhost/client + +install -D client/target/utilities/bin/* ${RPM_BUILD_ROOT}%{_bindir} +install -D console-proxy/dist/systemvm.iso ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/vms/systemvm.iso +install -D console-proxy/dist/systemvm.zip ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/vms/systemvm.zip + +cp -r client/target/utilities/scripts/db/* ${RPM_BUILD_ROOT}%{_datadir}/%{name}/setup +cp -r client/target/cloud-client-ui-4.1.0-SNAPSHOT/* ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client + +for name in db.properties log4j-cloud.xml tomcat6-nonssl.conf tomcat6-ssl.conf server-ssl.xml server-nonssl.xml \ + catalina.policy catalina.properties db-enc.properties classpath.conf tomcat-users.xml web.xml ; do + mv ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/$name \ + ${RPM_BUILD_ROOT}/etc/%{name}/management/$name +done +mv ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/context.xml \ + ${RPM_BUILD_ROOT}/etc/%{name}/management/Catalina/localhost/client + +mkdir -p ${RPM_BUILD_ROOT}/usr/lib/python2.6/site-packages/ +cp -r python/lib/cloudutils ${RPM_BUILD_ROOT}/usr/lib/python2.6/site-packages/ +cp -r cloud-cli/cloudtool ${RPM_BUILD_ROOT}/usr/lib/python2.6/site-packages/ +install python/lib/cloud_utils.py ${RPM_BUILD_ROOT}/usr/lib/python2.6/site-packages/cloud_utils.py +install cloud-cli/cloudapis/cloud.py ${RPM_BUILD_ROOT}/usr/lib/python2.6/site-packages/cloudapis.py +install python/bindir/cloud-external-ipallocator.py ${RPM_BUILD_ROOT}%{_bindir}/ +install -D client/target/pythonlibs/jasypt-1.9.0.jar ${RPM_BUILD_ROOT}%{_javadir}/jasypt-1.9.0.jar +install -D client/target/pythonlibs/jasypt-1.8.jar ${RPM_BUILD_ROOT}%{_javadir}/jasypt-1.8.jar + +install -D packaging/centos63/cloud-ipallocator.rc ${RPM_BUILD_ROOT}/etc/rc.d/init.d/%{name}-ipallocator +install -D packaging/centos63/cloud-management.rc ${RPM_BUILD_ROOT}/etc/rc.d/init.d/%{name}-management +install -D packaging/centos63/cloud-management.sysconfig ${RPM_BUILD_ROOT}/etc/sysconfig/%{name}-management + +chmod 770 ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/Catalina +chmod 770 ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/Catalina/localhost +chmod 770 ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/Catalina/localhost/client +chmod 770 ${RPM_BUILD_ROOT}%{_sharedstatedir}/%{name}/mnt +chmod 770 ${RPM_BUILD_ROOT}%{_sharedstatedir}/%{name}/management +chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/cache/%{name}/management/work +chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/cache/%{name}/management/temp +chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/management +chmod 770 ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/agent +chmod -R ugo+x ${RPM_BUILD_ROOT}/usr/share/%{name}/management/webapps/client/WEB-INF/classes/scripts + +mkdir -p ${RPM_BUILD_ROOT}/etc/cloud/agent +mkdir -p ${RPM_BUILD_ROOT}/var/log/cloud/agent +install -D packaging/centos63/cloud-agent.rc ${RPM_BUILD_ROOT}/etc/init.d/%{name}-agent +install -D agent/target/transformed/agent.properties ${RPM_BUILD_ROOT}/etc/cloud/agent/agent.properties +install -D agent/target/transformed/environment.properties ${RPM_BUILD_ROOT}/etc/cloud/agent/environment.properties +install -D agent/target/transformed/log4j-cloud.xml ${RPM_BUILD_ROOT}/etc/cloud/agent/log4j-cloud.xml +install -D agent/target/transformed/cloud-setup-agent ${RPM_BUILD_ROOT}/usr/bin/cloud-setup-agent +install -D agent/target/transformed/cloud-ssh ${RPM_BUILD_ROOT}/usr/bin/cloud-ssh + +install -D plugins/hypervisors/kvm/target/%{name}-plugin-hypervisor-kvm-%{_maventag}.jar ${RPM_BUILD_ROOT}/usr/share/cloud/java/%{name}-plugin-hypervisor-kvm-%{_maventag}.jar +cp plugins/hypervisors/kvm/target/dependencies/* ${RPM_BUILD_ROOT}/usr/share/cloud/java +mkdir -p ${RPM_BUILD_ROOT}/usr/share/cloud/scripts +cp -r scripts/* ${RPM_BUILD_ROOT}/usr/share/cloud/scripts + +%clean +[ ${RPM_BUILD_ROOT} != "/" ] && rm -rf ${RPM_BUILD_ROOT} + + +%preun management-server +/sbin/service %{name}-management stop || true +if [ "$1" == "0" ] ; then + /sbin/chkconfig --del %{name}-management > /dev/null 2>&1 || true + /sbin/service %{name}-management stop > /dev/null 2>&1 || true +fi + +%pre management-server +id %{name} > /dev/null 2>&1 || /usr/sbin/useradd -M -c "CloudStack unprivileged user" \ + -r -s /bin/sh -d %{_sharedstatedir}/%{name}/management %{name}|| true + +# set max file descriptors for cloud user to 4096 +sed -i /"cloud hard nofile"/d /etc/security/limits.conf +sed -i /"cloud soft nofile"/d /etc/security/limits.conf +echo "cloud hard nofile 4096" >> /etc/security/limits.conf +echo "cloud soft nofile 4096" >> /etc/security/limits.conf +rm -rf %{_localstatedir}/cache/%{name} +# user harcoded here, also hardcoded on wscript + +%post management-server +if [ "$1" == "1" ] ; then + /sbin/chkconfig --add %{name}-management > /dev/null 2>&1 || true + /sbin/chkconfig --level 345 %{name}-management on > /dev/null 2>&1 || true +fi + +if [ ! -f %{_datadir}/%{name}/management/webapps/client/WEB-INF/classes/scripts/scripts/vm/hypervisor/xenserver/vhd-util ] ; then + echo Please download vhd-util from http://download.cloud.com.s3.amazonaws.com/tools/vhd-util and put it in + echo %{_datadir}/%{name}/management/webapps/client/WEB-INF/classes/scripts/vm/hypervisor/xenserver/ +fi + +#No default permission as the permission setup is complex +%files management-server +%defattr(-,root,root,-) +%doc LICENSE +%doc NOTICE +%dir %attr(0770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina +%dir %attr(0770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina/localhost +%dir %attr(0770,root,%{name}) %{_sysconfdir}/%{name}/management/Catalina/localhost/client +%dir %{_datadir}/%{name}/management +%dir %attr(0770,root,%{name}) %{_sharedstatedir}/%{name}/mnt +%dir %attr(0770,%{name},%{name}) %{_sharedstatedir}/%{name}/management +%dir %attr(0770,root,%{name}) %{_localstatedir}/cache/%{name}/management +%dir %attr(0770,root,%{name}) %{_localstatedir}/cache/%{name}/management/work +%dir %attr(0770,root,%{name}) %{_localstatedir}/cache/%{name}/management/temp +%dir %attr(0770,root,%{name}) %{_localstatedir}/log/%{name}/management +%dir %attr(0770,root,%{name}) %{_localstatedir}/log/%{name}/agent +%config(noreplace) %{_sysconfdir}/sysconfig/%{name}-management +%config(noreplace) %{_sysconfdir}/%{name}/management +%config(noreplace) %attr(0640,root,%{name}) %{_sysconfdir}/%{name}/management/db.properties +%config(noreplace) %{_sysconfdir}/%{name}/management/log4j-%{name}.xml +%config(noreplace) %{_sysconfdir}/%{name}/management/tomcat6-nonssl.conf +%config(noreplace) %{_sysconfdir}/%{name}/management/tomcat6-ssl.conf +%attr(0755,root,root) %{_initrddir}/%{name}-management +%attr(0755,root,root) %{_bindir}/%{name}-setup-management +%attr(0755,root,root) %{_bindir}/%{name}-update-xenserver-licenses +%{_datadir}/%{name}/management/* + +%files setup +%attr(0755,root,root) %{_bindir}/%{name}-setup-databases +%attr(0755,root,root) %{_bindir}/%{name}-migrate-databases +%attr(0755,root,root) %{_bindir}/%{name}-set-guest-password +%attr(0755,root,root) %{_bindir}/%{name}-set-guest-sshkey +%attr(0755,root,root) %{_bindir}/%{name}-sysvmadm +%attr(0755,root,root) %{_bindir}/%{name}-setup-encryption +%dir %{_datadir}/%{name}/setup +%{_datadir}/%{name}/setup/*.sql +%{_datadir}/%{name}/setup/db/*.sql +%{_datadir}/%{name}/setup/*.sh +%{_datadir}/%{name}/setup/server-setup.xml +%{_javadir}/jasypt-1.9.0.jar +%{_javadir}/jasypt-1.8.jar +%doc LICENSE +%doc NOTICE + +%files python +%defattr(0644,root,root,0755) +%{_prefix}/lib*/python*/site-packages/%{name}* +%attr(0755,root,root) %{_bindir}/cloud-external-ipallocator.py +%attr(0755,root,root) %{_initrddir}/cloud-ipallocator +%dir %attr(0770,root,root) %{_localstatedir}/log/%{name}/ipallocator +%doc LICENSE +%doc NOTICE + +%files agent +%attr(0755,root,root) %{_bindir}/%{name}-setup-agent +%attr(0755,root,root) %{_bindir}/%{name}-ssh +%attr(0755,root,root) %{_sysconfdir}/init.d/cloud-agent +%config(noreplace) %{_sysconfdir}/cloud/agent +%dir /var/log/cloud/agent +%attr(0644,root,root) /usr/share/cloud/java/*.jar +%attr(0755,root,root) /usr/share/cloud/scripts + +%changelog +* Fri Oct 03 2012 Hugo Trippaers 4.1.0 +- new style spec file + diff --git a/packaging/centos63/package.sh b/packaging/centos63/package.sh new file mode 100644 index 00000000000..83c0e5eda4c --- /dev/null +++ b/packaging/centos63/package.sh @@ -0,0 +1,45 @@ +#!/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. + +CWD=`pwd` +RPMDIR=$CWD/../../dist/rpmbuild + + + +VERSION=`(cd ../../; mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate -Dexpression=project.version) | grep -v '^\['` +if echo $VERSION | grep SNAPSHOT ; then + REALVER=`echo $VERSION | cut -d '-' -f 1` + DEFVER="-D_ver $REALVER" + DEFPRE="-D_prerelease 1" + DEFREL="-D_rel SNAPSHOT" +else + DEFVER="-D_ver $REALVER" + DEFPRE= + DEFREL= +fi + +mkdir -p $RPMDIR/SPECS +mkdir -p $RPMDIR/SOURCES/cloud-$VERSION + + +(cd ../../; tar -c --exclude .git --exclude dist . | tar -C $RPMDIR/SOURCES/cloud-$VERSION -x ) +(cd $RPMDIR/SOURCES/; tar -czf cloud-$VERSION.tgz cloud-$VERSION) + +cp cloud.spec $RPMDIR/SPECS + +(cd $RPMDIR; rpmbuild -ba SPECS/cloud.spec "-D_topdir $RPMDIR" "$DEFVER" "$DEFREL" "$DEFPRE" ) diff --git a/packaging/centos63/replace.properties b/packaging/centos63/replace.properties new file mode 100644 index 00000000000..e6efc76278c --- /dev/null +++ b/packaging/centos63/replace.properties @@ -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. + +DBUSER=cloud +DBPW=cloud +DBROOTPW= +MSLOG=vmops.log +APISERVERLOG=api.log +DBHOST=localhost +MSMNTDIR=/mnt +COMPONENTS-SPEC=components-premium.xml +AWSAPILOG=awsapi.log +REMOTEHOST=localhost +AGENTCLASSPATH= +AGENTLOG=/var/log/cloud/agent/agent.log +AGENTLOGDIR=/var/log/cloud/agent/ +AGENTSYSCONFDIR=/etc/cloud/agent +APISERVERLOG=/var/log/cloud/management/apilog.log +AWSAPILOG=/var/log/cloud/awsapi/awsapi.log +BINDIR=/usr/bin +COMMONLIBDIR=/usr/share/java +CONFIGUREVARS= +DEPSCLASSPATH= +DOCDIR= +IPALOCATORLOG=/var/log/cloud/management/ipallocator.log +JAVADIR=/usr/share/java +LIBEXECDIR=/usr/libexec +LOCKDIR=/var/lock +MSCLASSPATH= +MSCONF=/etc/cloud/management +MSENVIRON=/usr/share/cloud/management +MSLOG=/var/log/cloud/management/management-server.log +MSLOGDIR=/var/log/cloud/management/ +MSMNTDIR=/var/lib/cloud/mnt +MSUSER=cloud +PIDDIR=/var/run +PLUGINJAVADIR= +PREMIUMJAVADIR= +PYTHONDIR=/usr/lib/python2.6/site-packages/ +SERVERSYSCONFDIR=/etc/sysconfig +SETUPDATADIR=/usr/share/cloud/setup +SYSCONFDIR=/etc/sysconfig +SYSTEMCLASSPATH= +SYSTEMJARS= +USAGECLASSPATH= +USAGELOG=/var/log/cloud/usage +USAGESYSCONFDIR=/etc/sysconfig diff --git a/packaging/debian/replace.properties b/packaging/debian/replace.properties new file mode 100644 index 00000000000..6520f63e682 --- /dev/null +++ b/packaging/debian/replace.properties @@ -0,0 +1,62 @@ +# 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. + +DBUSER=cloud +DBPW=cloud +DBROOTPW= +MSLOG=vmops.log +APISERVERLOG=api.log +DBHOST=localhost +MSMNTDIR=/mnt +COMPONENTS-SPEC=components-premium.xml +AWSAPILOG=awsapi.log +REMOTEHOST=localhost +AGENTCLASSPATH= +AGENTLOG=/var/log/cloud/agent/agent.log +AGENTLOGDIR=/var/log/cloud/agent/ +AGENTSYSCONFDIR=/etc/cloud/agent +APISERVERLOG=/var/log/cloud/management/apilog.log +AWSAPILOG=/var/log/cloud/awsapi/awsapi.log +BINDIR=/usr/bin +COMMONLIBDIR=/usr/share/java +CONFIGUREVARS= +DEPSCLASSPATH= +DOCDIR= +IPALOCATORLOG=/var/log/cloud/management/ipallocator.log +JAVADIR=/usr/share/java +LIBEXECDIR=/usr/libexec +LOCKDIR=/var/lock +MSCLASSPATH= +MSCONF=/etc/cloud/management +MSENVIRON=/usr/share/cloud/management +MSLOG=/var/log/cloud/management/management-server.log +MSLOGDIR=/var/log/cloud/management/ +MSMNTDIR=/var/lib/cloud/mnt +MSUSER=cloud +PIDDIR=/var/run +PLUGINJAVADIR= +PREMIUMJAVADIR= +PYTHONDIR=/usr/lib/python2.6/site-packages/ +SERVERSYSCONFDIR=/etc/cloud/server +SETUPDATADIR=/usr/share/cloud/setup +SYSCONFDIR=/etc +SYSTEMCLASSPATH= +SYSTEMJARS= +USAGECLASSPATH= +USAGELOG=/var/log/cloud/usage +USAGESYSCONFDIR=/etc/cloud/usage +PACKAGE=cloud diff --git a/patches/pom.xml b/patches/pom.xml index d8267619153..a662bcb9791 100644 --- a/patches/pom.xml +++ b/patches/pom.xml @@ -1,88 +1,74 @@ - - + + 4.0.0 cloud-patches Apache CloudStack SystemVM Patches + pom org.apache.cloudstack cloudstack 4.1.0-SNAPSHOT - - - log4j - log4j - ${cs.log4j.version} - - - com.google.code.gson - gson - ${cs.gson.version} - - - commons-codec - commons-codec - ${cs.codec.version} - - - - org.apache.cloudstack - cloud-core - ${project.version} - - - org.apache.cloudstack - cloud-agent - ${project.version} - - - org.apache.cloudstack - cloud-api - ${project.version} - - - org.apache.cloudstack - cloud-utils - ${project.version} - - install - maven-assembly-plugin - 2.3 - - cloud-scripts - false - - cloudpatch-descriptor.xml - - + maven-antrun-plugin + 1.7 - make-cloud-scripts + build-cloud-scripts package - single + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 7e5815682a8..fe536cbb5a9 100755 --- a/patches/systemvm/debian/config/etc/init.d/cloud-early-config +++ b/patches/systemvm/debian/config/etc/init.d/cloud-early-config @@ -102,8 +102,8 @@ get_boot_params() { local hyp=$(hypervisor) [ $? -ne 0 ] && log_it "Failed to detect hypervisor type, bailing out of early init" && exit 10 - case $hyp in - xen-domU) + case $hyp in + xen-domU|xen-hvm) cat /proc/cmdline > /var/cache/cloud/cmdline sed -i "s/%/ /g" /var/cache/cloud/cmdline ;; @@ -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 @@ -597,6 +603,10 @@ setup_vpcrouter() { setup_vmware_extra_nics fi + if [ -f /etc/hosts ]; then + grep -q $NAME /etc/hosts || echo "127.0.0.1 $NAME" >> /etc/hosts; + fi + cat > /etc/network/interfaces << EOF auto lo $1 iface lo inet loopback diff --git a/patches/systemvm/debian/config/etc/init.d/cloud-passwd-srvr b/patches/systemvm/debian/config/etc/init.d/cloud-passwd-srvr index e6818415cfb..f893a30704f 100755 --- a/patches/systemvm/debian/config/etc/init.d/cloud-passwd-srvr +++ b/patches/systemvm/debian/config/etc/init.d/cloud-passwd-srvr @@ -1,7 +1,7 @@ #!/bin/bash ### BEGIN INIT INFO # Provides: cloud-passwd-srvr -# Required-Start: mountkernfs $local_fs cloud-early-config +# Required-Start: mountkernfs $local_fs cloud-early-config iptables-persistent # Required-Stop: $local_fs # Should-Start: # Should-Stop: @@ -29,10 +29,55 @@ ENABLED=0 [ -e /etc/default/cloud-passwd-srvr ] && . /etc/default/cloud-passwd-srvr +add_iptables_rules() +{ + #Delete any old iptables rule for port 8080 on eth0 + remove_iptables_rules + + #For all cidrs on eth0 for port 8080 accept only if source is withing that cidr + for cidr in $(ip addr | grep eth0 | grep inet | awk '{print $2}'); + do + count=1 + #Try for 10 times, if it still fails then bail + while [ $count -le 10 ]; + do + (( count++ )) + iptables -A INPUT -i eth0 -p tcp -m state --state NEW -m tcp -s $cidr --dport 8080 -j ACCEPT + if [ `iptables -L INPUT -n -v | grep eth0 | grep 8080 | grep ACCEPT | wc -l` -gt 0 ] + then + break + else + sleep 2 + fi + done + done + echo "Added cloud-passwd-srvr iptables rules" && return 0 +} + +remove_iptables_rules() +{ + #Change the Internal Field Separator so the for loop, loops on lines and not spaces + OIFS="${IFS}" + NIFS=$'\n' + IFS="${NIFS}" + + #Removed all iptable rules for port 8080 on eth0, they were added in start() + for srcdest in `iptables -L -n -v | grep eth0 | grep 8080 | grep ACCEPT | awk '{print "--source "$8" --destination "$9}'`; + do + eval "iptables -D INPUT -i eth0 -p tcp -m state --state NEW -m tcp $srcdest --dport 8080 -j ACCEPT"; + done + + #Restore IFS + IFS="${OIFS}" + + echo "Removed cloud-passwd-srvr iptables rules" && return 0 +} + start() { [ "$ENABLED" != 0 ] || exit 0 pid=$(getpid) [ "$pid" != "" ] && echo "Password server is already running (pid=$pid)" && return 0 + add_iptables_rules nohup bash /opt/cloud/bin/passwd_server & } @@ -50,7 +95,8 @@ stop_socat() { stop () { stop_socat pid=$(getpid) - [ "$pid" != "" ] && kill -9 $pid && echo "Stopped password server (pid=$pid)" && stop_socat && return 0 + [ "$pid" != "" ] && kill -9 $pid && remove_iptables_rules && echo "Stopped password server (pid=$pid)" && stop_socat && return 0 + echo "Password server is not running" && return 0 } diff --git a/patches/systemvm/debian/config/etc/iptables/iptables-router b/patches/systemvm/debian/config/etc/iptables/iptables-router index 1aba34c8d3f..28469fbc639 100644 --- a/patches/systemvm/debian/config/etc/iptables/iptables-router +++ b/patches/systemvm/debian/config/etc/iptables/iptables-router @@ -33,8 +33,8 @@ COMMIT -A INPUT -i lo -j ACCEPT -A INPUT -i eth0 -p udp -m udp --dport 67 -j ACCEPT -A INPUT -i eth0 -p udp -m udp --dport 53 -j ACCEPT +-A INPUT -i eth0 -p tcp -m tcp --dport 53 -j ACCEPT -A INPUT -i eth1 -p tcp -m state --state NEW --dport 3922 -j ACCEPT --A INPUT -i eth0 -p tcp -m state --state NEW --dport 8080 -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport 80 -j ACCEPT -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT -A FORWARD -i eth0 -o eth2 -j ACCEPT diff --git a/patches/systemvm/debian/config/etc/iptables/rules b/patches/systemvm/debian/config/etc/iptables/rules index 614c3f93bbb..7c577615167 100644 --- a/patches/systemvm/debian/config/etc/iptables/rules +++ b/patches/systemvm/debian/config/etc/iptables/rules @@ -31,6 +31,7 @@ COMMIT -A INPUT -i lo -j ACCEPT -A INPUT -i eth0 -p udp -m udp --dport 67 -j ACCEPT -A INPUT -i eth0 -p udp -m udp --dport 53 -j ACCEPT +-A INPUT -i eth0 -p tcp -m tcp --dport 53 -j ACCEPT -A INPUT -i eth1 -p tcp -m state --state NEW --dport 3922 -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport 8080 -j ACCEPT -A INPUT -i eth0 -p tcp -m state --state NEW --dport 80 -j ACCEPT 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/opt/cloud/bin/patchsystemvm.sh b/patches/systemvm/debian/config/opt/cloud/bin/patchsystemvm.sh index 3bbf7b1bf88..8816ad7c068 100755 --- a/patches/systemvm/debian/config/opt/cloud/bin/patchsystemvm.sh +++ b/patches/systemvm/debian/config/opt/cloud/bin/patchsystemvm.sh @@ -74,6 +74,8 @@ routing_svcs() { chkconfig ssh on chkconfig nfs-common off chkconfig portmap off + echo "ssh haproxy apache2" > /var/cache/cloud/enabled_svcs + echo "cloud nfs-common portmap" > /var/cache/cloud/disabled_svcs if [ $RROUTER -eq 0 ] then chkconfig dnsmasq off @@ -81,18 +83,16 @@ routing_svcs() { chkconfig keepalived on chkconfig conntrackd on chkconfig postinit on - echo "keepalived conntrackd postinit" > /var/cache/cloud/enabled_svcs - echo "dnsmasq cloud-passwd-srvr" > /var/cache/cloud/disabled_svcs + echo "keepalived conntrackd postinit" >> /var/cache/cloud/enabled_svcs + echo "dnsmasq cloud-passwd-srvr" >> /var/cache/cloud/disabled_svcs else chkconfig dnsmasq on chkconfig cloud-passwd-srvr on chkconfig keepalived off chkconfig conntrackd off - echo "dnsmasq cloud-passwd-srvr " > /var/cache/cloud/enabled_svcs - echo "keepalived conntrackd " > /var/cache/cloud/disabled_svcs + echo "dnsmasq cloud-passwd-srvr " >> /var/cache/cloud/enabled_svcs + echo "keepalived conntrackd " >> /var/cache/cloud/disabled_svcs fi - echo "ssh haproxy apache2" >> /var/cache/cloud/enabled_svcs - echo "cloud nfs-common portmap" > /var/cache/cloud/disabled_svcs } vpcrouting_svcs() { @@ -119,7 +119,7 @@ dhcpsrvr_svcs() { chkconfig portmap off chkconfig keepalived off chkconfig conntrackd off - echo "cloud-passwd-srvr ssh dnsmasq apache2" > /var/cache/cloud/enabled_svcs + echo "ssh dnsmasq cloud-passwd-srvr apache2" > /var/cache/cloud/enabled_svcs echo "cloud nfs-common haproxy portmap" > /var/cache/cloud/disabled_svcs } @@ -132,7 +132,7 @@ elbvm_svcs() { chkconfig keepalived off chkconfig conntrackd off echo "ssh haproxy" > /var/cache/cloud/enabled_svcs - echo "cloud cloud-passwd-srvr dnsmasq apache2 nfs-common portmap" > /var/cache/cloud/disabled_svcs + echo "cloud dnsmasq cloud-passwd-srvr apache2 nfs-common portmap" > /var/cache/cloud/disabled_svcs } enable_pcihotplug() { diff --git a/patches/systemvm/debian/config/opt/cloud/bin/vpc_guestnw.sh b/patches/systemvm/debian/config/opt/cloud/bin/vpc_guestnw.sh index faf62c6ff0c..d20ed5a05d2 100755 --- a/patches/systemvm/debian/config/opt/cloud/bin/vpc_guestnw.sh +++ b/patches/systemvm/debian/config/opt/cloud/bin/vpc_guestnw.sh @@ -83,8 +83,10 @@ setup_dnsmasq() { # setup rules to allow dhcp/dns request sudo iptables -D INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT sudo iptables -D INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT + sudo iptables -D INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT sudo iptables -A INPUT -i $dev -p udp -m udp --dport 67 -j ACCEPT sudo iptables -A INPUT -i $dev -d $ip -p udp -m udp --dport 53 -j ACCEPT + sudo iptables -A INPUT -i $dev -d $ip -p tcp -m tcp --dport 53 -j ACCEPT # setup static sed -i -e "/^[#]*dhcp-range=interface:$dev/d" /etc/dnsmasq.d/cloud.conf echo "dhcp-range=interface:$dev,set:interface-$dev,$ip,static" >> /etc/dnsmasq.d/cloud.conf 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/patches/systemvm/debian/vpn/opt/cloud/bin/vpc_vpn_l2tp.sh b/patches/systemvm/debian/vpn/opt/cloud/bin/vpc_vpn_l2tp.sh index 9277bc7e943..0595869adf8 100755 --- a/patches/systemvm/debian/vpn/opt/cloud/bin/vpc_vpn_l2tp.sh +++ b/patches/systemvm/debian/vpn/opt/cloud/bin/vpc_vpn_l2tp.sh @@ -40,7 +40,9 @@ iptables_() { sudo iptables $op FORWARD -i ppp+ -d $zcidr -j ACCEPT sudo iptables $op FORWARD -i ppp+ -o ppp+ -j ACCEPT sudo iptables $op INPUT -i ppp+ -p udp --dport 53 -j ACCEPT + sudo iptables $op INPUT -i ppp+ -p tcp --dport 53 -j ACCEPT sudo iptables -t nat $op PREROUTING -i ppp+ -p udp --dport 53 -j DNAT --to-destination $local_ip + sudo iptables -t nat $op PREROUTING -i ppp+ -p tcp --dport 53 -j DNAT --to-destination $local_ip } ipsec_server() { diff --git a/patches/systemvm/debian/vpn/opt/cloud/bin/vpn_l2tp.sh b/patches/systemvm/debian/vpn/opt/cloud/bin/vpn_l2tp.sh index 7eb8b00d288..79661c8b0d1 100755 --- a/patches/systemvm/debian/vpn/opt/cloud/bin/vpn_l2tp.sh +++ b/patches/systemvm/debian/vpn/opt/cloud/bin/vpn_l2tp.sh @@ -49,7 +49,8 @@ iptables_() { sudo iptables $op FORWARD -i $subnet_if -o ppp+ -j ACCEPT sudo iptables $op FORWARD -i ppp+ -o ppp+ -j ACCEPT sudo iptables $op INPUT -i ppp+ -m udp -p udp --dport 53 -j ACCEPT - sudo iptables -t nat $op PREROUTING -i ppp+ -p udp -m udp --dport 53 -j DNAT --to-destination $subnet_ip + sudo iptables $op INPUT -i ppp+ -m tcp -p tcp --dport 53 -j ACCEPT + sudo iptables -t nat $op PREROUTING -i ppp+ -p tcp -m tcp --dport 53 -j DNAT --to-destination $subnet_ip if sudo iptables -t mangle -N VPN_$public_ip &> /dev/null then diff --git a/plugins/acl/static-role-based/pom.xml b/plugins/acl/static-role-based/pom.xml new file mode 100644 index 00000000000..a2e8d05d48e --- /dev/null +++ b/plugins/acl/static-role-based/pom.xml @@ -0,0 +1,32 @@ + + + 4.0.0 + cloud-plugin-acl-static-role-based + Apache CloudStack Plugin - ACL Static Role Based + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + diff --git a/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java new file mode 100644 index 00000000000..d39f87f1048 --- /dev/null +++ b/plugins/acl/static-role-based/src/org/apache/cloudstack/acl/StaticRoleBasedAPIAccessChecker.java @@ -0,0 +1,182 @@ +// 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 org.apache.cloudstack.acl; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.acl.APIAccessChecker; +import org.apache.log4j.Logger; + +import com.cloud.exception.PermissionDeniedException; +import com.cloud.server.ManagementServer; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import com.cloud.utils.PropertiesUtil; +import com.cloud.utils.component.AdapterBase; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.PluggableService; + +/* + * This is the default API access checker that grab's the user's account + * based on the account type, access is granted referring to commands in all *.properties files. + */ + +@Local(value=APIAccessChecker.class) +public class StaticRoleBasedAPIAccessChecker extends AdapterBase implements APIAccessChecker { + + protected static final Logger s_logger = Logger.getLogger(StaticRoleBasedAPIAccessChecker.class); + public static final short ADMIN_COMMAND = 1; + public static final short DOMAIN_ADMIN_COMMAND = 4; + public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2; + public static final short USER_COMMAND = 8; + private static List s_userCommands = null; + private static List s_resellerCommands = null; // AKA domain-admin + private static List s_adminCommands = null; + private static List s_resourceDomainAdminCommands = null; + private static List s_allCommands = null; + + protected @Inject AccountManager _accountMgr; + + protected StaticRoleBasedAPIAccessChecker() { + super(); + s_allCommands = new ArrayList(); + s_userCommands = new ArrayList(); + s_resellerCommands = new ArrayList(); + s_adminCommands = new ArrayList(); + s_resourceDomainAdminCommands = new ArrayList(); + } + + @Override + public boolean canAccessAPI(User user, String apiCommandName) + throws PermissionDeniedException{ + + boolean commandExists = s_allCommands.contains(apiCommandName); + + if(commandExists && user != null){ + Long accountId = user.getAccountId(); + Account userAccount = _accountMgr.getAccount(accountId); + short accountType = userAccount.getType(); + return isCommandAvailableForAccount(accountType, apiCommandName); + } + + return commandExists; + } + + private static boolean isCommandAvailableForAccount(short accountType, String commandName) { + boolean isCommandAvailable = false; + switch (accountType) { + case Account.ACCOUNT_TYPE_ADMIN: + isCommandAvailable = s_adminCommands.contains(commandName); + break; + case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: + isCommandAvailable = s_resellerCommands.contains(commandName); + break; + case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: + isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName); + break; + case Account.ACCOUNT_TYPE_NORMAL: + isCommandAvailable = s_userCommands.contains(commandName); + break; + } + return isCommandAvailable; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + super.configure(name, params); + + // Read command properties files to build the static map per role. + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + List services = locator.getAllPluggableServices(); + services.add((PluggableService) ComponentLocator.getComponent(ManagementServer.Name)); + + List configFiles = new ArrayList(); + for (PluggableService service : services) { + configFiles.addAll(Arrays.asList(service.getPropertiesFiles())); + } + + processConfigFiles(configFiles); + return true; + } + + private void processConfigFiles(List configFiles) { + Properties preProcessedCommands = new Properties(); + + for (String configFile : configFiles) { + File commandsFile = PropertiesUtil.findConfigFile(configFile); + if (commandsFile != null) { + try { + preProcessedCommands.load(new FileInputStream(commandsFile)); + } catch (FileNotFoundException fnfex) { + // in case of a file within a jar in classpath, try to open stream using url + InputStream stream = PropertiesUtil.openStreamFromURL(configFile); + if (stream != null) { + try { + preProcessedCommands.load(stream); + } catch (IOException e) { + s_logger.error("IO Exception, unable to find properties file:", fnfex); + } + } else { + s_logger.error("Unable to find properites file", fnfex); + } + } catch (IOException ioe) { + s_logger.error("IO Exception loading properties file", ioe); + } + } + } + + for (Object key : preProcessedCommands.keySet()) { + String preProcessedCommand = preProcessedCommands.getProperty((String) key); + int splitIndex = preProcessedCommand.lastIndexOf(";"); + // Backward compatible to old style, apiname=pkg;mask + String mask = preProcessedCommand.substring(splitIndex+1); + + try { + short cmdPermissions = Short.parseShort(mask); + if ((cmdPermissions & ADMIN_COMMAND) != 0) { + s_adminCommands.add((String) key); + } + if ((cmdPermissions & RESOURCE_DOMAIN_ADMIN_COMMAND) != 0) { + s_resourceDomainAdminCommands.add((String) key); + } + if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { + s_resellerCommands.add((String) key); + } + if ((cmdPermissions & USER_COMMAND) != 0) { + s_userCommands.add((String) key); + } + s_allCommands.addAll(s_adminCommands); + s_allCommands.addAll(s_resourceDomainAdminCommands); + s_allCommands.addAll(s_userCommands); + s_allCommands.addAll(s_resellerCommands); + } catch (NumberFormatException nfe) { + s_logger.info("Malformed command.properties permissions value, key = " + key + ", value = " + preProcessedCommand); + } + } + } + +} 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/file-systems/netapp/pom.xml b/plugins/file-systems/netapp/pom.xml index d2fdda8e8ff..e1c8866d15d 100644 --- a/plugins/file-systems/netapp/pom.xml +++ b/plugins/file-systems/netapp/pom.xml @@ -30,7 +30,7 @@ com.cloud.com.netapp manageontap - 1.0 + 4.0 diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java index db317e06d65..c87c9242010 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/AssociateLunCmd.java @@ -20,18 +20,18 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.netapp.NetappManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.AssociateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Associate a LUN with a guest IQN", responseObject = AssociateLunCmdResponse.class) +@APICommand(name = "associateLun", description="Associate a LUN with a guest IQN", responseObject = AssociateLunCmdResponse.class) public class AssociateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AssociateLunCmd.class.getName()); private static final String s_name = "associatelunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java index 2e0eb86eb1b..8c89730b978 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateLunCmd.java @@ -20,11 +20,11 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a LUN from a pool", responseObject = CreateLunCmdResponse.class) +@APICommand(name = "createLunOnFiler", description="Create a LUN from a pool", responseObject = CreateLunCmdResponse.class) public class CreateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateLunCmd.class.getName()); private static final String s_name = "createlunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java index a301deeed4a..a2d4b96e6dd 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumeOnFilerCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import java.net.UnknownHostException; import java.rmi.ServerException; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -34,7 +34,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateVolumeOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class) +@APICommand(name = "createVolumeOnFiler", description="Create a volume", responseObject = CreateVolumeOnFilerCmdResponse.class) public class CreateVolumeOnFilerCmd extends BaseCmd { private static final String s_name = "createvolumeresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java index 020493b98d4..9e38c5fc097 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/CreateVolumePoolCmd.java @@ -18,11 +18,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -33,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.CreateVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class) +@APICommand(name = "createPool", description="Create a pool", responseObject = CreateVolumePoolCmdResponse.class) public class CreateVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(CreateVolumePoolCmd.class.getName()); private static final String s_name = "createpoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java index de12511f0dd..1105ea53e9d 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DeleteVolumePoolCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class) +@APICommand(name = "deletePool", description="Delete a pool", responseObject = DeleteVolumePoolCmdResponse.class) public class DeleteVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteVolumePoolCmd.class.getName()); private static final String s_name = "deletepoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java index 76ccd0e5c3d..c5f7b117f5b 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyLunCmd.java @@ -20,23 +20,22 @@ import java.rmi.ServerException; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceInUseException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.netapp.NetappManager; import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteLUNCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) +@APICommand(name = "destroyLunOnFiler", description="Destroy a LUN", responseObject = DeleteLUNCmdResponse.class) public class DestroyLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DestroyLunCmd.class.getName()); diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java index 4bde7f519b8..4ddc0c9f6d0 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DestroyVolumeOnFilerCmd.java @@ -18,13 +18,10 @@ package com.cloud.api.commands.netapp; import java.rmi.ServerException; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.APICommand; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -36,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DeleteVolumeOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class) +@APICommand(name = "destroyVolumeOnFiler", description="Destroy a Volume", responseObject = DeleteVolumeOnFilerCmdResponse.class) public class DestroyVolumeOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DestroyVolumeOnFilerCmd.class.getName()); private static final String s_name = "destroyvolumeresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java index 77425cbe5ce..0a6c1a70ef1 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/DissociateLunCmd.java @@ -18,13 +18,10 @@ package com.cloud.api.commands.netapp; import java.rmi.ServerException; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.APICommand; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,7 +32,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.DissociateLunCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class) +@APICommand(name = "dissociateLun", description="Dissociate a LUN", responseObject = DissociateLunCmdResponse.class) public class DissociateLunCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DissociateLunCmd.class.getName()); private static final String s_name = "dissociatelunresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java index 1101648219a..630b14994e7 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListLunsCmd.java @@ -21,12 +21,12 @@ import java.util.List; import org.apache.log4j.Logger; -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.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +38,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListLunsCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List LUN", responseObject = ListLunsCmdResponse.class) +@APICommand(name = "listLunsOnFiler", description="List LUN", responseObject = ListLunsCmdResponse.class) public class ListLunsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListLunsCmd.class.getName()); diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java index e6467393386..d77f4fad849 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumePoolsCmd.java @@ -21,10 +21,10 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -36,7 +36,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListVolumePoolsCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List Pool", responseObject = ListVolumePoolsCmdResponse.class) +@APICommand(name = "listPools", description="List Pool", responseObject = ListVolumePoolsCmdResponse.class) public class ListVolumePoolsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListVolumePoolsCmd.class.getName()); private static final String s_name = "listpoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java index 389053a36dc..66a96f3a221 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ListVolumesOnFilerCmd.java @@ -19,14 +19,11 @@ package com.cloud.api.commands.netapp; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -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.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +35,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ListVolumesOnFilerCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class) +@APICommand(name = "listVolumesOnFiler", description="List Volumes", responseObject = ListVolumesOnFilerCmdResponse.class) public class ListVolumesOnFilerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListVolumesOnFilerCmd.class.getName()); private static final String s_name = "listvolumesresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java index 0bca2901dc7..3e32caebef3 100644 --- a/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java +++ b/plugins/file-systems/netapp/src/com/cloud/api/commands/netapp/ModifyVolumePoolCmd.java @@ -19,11 +19,11 @@ package com.cloud.api.commands.netapp; import org.apache.log4j.Logger; -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 org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -33,7 +33,7 @@ import com.cloud.server.ManagementService; import com.cloud.server.api.response.netapp.ModifyVolumePoolCmdResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class) +@APICommand(name = "modifyPool", description="Modify pool", responseObject = ModifyVolumePoolCmdResponse.class) public class ModifyVolumePoolCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ModifyVolumePoolCmd.class.getName()); private static final String s_name = "modifypoolresponse"; diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java index af2e5755516..861bb3cc668 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/LunVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="netapp_lun") -public class LunVO { +public class LunVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -85,7 +87,7 @@ public class LunVO { this.targetIqn = targetIqn; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java index 04318d00190..abcd20f8262 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/NetappVolumeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="netapp_volume") -public class NetappVolumeVO { +public class NetappVolumeVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -132,7 +134,7 @@ public class NetappVolumeVO { this.volumeSize = volumeSize; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java b/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java index 713db46ee54..71e8342e620 100644 --- a/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java +++ b/plugins/file-systems/netapp/src/com/cloud/netapp/PoolVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.netapp; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,9 +27,9 @@ import javax.persistence.Table; @Entity @Table(name="netapp_pool") -public class PoolVO { +public class PoolVO implements InternalIdentity { - public Long getId() { + public long getId() { return id; } 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/pom.xml b/plugins/hypervisors/kvm/pom.xml index d3eca911a04..8fc8f739460 100644 --- a/plugins/hypervisors/kvm/pom.xml +++ b/plugins/hypervisors/kvm/pom.xml @@ -94,6 +94,24 @@ + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + + + copy-dependencies + package + + copy-dependencies + + + target/dependencies + runtime + + + + diff --git a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java index 116c09d3807..e6f2f7f376a 100644 --- a/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java +++ b/plugins/hypervisors/kvm/src/com/cloud/hypervisor/kvm/resource/BridgeVifDriver.java @@ -89,7 +89,7 @@ public class BridgeVifDriver extends VifDriverBase { if (nic.getType() == Networks.TrafficType.Guest) { if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && !vlanId.equalsIgnoreCase("untagged")) { - if(trafficLabel != null || !trafficLabel.isEmpty()) { + if(trafficLabel != null && !trafficLabel.isEmpty()) { s_logger.debug("creating a vlan dev and bridge for guest traffic per traffic label " + trafficLabel); String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); @@ -107,7 +107,7 @@ public class BridgeVifDriver extends VifDriverBase { } else if (nic.getType() == Networks.TrafficType.Public) { if (nic.getBroadcastType() == Networks.BroadcastDomainType.Vlan && !vlanId.equalsIgnoreCase("untagged")) { - if(trafficLabel != null || !trafficLabel.isEmpty()){ + if(trafficLabel != null && !trafficLabel.isEmpty()){ s_logger.debug("creating a vlan dev and bridge for public traffic per traffic label " + trafficLabel); String brName = createVlanBr(vlanId, _pifs.get(trafficLabel)); intf.defBridgeNet(brName, null, nic.getMac(), getGuestNicModel(guestOsType)); 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 1bc70faa9d3..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 @@ -788,7 +788,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements String pif = getPif(bridge); if(_publicBridgeName != null && bridge.equals(_publicBridgeName)){ _pifs.put("public", pif); - } else if (_guestBridgeName != null) { + } + if (_guestBridgeName != null && bridge.equals(_guestBridgeName)) { _pifs.put("private", pif); } _pifs.put(bridge, pif); @@ -1103,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) { @@ -1113,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, @@ -1144,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()); @@ -1185,15 +1189,18 @@ 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) { - - BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl()); - vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID + if(primaryPool.getType() == StoragePoolType.CLVM) { + vol = templateToPrimaryDownload(cmd.getTemplateUrl(),primaryPool); + } else { + BaseVol = primaryPool.getPhysicalDisk(cmd.getTemplateUrl()); + vol = _storagePoolMgr.createDiskFromTemplate(BaseVol, UUID .randomUUID().toString(), primaryPool); - + } if (vol == null) { return new Answer(cmd, false, " Can't create storage volume on storage pool"); @@ -1212,13 +1219,82 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } + // this is much like PrimaryStorageDownloadCommand, but keeping it separate + protected KVMPhysicalDisk templateToPrimaryDownload(String templateUrl, KVMStoragePool primaryPool) { + int index = templateUrl.lastIndexOf("/"); + String mountpoint = templateUrl.substring(0, index); + String templateName = null; + if (index < templateUrl.length() - 1) { + templateName = templateUrl.substring(index + 1); + } + + KVMPhysicalDisk templateVol = null; + KVMStoragePool secondaryPool = null; + try { + secondaryPool = _storagePoolMgr.getStoragePoolByURI(mountpoint); + /* Get template vol */ + if (templateName == null) { + secondaryPool.refresh(); + List disks = secondaryPool.listPhysicalDisks(); + if (disks == null || disks.isEmpty()) { + s_logger.error("Failed to get volumes from pool: " + secondaryPool.getUuid()); + return null; + } + for (KVMPhysicalDisk disk : disks) { + if (disk.getName().endsWith("qcow2")) { + templateVol = disk; + break; + } + } + if (templateVol == null) { + s_logger.error("Failed to get template from pool: " + secondaryPool.getUuid()); + return null; + } + } else { + templateVol = secondaryPool.getPhysicalDisk(templateName); + } + + /* Copy volume to primary storage */ + + KVMPhysicalDisk primaryVol = _storagePoolMgr.copyPhysicalDisk(templateVol, UUID.randomUUID().toString(), primaryPool); + return primaryVol; + } catch (CloudRuntimeException e) { + s_logger.error("Failed to download template to primary storage",e); + return null; + } finally { + if (secondaryPool != null) { + secondaryPool.delete(); + } + } + } + public Answer execute(DestroyCommand cmd) { 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) { @@ -1572,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"); @@ -1650,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 @@ -1661,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, @@ -1689,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(); @@ -1774,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 @@ -1804,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); @@ -1847,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; @@ -1897,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) { @@ -1917,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; @@ -2043,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); @@ -2065,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"); } @@ -2205,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()); @@ -2320,12 +2406,15 @@ public class LibvirtComputingResource extends ServerResourceBase implements _vms.put(vmName, State.Stopping); } + List ifaces = null; + Domain dm = null; Connect dconn = null; Domain destDomain = null; Connect conn = null; try { conn = LibvirtConnection.getConnection(); + ifaces = getInterfaces(conn, vmName); dm = conn.domainLookupByUUID(UUID.nameUUIDFromBytes(vmName .getBytes())); dconn = new Connect("qemu+tcp://" + cmd.getDestinationIp() @@ -2364,6 +2453,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements } } else { destroy_network_rules_for_vm(conn, vmName); + for (InterfaceDef iface : ifaces) { + _vifDriver.unplug(iface); + } cleanupVM(conn, vmName, getVnetId(VirtualMachineName.getVnet(vmName))); } @@ -2584,6 +2676,8 @@ public class LibvirtComputingResource extends ServerResourceBase implements Connect conn = LibvirtConnection.getConnection(); List disks = getDisks(conn, vmName); + List ifaces = getInterfaces(conn, vmName); + destroy_network_rules_for_vm(conn, vmName); String result = stopVM(conn, vmName, defineOps.UNDEFINE_VM); if (result == null) { @@ -2591,19 +2685,11 @@ 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()); - } } } - } - - List ifaces = getInterfaces(conn, vmName); - for(InterfaceDef iface: ifaces){ - _vifDriver.unplug(iface); + for (InterfaceDef iface: ifaces) { + _vifDriver.unplug(iface); + } } final String result2 = cleanupVnet(conn, cmd.getVnet()); @@ -2853,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 { @@ -2881,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()); } @@ -2963,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(); @@ -3059,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(); } @@ -3077,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(); @@ -4345,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 059073f4f69..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 @@ -212,7 +212,7 @@ public class LibvirtStorageAdaptor implements StorageAdaptor { Secret s = null; - sd.setCephName(userInfoTemp[0]); + sd.setCephName(userInfoTemp[0] + "@" + host + ":" + port + "/" + path); try { s_logger.debug(sd.toString()); @@ -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..2658e4db3ee --- /dev/null +++ b/plugins/hypervisors/simulator/resources/components-simulator.xml @@ -0,0 +1,66 @@ + + + + + + + + + + + + + + true + + + + + + + + + + + + true + + + + + + + + + + + + + + + + + + + + + + + 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 85% 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..ff26d185d76 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockStorageManager.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManager.java @@ -35,35 +35,26 @@ import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.SecStorageSetupCommand; import com.cloud.agent.api.SecStorageVMSetupCommand; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.agent.api.storage.CopyVolumeAnswer; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateAnswer; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.storage.DownloadCommand; -import com.cloud.agent.api.storage.DownloadProgressCommand; -import com.cloud.agent.api.storage.ListTemplateCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; +import com.cloud.agent.api.storage.*; 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 ListVolumes(ListVolumeCommand cmd); public Answer Destroy(DestroyCommand cmd); public Answer Download(DownloadCommand cmd); public Answer DownloadProcess(DownloadProgressCommand cmd); @@ -74,7 +65,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 95% 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..1076089dcd6 100644 --- a/agent-simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/agent/manager/MockStorageManagerImpl.java @@ -30,6 +30,7 @@ import java.util.UUID; import javax.ejb.Local; import javax.naming.ConfigurationException; +import com.cloud.agent.api.storage.*; import org.apache.log4j.Logger; import com.cloud.agent.api.Answer; @@ -56,20 +57,6 @@ import com.cloud.agent.api.SecStorageSetupAnswer; import com.cloud.agent.api.SecStorageSetupCommand; import com.cloud.agent.api.SecStorageVMSetupCommand; import com.cloud.agent.api.StoragePoolInfo; -import com.cloud.agent.api.storage.CopyVolumeAnswer; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateAnswer; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; -import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.storage.DownloadAnswer; -import com.cloud.agent.api.storage.DownloadCommand; -import com.cloud.agent.api.storage.DownloadProgressCommand; -import com.cloud.agent.api.storage.ListTemplateAnswer; -import com.cloud.agent.api.storage.ListTemplateCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.simulator.MockHost; @@ -139,8 +126,8 @@ public class MockStorageManagerImpl implements MockStorageManager { @Override public PrimaryStorageDownloadAnswer primaryStorageDownload(PrimaryStorageDownloadCommand cmd) { - MockVolumeVO template = findVolumeFromSecondary(cmd.getUrl(), cmd.getSecondaryStorageUrl(), - MockVolumeType.TEMPLATE); + MockVolumeVO template = findVolumeFromSecondary(cmd.getUrl(), cmd.getSecondaryStorageUrl(), + MockVolumeType.TEMPLATE); if (template == null) { return new PrimaryStorageDownloadAnswer("Can't find primary storage"); } @@ -421,6 +408,49 @@ public class MockStorageManagerImpl implements MockStorageManager { return new SecStorageSetupAnswer(storage.getMountPoint()); } + @Override + public Answer ListVolumes(ListVolumeCommand cmd) { + Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); + MockSecStorageVO storage = null; + try { + txn.start(); + storage = _mockSecStorageDao.findByUrl(cmd.getSecUrl()); + if (storage == null) { + return new Answer(cmd, false, "Failed to get secondary storage"); + } + txn.commit(); + } catch (Exception ex) { + txn.rollback(); + throw new CloudRuntimeException("Error when finding sec storage " + cmd.getSecUrl(), ex); + } finally { + txn.close(); + txn = Transaction.open(Transaction.CLOUD_DB); + txn.close(); + } + + txn = Transaction.open(Transaction.SIMULATOR_DB); + try { + txn.start(); + List volumes = _mockVolumeDao.findByStorageIdAndType(storage.getId(), + MockVolumeType.VOLUME); + + Map templateInfos = new HashMap(); + for (MockVolumeVO volume : volumes) { + templateInfos.put(volume.getId(), new TemplateInfo(volume.getName(), volume.getPath() + .replaceAll(storage.getMountPoint(), ""), volume.getSize(), volume.getSize(), true, false)); + } + txn.commit(); + return new ListVolumeAnswer(cmd.getSecUrl(), templateInfos); + } catch (Exception ex) { + txn.rollback(); + throw new CloudRuntimeException("Error when finding template on sec storage " + storage.getId(), ex); + } finally { + txn.close(); + txn = Transaction.open(Transaction.CLOUD_DB); + txn.close(); + } + } + @Override public Answer ListTemplates(ListTemplateCommand cmd) { Transaction txn = Transaction.open(Transaction.SIMULATOR_DB); @@ -703,7 +733,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); @@ -907,7 +937,7 @@ public class MockStorageManagerImpl implements MockStorageManager { long defaultTemplateSize = 2 * 1024 * 1024 * 1024L; MockVolumeVO template = new MockVolumeVO(); template.setName("simulator-domR"); - template.setPath(storage.getMountPoint() + "template/tmpl/1/9/" + UUID.randomUUID().toString()); + template.setPath(storage.getMountPoint() + "template/tmpl/1/10/" + UUID.randomUUID().toString()); template.setPoolId(storage.getId()); template.setSize(defaultTemplateSize); template.setType(MockVolumeType.TEMPLATE); @@ -928,7 +958,7 @@ public class MockStorageManagerImpl implements MockStorageManager { template = new MockVolumeVO(); template.setName("simulator-Centos"); - template.setPath(storage.getMountPoint() + "template/tmpl/1/10/" + UUID.randomUUID().toString()); + template.setPath(storage.getMountPoint() + "template/tmpl/1/11/" + UUID.randomUUID().toString()); template.setPoolId(storage.getId()); template.setSize(defaultTemplateSize); template.setType(MockVolumeType.TEMPLATE); @@ -953,7 +983,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 +998,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 +1028,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 81% 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..4f70ee5bae7 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; @@ -25,6 +23,7 @@ import javax.ejb.Local; import javax.naming.ConfigurationException; import com.cloud.agent.api.*; +import com.cloud.agent.api.storage.*; import org.apache.log4j.Logger; import com.cloud.agent.api.check.CheckSshCommand; @@ -38,14 +37,6 @@ import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VmDataCommand; -import com.cloud.agent.api.storage.CopyVolumeCommand; -import com.cloud.agent.api.storage.CreateCommand; -import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.agent.api.storage.DestroyCommand; -import com.cloud.agent.api.storage.DownloadCommand; -import com.cloud.agent.api.storage.DownloadProgressCommand; -import com.cloud.agent.api.storage.ListTemplateCommand; -import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.simulator.MockConfigurationVO; import com.cloud.simulator.MockHost; import com.cloud.simulator.MockVMVO; @@ -58,6 +49,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,83 +113,83 @@ 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); + return _mockAgentMgr.getHostStatistic((GetHostStatsCommand) cmd); } else if (cmd instanceof CheckHealthCommand) { - return _mockAgentMgr.checkHealth((CheckHealthCommand)cmd); + return _mockAgentMgr.checkHealth((CheckHealthCommand) cmd); } else if (cmd instanceof PingTestCommand) { - return _mockAgentMgr.pingTest((PingTestCommand)cmd); + 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); + return _mockVmMgr.Migrate((MigrateCommand) cmd, info); } else if (cmd instanceof StartCommand) { - return _mockVmMgr.startVM((StartCommand)cmd, info); + return _mockVmMgr.startVM((StartCommand) cmd, info); } else if (cmd instanceof CheckSshCommand) { - return _mockVmMgr.checkSshCommand((CheckSshCommand)cmd); + 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); + 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); + return _mockVmMgr.SetPortForwardingRules((SetPortForwardingRulesCommand) cmd); } else if (cmd instanceof NetworkUsageCommand) { - return _mockVmMgr.getNetworkUsage((NetworkUsageCommand)cmd); + return _mockVmMgr.getNetworkUsage((NetworkUsageCommand) cmd); } else if (cmd instanceof IpAssocCommand) { - return _mockVmMgr.IpAssoc((IpAssocCommand)cmd); + return _mockVmMgr.IpAssoc((IpAssocCommand) cmd); } else if (cmd instanceof LoadBalancerConfigCommand) { - return _mockVmMgr.LoadBalancerConfig((LoadBalancerConfigCommand)cmd); + return _mockVmMgr.LoadBalancerConfig((LoadBalancerConfigCommand) cmd); } else if (cmd instanceof DhcpEntryCommand) { - return _mockVmMgr.AddDhcpEntry((DhcpEntryCommand)cmd); + return _mockVmMgr.AddDhcpEntry((DhcpEntryCommand) cmd); } else if (cmd instanceof VmDataCommand) { - return _mockVmMgr.setVmData((VmDataCommand)cmd); + return _mockVmMgr.setVmData((VmDataCommand) cmd); } else if (cmd instanceof CleanupNetworkRulesCmd) { - return _mockVmMgr.CleanupNetworkRules((CleanupNetworkRulesCmd)cmd, info); + 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) { - return _mockVmMgr.rebootVM((RebootCommand)cmd); + return _mockVmMgr.rebootVM((RebootCommand) cmd); } else if (cmd instanceof GetVncPortCommand) { return _mockVmMgr.getVncPort((GetVncPortCommand)cmd); } else if (cmd instanceof CheckConsoleProxyLoadCommand) { @@ -226,6 +218,8 @@ public class SimulatorManagerImpl implements SimulatorManager { return _mockStorageMgr.SecStorageSetup((SecStorageSetupCommand)cmd); } else if (cmd instanceof ListTemplateCommand) { return _mockStorageMgr.ListTemplates((ListTemplateCommand)cmd); + } else if (cmd instanceof ListVolumeCommand) { + return _mockStorageMgr.ListVolumes((ListVolumeCommand)cmd); } else if (cmd instanceof DestroyCommand) { return _mockStorageMgr.Destroy((DestroyCommand)cmd); } else if (cmd instanceof DownloadProgressCommand) { @@ -261,12 +255,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 +281,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 88% 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..df81249538d 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.APICommand; +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; @@ -33,29 +33,29 @@ import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="configure simulator", responseObject=SuccessResponse.class) +@APICommand(name = "configureSimulator", description="configure simulator", responseObject=SuccessResponse.class) 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 75% rename from agent-simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java rename to plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java index f828bc822ca..3f7cea5b6b1 100644 --- a/agent-simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java +++ b/plugins/hypervisors/simulator/src/com/cloud/resource/SimulatorSecondaryDiscoverer.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.resource; +import java.net.URI; import java.util.List; import java.util.Map; @@ -39,24 +40,50 @@ import com.cloud.storage.dao.SnapshotDao; import com.cloud.storage.secondary.SecondaryStorageDiscoverer; import com.cloud.utils.component.Inject; import com.cloud.utils.exception.CloudRuntimeException; +import org.apache.log4j.Logger; + @Local(value=Discoverer.class) public class SimulatorSecondaryDiscoverer extends SecondaryStorageDiscoverer implements ResourceStateAdapter, Listener { + private static final Logger s_logger = Logger.getLogger(SimulatorSecondaryDiscoverer.class); @Inject MockStorageManager _mockStorageMgr = null; @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 Map> find(long dcId, Long podId, Long clusterId, URI uri, String username, String password, List hostTags) { + if (!uri.getScheme().equalsIgnoreCase("nfs") && !uri.getScheme().equalsIgnoreCase("file") + && !uri.getScheme().equalsIgnoreCase("iso") && !uri.getScheme().equalsIgnoreCase("dummy")) { + s_logger.debug("It's not NFS or file or ISO, so not a secondary storage server: " + uri.toString()); + return null; + } + + if (uri.getScheme().equalsIgnoreCase("nfs") || uri.getScheme().equalsIgnoreCase("iso")) { + return createNfsSecondaryStorageResource(dcId, podId, uri); + } else if (uri.getScheme().equalsIgnoreCase("file")) { + return createLocalSecondaryStorageResource(dcId, podId, uri); + } else if (uri.getScheme().equalsIgnoreCase("dummy")) { + return createDummySecondaryStorageResource(dcId, podId, uri); + } else { + return null; + } + } + + @Override public void postDiscovery(List hosts, long msId) { super.postDiscovery(hosts, msId); for (HostVO host: hosts) { + if(s_logger.isDebugEnabled()) { + s_logger.debug("Preinstalling simulator templates"); + } _mockStorageMgr.preinstallTemplates(host.getStorageUrl(), host.getDataCenterId()); } } @@ -74,9 +101,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 +130,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 +157,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 92% rename from agent-simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java rename to plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java index 1c69b543aa8..ad42c23380e 100644 --- a/agent-simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java +++ b/plugins/hypervisors/simulator/src/com/cloud/server/ManagementServerSimulatorImpl.java @@ -19,13 +19,13 @@ package com.cloud.server; public class ManagementServerSimulatorImpl extends ManagementServerExtImpl { @Override - public String[] getApiConfig() { - String[] apis = super.getApiConfig(); + public String[] getPropertiesFiles() { + String[] apis = super.getPropertiesFiles(); String[] newapis = new String[apis.length + 1]; 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 95% rename from agent-simulator/src/com/cloud/simulator/MockConfigurationVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java index dfea2279e9e..5959347e6dd 100644 --- a/agent-simulator/src/com/cloud/simulator/MockConfigurationVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockConfigurationVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.HashMap; import java.util.Map; @@ -28,84 +30,84 @@ import javax.persistence.Table; @Entity @Table(name="mockconfiguration") -public class MockConfigurationVO { +public class MockConfigurationVO implements InternalIdentity { @Id @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 +115,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..0242135abbc 100644 --- a/agent-simulator/src/com/cloud/simulator/MockHostVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockHostVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,250 +28,250 @@ import javax.persistence.Table; @Entity @Table(name="mockhost") -public class MockHostVO implements MockHost { +public class MockHostVO implements MockHost, InternalIdentity { @Id @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 93% rename from agent-simulator/src/com/cloud/simulator/MockSecStorageVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java index c503cc260be..2352687ba9f 100644 --- a/agent-simulator/src/com/cloud/simulator/MockSecStorageVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecStorageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,50 +28,50 @@ import javax.persistence.Table; @Entity @Table(name="mocksecstorage") -public class MockSecStorageVO { +public class MockSecStorageVO implements InternalIdentity { @Id @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 94% rename from agent-simulator/src/com/cloud/simulator/MockSecurityRulesVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java index 3036ea98db2..d0d77c969ac 100644 --- a/agent-simulator/src/com/cloud/simulator/MockSecurityRulesVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockSecurityRulesVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.simulator; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,78 +28,78 @@ import javax.persistence.Table; @Entity @Table(name="mocksecurityrules") -public class MockSecurityRulesVO { +public class MockSecurityRulesVO implements InternalIdentity { @Id @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 95% rename from agent-simulator/src/com/cloud/simulator/MockStoragePoolVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java index 81f0432247d..c8f068a9e29 100644 --- a/agent-simulator/src/com/cloud/simulator/MockStoragePoolVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockStoragePoolVO.java @@ -26,76 +26,77 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.storage.Storage.StoragePoolType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockstoragepool") -public class MockStoragePoolVO { +public class MockStoragePoolVO implements InternalIdentity { @Id @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 87% rename from agent-simulator/src/com/cloud/simulator/MockVMVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java index c1b391e37f6..292f20031c3 100644 --- a/agent-simulator/src/com/cloud/simulator/MockVMVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVMVO.java @@ -24,107 +24,118 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockvm") -public class MockVMVO implements MockVm{ +public class MockVMVO implements MockVm, InternalIdentity { @Id @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 95% rename from agent-simulator/src/com/cloud/simulator/MockVolumeVO.java rename to plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java index 94908d7efd4..fe337e793f2 100644 --- a/agent-simulator/src/com/cloud/simulator/MockVolumeVO.java +++ b/plugins/hypervisors/simulator/src/com/cloud/simulator/MockVolumeVO.java @@ -27,12 +27,13 @@ import javax.persistence.Table; import com.cloud.storage.VMTemplateStorageResourceAssoc; import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mockvolume") -public class MockVolumeVO { +public class MockVolumeVO implements InternalIdentity { public enum MockVolumeType { VOLUME, TEMPLATE, @@ -43,76 +44,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/vmware/pom.xml b/plugins/hypervisors/vmware/pom.xml index 81d8dc1dd4f..d990e89b388 100644 --- a/plugins/hypervisors/vmware/pom.xml +++ b/plugins/hypervisors/vmware/pom.xml @@ -34,21 +34,36 @@ com.cloud.com.vmware - vmware-vim - 1.0 - provided + vmware-vim25 + ${cs.vmware.api.version} + compile com.cloud.com.vmware - vmware-vim25 - 1.0 - provided + vmware-vim + ${cs.vmware.api.version} + compile com.cloud.com.vmware vmware-apputils - 1.0 - provided - + ${cs.vmware.api.version} + compile + + + org.apache.axis + axis + ${cs.axis.version} + + + org.apache.axis + axis-jaxrpc + ${cs.axis.version} + + + wsdl4j + wsdl4j + 1.4 + diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java index 601ec9d6f4d..3e45ce2a084 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DeleteCiscoNexusVSMCmd.java @@ -19,14 +19,14 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -34,9 +34,8 @@ import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.element.CiscoNexusVSMElementService; import com.cloud.user.Account; -import com.cloud.user.UserContext; -@Implementation(responseObject=SuccessResponse.class, description=" delete a Cisco Nexus VSM device") +@APICommand(name = "deleteCiscoNexusVSM", responseObject=SuccessResponse.class, description=" delete a Cisco Nexus VSM device") public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteCiscoNexusVSMCmd.class.getName()); @@ -47,8 +46,8 @@ public class DeleteCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java index 5f911f45c8e..9a7f6ada97c 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/DisableCiscoNexusVSMCmd.java @@ -19,13 +19,12 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -36,7 +35,7 @@ import com.cloud.event.EventTypes; import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.network.CiscoNexusVSMDevice; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="disable a Cisco Nexus VSM device") +@APICommand(name = "disableCiscoNexusVSM", responseObject=CiscoNexusVSMResponse.class, description="disable a Cisco Nexus VSM device") public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DisableCiscoNexusVSMCmd.class.getName()); @@ -47,8 +46,8 @@ public class DisableCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be deleted") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java index 67c0ae3aba4..5dc67212fd3 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/EnableCiscoNexusVSMCmd.java @@ -17,15 +17,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -36,7 +31,7 @@ import com.cloud.user.Account; import com.cloud.api.response.CiscoNexusVSMResponse; import com.cloud.network.CiscoNexusVSMDevice; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="Enable a Cisco Nexus VSM device") +@APICommand(name = "enableCiscoNexusVSM", responseObject=CiscoNexusVSMResponse.class, description="Enable a Cisco Nexus VSM device") public class EnableCiscoNexusVSMCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(EnableCiscoNexusVSMCmd.class.getName()); @@ -47,8 +42,8 @@ public class EnableCiscoNexusVSMCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="virtual_supervisor_module") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required=true, description="Id of the Cisco Nexus 1000v VSM device to be enabled") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType=CiscoNexusVSMResponse.class, + required=true, description="Id of the Cisco Nexus 1000v VSM device to be enabled") private Long id; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java index bd25258b546..ee6a01bdb8a 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/commands/ListCiscoNexusVSMsCmd.java @@ -17,16 +17,17 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.CiscoNexusVSMResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceAllocationException; @@ -38,7 +39,7 @@ import com.cloud.user.Account; import java.util.ArrayList; import java.util.List; -@Implementation(responseObject=CiscoNexusVSMResponse.class, description="Retrieves a Cisco Nexus 1000v Virtual Switch Manager device associated with a Cluster") +@APICommand(name = "listCiscoNexusVSMs", responseObject=CiscoNexusVSMResponse.class, description="Retrieves a Cisco Nexus 1000v Virtual Switch Manager device associated with a Cluster") public class ListCiscoNexusVSMsCmd extends BaseListCmd { /** @@ -56,12 +57,12 @@ public class ListCiscoNexusVSMsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="cluster") - @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.LONG, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") + @Parameter(name=ApiConstants.CLUSTER_ID, type=CommandType.UUID, entityType = ClusterResponse.class, + required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long clusterId; - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = false, description="Id of the CloudStack cluster in which the Cisco Nexus 1000v VSM appliance.") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java b/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java index e0169d3c8e3..25a824e5796 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java +++ b/plugins/hypervisors/vmware/src/com/cloud/api/response/CiscoNexusVSMResponse.java @@ -16,27 +16,29 @@ // under the License. package com.cloud.api.response; -import javax.persistence.Column; - -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +import com.cloud.network.CiscoNexusVSMDevice; + +@EntityReference(value=CiscoNexusVSMDevice.class) public class CiscoNexusVSMResponse extends BaseResponse { @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_ID) @Param(description="device id of the Cisco N1KV VSM device") - private IdentityProxy id = new IdentityProxy("virtual_supervisor_module"); - + private String id; + @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_NAME) @Param(description="device name") private String deviceName; - + @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external Cisco Nexus 1000v Virtual Supervisor Module") private String vsmmgmtIpAddress; - + @SerializedName(ApiConstants.EXTERNAL_SWITCH_MGMT_DEVICE_STATE) @Param(description="device state") private String deviceState; - + @SerializedName(ApiConstants.VSM_MGMT_VLAN_ID) @Param(description="management vlan id of the VSM") private String vsmmgmtvlanid; @@ -48,22 +50,22 @@ public class CiscoNexusVSMResponse extends BaseResponse { @SerializedName(ApiConstants.VSM_STORAGE_VLAN_ID) @Param(description="storage vlan id of the VSM") private int vsmstoragevlanid; - + @SerializedName(ApiConstants.VSM_DOMAIN_ID) @Param(description="The VSM is a switch supervisor. This is the VSM's switch domain id") private String vsmdomainid; - + @SerializedName(ApiConstants.VSM_CONFIG_MODE) @Param(description="The mode of the VSM (standalone/HA)") private String vsmconfigmode; - + @SerializedName(ApiConstants.VSM_CONFIG_STATE) @Param(description="The Config State (Primary/Standby) of the VSM") private String vsmconfigstate; - + @SerializedName(ApiConstants.VSM_DEVICE_STATE) @Param(description="The Device State (Enabled/Disabled) of the VSM") private String vsmdevicestate; // Setter methods. - public void setId(long vsmDeviceId) { - this.id.setValue(vsmDeviceId); + public void setId(String vsmDeviceId) { + this.id = vsmDeviceId; } public void setDeviceName(String deviceName) { @@ -73,39 +75,39 @@ public class CiscoNexusVSMResponse extends BaseResponse { public void setMgmtIpAddress(String ipAddress) { this.vsmmgmtIpAddress = ipAddress; } - + public void setDeviceState(String deviceState) { this.deviceState = deviceState; } - + public void setVSMMgmtVlanId(String vlanId) { this.vsmmgmtvlanid = vlanId; } - + public void setVSMCtrlVlanId(int vlanId) { this.vsmctrlvlanid = vlanId; } - + public void setVSMPktVlanId(int vlanId) { this.vsmpktvlanid = vlanId; } - + public void setVSMStorageVlanId(int vlanId) { this.vsmstoragevlanid = vlanId; } - + public void setVSMDomainId(String domId) { this.vsmdomainid = domId; } - + public void setVSMConfigMode(String configMode) { this.vsmconfigmode = configMode; } - + public void setVSMConfigState(String configState) { this.vsmconfigstate = configState; } - + public void setVSMDeviceState(String devState) { this.vsmdevicestate = devState; } diff --git a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java index 0b0f285a960..a444cfec197 100755 --- a/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java +++ b/plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java @@ -3705,10 +3705,12 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if (morDatastore == null) throw new Exception("Unable to find datastore in vSphere"); - + DatastoreMO dsMo = new DatastoreMO(context, morDatastore); - if (cmd.getDiskCharacteristics().getType() == Volume.Type.ROOT) { + if (dskch.getType() == Volume.Type.ROOT) { + // attach volume id to make the name unique + String vmdkName = dskch.getName() + "-" + dskch.getVolumeId(); if (cmd.getTemplateUrl() == null) { // create a root volume for blank VM String dummyVmName = getWorkerName(context, cmd, 0); @@ -3720,16 +3722,15 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception("Unable to create a dummy VM for volume creation"); } - String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), cmd.getDiskCharacteristics().getName()); + String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName); synchronized (this) { s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); - VmwareHelper.deleteVolumeVmdkFiles(dsMo, cmd.getDiskCharacteristics().getName(), dcMo); - vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, -1); + VmwareHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo); + vmMo.createDisk(volumeDatastorePath, (int) (dskch.getSize() / (1024L * 1024L)), morDatastore, -1); vmMo.detachDisk(volumeDatastorePath, false); } - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), cmd - .getDiskCharacteristics().getName(), cmd.getDiskCharacteristics().getSize(), null); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); @@ -3753,41 +3754,40 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa throw new Exception(msg); } - String name = cmd.getDiskCharacteristics().getName(); - if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), name)) - dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), name), dcMo.getMor(), false); + if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) + dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("create linked clone from template"); - if (!vmTemplate.createLinkedClone(name, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { + if (!vmTemplate.createLinkedClone(vmdkName, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to clone from the template"; s_logger.error(msg); throw new Exception(msg); } - VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(name); + VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName); assert (vmMo != null); // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); - dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), name, name), - dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s.vmdk", dsMo.getName(), name), dcMo.getMor(), true); + dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), + dcMo.getMor(), dsMo.getMor(), + String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); - dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), name, name), - dcMo.getMor(), dsMo.getMor(), - String.format("[%s] %s-delta.vmdk", dsMo.getName(), name), dcMo.getMor(), true); + dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), + dcMo.getMor(), dsMo.getMor(), + String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); - s_logger.info("detach disks from volume-wrapper VM " + name); + s_logger.info("detach disks from volume-wrapper VM " + vmdkName); vmMo.detachAllDisks(); - s_logger.info("destroy volume-wrapper VM " + name); + s_logger.info("destroy volume-wrapper VM " + vmdkName); vmMo.destroy(); - String srcFile = String.format("[%s] %s/", dsMo.getName(), name); + String srcFile = String.format("[%s] %s/", dsMo.getName(), vmdkName); dsMo.deleteFile(srcFile, dcMo.getMor(), true); - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), name, pool.getPath(), name, cmd.getDiskCharacteristics().getSize(), null); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } } else { @@ -3806,12 +3806,11 @@ public class VmwareResource implements StoragePoolResource, ServerResource, Vmwa // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); - vmMo.createDisk(volumeDatastorePath, (int) (cmd.getDiskCharacteristics().getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey()); + vmMo.createDisk(volumeDatastorePath, (int) (dskch.getSize() / (1024L * 1024L)), morDatastore, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); } - VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), cmd.getDiskCharacteristics().getName(), pool.getPath(), volumeUuid, cmd - .getDiskCharacteristics().getSize(), null); + VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java index c58a6a77a77..19da27116de 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDevice.java @@ -16,57 +16,58 @@ // under the License. package com.cloud.network; -public interface CiscoNexusVSMDevice { - +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +public interface CiscoNexusVSMDevice extends InternalIdentity, Identity { + // This tells us whether the VSM is currently enabled or disabled. We may // need this if we would like to carry out any sort of maintenance on the // VSM or CS. public enum VSMDeviceState { Enabled, Disabled - } - + } + // This tells us whether the VSM is currently configured with a standby (HA) // or does not have any standby (Standalone). public enum VSMConfigMode { Standalone, HA } - + // This tells us whether the VSM is currently a primary or a standby VSM. public enum VSMConfigState { Primary, Standby } - long getId(); - public String getvsmName(); - + public long getHostId(); - + public String getUserName(); - + public String getPassword(); public String getipaddr(); - + public int getManagementVlan(); - + public int getControlVlan(); - + public int getPacketVlan(); public int getStorageVlan(); - + public long getvsmDomainId(); - + public VSMConfigMode getvsmConfigMode(); - + public VSMConfigState getvsmConfigState(); - + public VSMDeviceState getvsmDeviceState(); - + public String getUuid(); - + } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java index e5da5624912..c28f25987c3 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceManagerImpl.java @@ -16,17 +16,13 @@ // under the License. package com.cloud.network; -import java.util.HashMap; - import java.util.List; -import java.util.Map; import javax.inject.Inject; import org.apache.log4j.Logger; import com.cloud.agent.api.StartupCommand; -import com.cloud.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterDetailsDao; @@ -35,7 +31,6 @@ import com.cloud.dc.ClusterVSMMapVO; import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.ClusterVSMMapDao; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.DetailVO; import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDetailsDao; diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java index af9ff0e1d7c..d24f15def97 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/CiscoNexusVSMDeviceVO.java @@ -26,8 +26,9 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.api.InternalIdentity; /** * CiscoNexusVSMDeviceVO contains information on external Cisco Nexus 1000v VSM devices added into a deployment. @@ -37,7 +38,7 @@ import com.cloud.utils.db.Encrypt; @Entity @Table(name="virtual_supervisor_module") -public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ +public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice { // We need to know what properties a VSM has. Put them here. @@ -133,7 +134,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ @Override public int getPacketVlan() { return packetVlan; - } + } @Override public int getStorageVlan() { @@ -197,7 +198,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ public void setPacketVlan(int vlan) { this.packetVlan = vlan; - } + } public void setStorageVlan(int vlan) { this.storageVlan = vlan; @@ -222,7 +223,7 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ // Constructors. - public CiscoNexusVSMDeviceVO(String vsmIpAddr, String username, String password) { + public CiscoNexusVSMDeviceVO(String vsmIpAddr, String username, String password) { // Set all the VSM's properties here. this.uuid = UUID.randomUUID().toString(); this.setMgmtIpAddr(vsmIpAddr); @@ -234,5 +235,5 @@ public class CiscoNexusVSMDeviceVO implements CiscoNexusVSMDevice, Identity{ public CiscoNexusVSMDeviceVO() { this.uuid = UUID.randomUUID().toString(); - } + } } diff --git a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java index ab3eb347315..98ed3f8a231 100644 --- a/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java +++ b/plugins/hypervisors/vmware/src/com/cloud/network/element/CiscoNexusVSMElement.java @@ -52,7 +52,6 @@ import com.cloud.vm.NicProfile; import com.cloud.vm.ReservationContext; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachineProfile; -import com.cloud.network.element.NetworkElement; import com.cloud.offering.NetworkOffering; import com.cloud.org.Cluster; import com.cloud.utils.component.Manager; @@ -112,7 +111,7 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme } @Override - public boolean destroy(Network network) + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } @@ -215,14 +214,14 @@ public class CiscoNexusVSMElement extends CiscoNexusVSMDeviceManagerImpl impleme @Override public CiscoNexusVSMResponse createCiscoNexusVSMResponse(CiscoNexusVSMDevice vsmDeviceVO) { CiscoNexusVSMResponse response = new CiscoNexusVSMResponse(); - response.setId(vsmDeviceVO.getId()); + response.setId(vsmDeviceVO.getUuid()); response.setMgmtIpAddress(vsmDeviceVO.getipaddr()); return response; } public CiscoNexusVSMResponse createCiscoNexusVSMDetailedResponse(CiscoNexusVSMDevice vsmDeviceVO) { CiscoNexusVSMResponse response = new CiscoNexusVSMResponse(); - response.setId(vsmDeviceVO.getId()); + response.setId(vsmDeviceVO.getUuid()); response.setDeviceName(vsmDeviceVO.getvsmName()); response.setDeviceState(vsmDeviceVO.getvsmDeviceState().toString()); response.setMgmtIpAddress(vsmDeviceVO.getipaddr()); 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 f43e76fdcee..46eaa725f1e 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 @@ -72,6 +72,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; @@ -439,8 +440,8 @@ 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(); @@ -455,7 +456,7 @@ public class XcpServerDiscoverer extends DiscovererBase implements Discoverer, L 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; + 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); @@ -591,8 +592,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)) { @@ -605,7 +606,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 9a0490335fe..b30ef23732a 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; @@ -181,6 +187,7 @@ import com.cloud.agent.api.storage.StorageCommand; 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; @@ -219,6 +226,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; @@ -3121,11 +3130,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 { @@ -4336,8 +4341,13 @@ public abstract class CitrixResourceBase implements ServerResource, HypervisorRe } XsLocalNetwork storageNic1 = null; storageNic1 = getNetworkByName(conn, _storageNetworkName1); + if (storageNic1 == null) { + s_logger.warn("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.ip); + throw new IllegalArgumentException("Unable to find storage network " + _storageNetworkName1 + " for host " + _host.ip); + } else { _host.storageNetwork1 = storageNic1.getNetworkRecord(conn).uuid; _host.storagePif1 = storageNic1.getPifRecord(conn).uuid; + } XsLocalNetwork storageNic2 = null; if (_storageNetworkName2 != null) { @@ -6525,6 +6535,13 @@ 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 { @@ -6542,6 +6559,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); @@ -6564,6 +6583,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..412da0e289e --- /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/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java index 024dcdc09e0..44b98eb2973 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/ElasticLbVmMapVO.java @@ -29,13 +29,14 @@ import javax.persistence.SecondaryTables; import javax.persistence.Table; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("elastic_lb_vm_map")) @SecondaryTables({ @SecondaryTable(name = "user_ip_address", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "ip_addr_id", referencedColumnName = "id") }) }) -public class ElasticLbVmMapVO { +public class ElasticLbVmMapVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -66,7 +67,7 @@ public class ElasticLbVmMapVO { this.lbId = lbId; } - public Long getId() { + public long getId() { return id; } diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/element/ElasticLoadBalancerElement.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/element/ElasticLoadBalancerElement.java index b11389c1a81..1271f4106c2 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/element/ElasticLoadBalancerElement.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/element/ElasticLoadBalancerElement.java @@ -126,7 +126,7 @@ public class ElasticLoadBalancerElement extends AdapterBase implements LoadBalan } @Override - public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { // TODO kill all loadbalancer vms by calling the ElasticLoadBalancerManager return false; } diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java index 0dc5b14a1a5..aea795d436f 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManager.java @@ -18,7 +18,7 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; diff --git a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java index f1eb7910cd0..e6dc1e8ed6c 100644 --- a/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java +++ b/plugins/network-elements/elastic-loadbalancer/src/com/cloud/network/lb/ElasticLoadBalancerManagerImpl.java @@ -33,6 +33,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -48,7 +49,6 @@ import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -140,7 +140,7 @@ import com.cloud.vm.dao.NicDao; @Component @Local(value = { ElasticLoadBalancerManager.class }) public class ElasticLoadBalancerManagerImpl implements - ElasticLoadBalancerManager, Manager, VirtualMachineGuru { +ElasticLoadBalancerManager, Manager, VirtualMachineGuru { private static final Logger s_logger = Logger .getLogger(ElasticLoadBalancerManagerImpl.class); @@ -197,7 +197,6 @@ public class ElasticLoadBalancerManagerImpl implements @Inject NicDao _nicDao; - String _name; String _instance; static final private String _elbVmNamePrefix = "l"; @@ -227,7 +226,6 @@ public class ElasticLoadBalancerManagerImpl implements } } - public DomainRouterVO deployLoadBalancerVM(Long networkId, IPAddressVO ipAddr, Long accountId) { NetworkVO network = _networkDao.findById(networkId); DataCenter dc = _dcDao.findById(network.getDataCenterId()); @@ -287,7 +285,6 @@ public class ElasticLoadBalancerManagerImpl implements private void createApplyLoadBalancingRulesCommands( List rules, DomainRouterVO elbVm, Commands cmds, long guestNetworkId) { - LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()]; int i = 0; for (LoadBalancingRule rule : rules) { @@ -299,8 +296,9 @@ public class ElasticLoadBalancerManagerImpl implements String elbIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress() .addr(); int srcPort = rule.getSourcePortStart(); + String uuid = rule.getUuid(); List destinations = rule.getDestinations(); - LoadBalancerTO lb = new LoadBalancerTO(elbIp, srcPort, protocol, algorithm, revoked, false, destinations); + LoadBalancerTO lb = new LoadBalancerTO(uuid, elbIp, srcPort, protocol, algorithm, revoked, false, false, destinations); lbs[i++] = lb; } @@ -338,6 +336,7 @@ public class ElasticLoadBalancerManagerImpl implements return elbVm; } + @Override public boolean applyLoadBalancerRules(Network network, List rules) throws ResourceUnavailableException { @@ -409,8 +408,6 @@ public class ElasticLoadBalancerManagerImpl implements _elasticLbVmOffering.setUniqueName(ServiceOffering.elbVmDefaultOffUniqueName); _elasticLbVmOffering = _serviceOfferingDao.persistSystemServiceOffering(_elasticLbVmOffering); - - String enabled = _configDao.getValue(Config.ElasticLoadBalancerEnabled.key()); _enabled = (enabled == null) ? false: Boolean.parseBoolean(enabled); s_logger.info("Elastic Load balancer enabled: " + _enabled); @@ -432,7 +429,6 @@ public class ElasticLoadBalancerManagerImpl implements _itMgr.registerGuru(VirtualMachine.Type.ElasticLoadBalancerVm, this); } - return true; } @@ -487,8 +483,7 @@ public class ElasticLoadBalancerManagerImpl implements } assert guestNetwork.getState() == Network.State.Implemented || guestNetwork.getState() == Network.State.Setup - || guestNetwork.getState() == Network.State.Implementing - : "Network is not yet fully implemented: "+ guestNetwork; + || guestNetwork.getState() == Network.State.Implementing : "Network is not yet fully implemented: " + guestNetwork; DataCenterDeployment plan = null; DomainRouterVO elbVm = null; @@ -511,7 +506,6 @@ public class ElasticLoadBalancerManagerImpl implements networks.add(new Pair(controlConfig, null)); networks.add(new Pair((NetworkVO) guestNetwork, guestNic)); - VMTemplateVO template = _templateDao.findSystemVMTemplate(dcId); String typeString = "ElasticLoadBalancerVm"; @@ -539,7 +533,6 @@ public class ElasticLoadBalancerManagerImpl implements elbVm = this.start(elbVm, _accountService.getSystemUser(), _accountService.getSystemAccount(), params); } - return elbVm; } finally { _networkDao.releaseFromLockTable(guestNetworkId); @@ -556,7 +549,6 @@ public class ElasticLoadBalancerManagerImpl implements } } - private DomainRouterVO stop(DomainRouterVO elbVm, boolean forced, User user, Account caller) throws ConcurrentOperationException, ResourceUnavailableException { s_logger.debug("Stopping ELB vm " + elbVm); try { @@ -686,7 +678,6 @@ public class ElasticLoadBalancerManagerImpl implements DomainRouterVO elbVm = null; - if (existingLbs == null) { elbVm = findELBVmWithCapacity(network, ipAddr); if (elbVm == null) { @@ -790,7 +781,6 @@ public class ElasticLoadBalancerManagerImpl implements } } - @Override public DomainRouterVO findByName(String name) { if (!VirtualMachineName.isValidSystemVmName(name, _instance, _elbVmNamePrefix)) { @@ -800,19 +790,16 @@ public class ElasticLoadBalancerManagerImpl implements return _routerDao.findById(VirtualMachineName.getSystemVmId(name)); } - @Override public DomainRouterVO findById(long id) { return _routerDao.findById(id); } - @Override public DomainRouterVO persist(DomainRouterVO elbVm) { return _routerDao.persist(elbVm); } - @Override public boolean finalizeVirtualMachineProfile(VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) { DomainRouterVO elbVm = profile.getVirtualMachine(); @@ -894,7 +881,6 @@ public class ElasticLoadBalancerManagerImpl implements return true; } - @Override public boolean finalizeDeployment(Commands cmds, VirtualMachineProfile profile, DeployDestination dest, ReservationContext context) throws ResourceUnavailableException { DomainRouterVO elbVm = profile.getVirtualMachine(); @@ -916,7 +902,6 @@ public class ElasticLoadBalancerManagerImpl implements return true; } - @Override public boolean finalizeStart(VirtualMachineProfile profile, long hostId, Commands cmds, ReservationContext context) { CheckSshAnswer answer = (CheckSshAnswer) cmds.getAnswer("checkSsh"); @@ -928,7 +913,6 @@ public class ElasticLoadBalancerManagerImpl implements return true; } - @Override public boolean finalizeCommandsOnStart(Commands cmds, VirtualMachineProfile profile) { DomainRouterVO elbVm = profile.getVirtualMachine(); @@ -981,7 +965,6 @@ public class ElasticLoadBalancerManagerImpl implements return true; } - @Override public void finalizeStop(VirtualMachineProfile profile, StopAnswer answer) { if (answer != null) { @@ -995,7 +978,6 @@ public class ElasticLoadBalancerManagerImpl implements //TODO: process network usage stats } - @Override public void finalizeExpunge(DomainRouterVO vm) { // no-op @@ -1019,7 +1001,6 @@ public class ElasticLoadBalancerManagerImpl implements throw new UnsupportedOperationException("Plug nic is not supported for vm of type " + vm.getType()); } - @Override public boolean unplugNic(Network network, NicTO nic, VirtualMachineTO vm, ReservationContext context, DeployDestination dest) throws ConcurrentOperationException, ResourceUnavailableException { 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/api/commands/AddExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java index 3fa61167efa..69a21fc184c 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddExternalLoadBalancerCmd.java @@ -17,23 +17,23 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.user.Account; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds F5 external load balancer appliance.", responseObject = ExternalLoadBalancerResponse.class) +@APICommand(name = "addExternalLoadBalancer", description="Adds F5 external load balancer appliance.", responseObject = ExternalLoadBalancerResponse.class) @Deprecated // API supported only for backward compatibility. public class AddExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddExternalLoadBalancerCmd.class.getName()); @@ -43,8 +43,8 @@ public class AddExternalLoadBalancerCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external load balancer appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external load balancer appliance.") private Long zoneId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external load balancer appliance.") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java index 13c443e7cf0..a5616e0ee73 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/AddF5LoadBalancerCmd.java @@ -17,16 +17,11 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +34,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="Adds a F5 BigIP load balancer device") +@APICommand(name = "addF5LoadBalancer", responseObject=F5LoadBalancerResponse.class, description="Adds a F5 BigIP load balancer device") public class AddF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddF5LoadBalancerCmd.class.getName()); @@ -50,8 +45,8 @@ public class AddF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the F5 load balancer appliance.") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java index 9f5217c3280..e796b57cc41 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ConfigureF5LoadBalancerCmd.java @@ -17,16 +17,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +33,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="configures a F5 load balancer device") +@APICommand(name = "configureF5LoadBalancer", responseObject=F5LoadBalancerResponse.class, description="configures a F5 load balancer device") public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureF5LoadBalancerCmd.class.getName()); @@ -50,8 +44,8 @@ public class ConfigureF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="F5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required=true, description="F5 load balancer device ID") private Long lbDeviceId; @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the device, Capacity will be interpreted as number of networks device can handle") diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java index 2c89a4a6a9d..d3015712596 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteExternalLoadBalancerCmd.java @@ -17,21 +17,17 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.Account; -@Implementation(description="Deletes a F5 external load balancer appliance added in a zone.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteExternalLoadBalancer", description="Deletes a F5 external load balancer appliance added in a zone.", responseObject = SuccessResponse.class) @Deprecated // API supported for backward compatibility. public class DeleteExternalLoadBalancerCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteExternalLoadBalancerCmd.class.getName()); @@ -41,8 +37,8 @@ public class DeleteExternalLoadBalancerCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the external loadbalancer appliance.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the external loadbalancer appliance.") private Long id; /////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java index 959819b1588..8b53d70f76d 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/DeleteF5LoadBalancerCmd.java @@ -19,16 +19,16 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseAsyncCmd; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -39,7 +39,7 @@ import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a F5 load balancer device") +@APICommand(name = "deleteF5LoadBalancer", responseObject=SuccessResponse.class, description=" delete a F5 load balancer device") public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteF5LoadBalancerCmd.class.getName()); private static final String s_name = "deletef5loadbalancerresponse"; @@ -49,8 +49,8 @@ public class DeleteF5LoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required=true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java index acb71b06c0a..3ee8d4865a5 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListExternalLoadBalancersCmd.java @@ -20,21 +20,17 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.host.Host; import com.cloud.network.element.F5ExternalLoadBalancerElementService; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; -@Implementation(description="Lists F5 external load balancer appliances added in a zone.", responseObject = HostResponse.class) +@APICommand(name = "listExternalLoadBalancers", description="Lists F5 external load balancer appliances added in a zone.", responseObject = HostResponse.class) @Deprecated // API supported for backward compatibility. public class ListExternalLoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListExternalLoadBalancersCmd.class.getName()); @@ -44,8 +40,8 @@ public class ListExternalLoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneRespones.class, + description="zone Id") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java index f2fa071b53e..4ec98f02d58 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancerNetworksCmd.java @@ -22,16 +22,15 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +40,7 @@ import com.cloud.network.Network; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a F5 load balancer device") +@APICommand(name = "listF5LoadBalancerNetworks", responseObject=NetworkResponse.class, description="lists network that are using a F5 load balancer device") public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancerNetworksCmd.class.getName()); @@ -52,8 +51,8 @@ public class ListF5LoadBalancerNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="f5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + required = true, description="f5 load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java index fe4cb67bd01..c03d55abc0a 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java +++ b/plugins/network-elements/f5/src/com/cloud/api/commands/ListF5LoadBalancersCmd.java @@ -20,18 +20,13 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.F5LoadBalancerResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -41,7 +36,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.element.F5ExternalLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=F5LoadBalancerResponse.class, description="lists F5 load balancer devices") +@APICommand(name = "listF5LoadBalancers", responseObject=F5LoadBalancerResponse.class, description="lists F5 load balancer devices") public class ListF5LoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListF5LoadBalancersCmd.class.getName()); private static final String s_name = "listf5loadbalancerresponse"; @@ -51,12 +46,12 @@ public class ListF5LoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, description="f5 load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = F5LoadBalancerResponse.class, + description="f5 load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java b/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java index dbb962fff03..19e67260b90 100644 --- a/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java +++ b/plugins/network-elements/f5/src/com/cloud/api/response/F5LoadBalancerResponse.java @@ -16,24 +16,27 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.EntityReference; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalLoadBalancerDeviceVO; +@EntityReference(value=ExternalLoadBalancerDeviceVO.class) public class F5LoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_ID) @Param(description="device id of the F5 load balancer") - private IdentityProxy id = new IdentityProxy("external_load_balancer_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this F5 device belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -43,24 +46,21 @@ public class F5LoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) @Param(description="true if device is dedicated for an account") private Boolean dedicatedLoadBalancer; - @SerializedName(ApiConstants.INLINE) @Param(description="true if device is inline with firewall device") - private Boolean inlineLoadBalancer; - @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the load balancer") private String privateInterface; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external load balancer") private String ipAddress; - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { @@ -83,10 +83,6 @@ public class F5LoadBalancerResponse extends BaseResponse { this.dedicatedLoadBalancer = isDedicated; } - public void setInlineMode(boolean inline) { - this.inlineLoadBalancer = inline; - } - public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } 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 bcb7c8bb412..33fae86591b 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 @@ -28,6 +28,7 @@ import javax.inject.Inject; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddExternalLoadBalancerCmd; import com.cloud.api.commands.AddF5LoadBalancerCmd; import com.cloud.api.commands.ConfigureF5LoadBalancerCmd; @@ -57,7 +58,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -66,6 +67,7 @@ import com.cloud.network.NetworkExternalLoadBalancerVO; 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.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -80,7 +82,7 @@ import com.cloud.network.rules.LbStickinessMethod; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.offering.NetworkOffering; import com.cloud.resource.ServerResource; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -119,7 +121,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; } @@ -168,13 +170,14 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } @Override - public boolean destroy(Network config) { + public boolean destroy(Network config, ReservationContext context) { return true; } @Override public boolean validateLBRule(Network network, LoadBalancingRule rule) { - return true; + String algo = rule.getAlgorithm(); + return (algo.equals("roundrobin") || algo.equals("leastconn")); } @Override @@ -208,6 +211,9 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional"); + // Support inline mode with firewall + lbCapabilities.put(Capability.InlineMode, "true"); + LbStickinessMethod method; List methodList = new ArrayList(); method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http"); @@ -438,9 +444,12 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan Host lbHost = _hostDao.findById(lbDeviceVO.getHostId()); Map lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId()); - response.setId(lbDeviceVO.getId()); + response.setId(lbDeviceVO.getUuid()); response.setIpAddress(lbHost.getPrivateIpAddress()); - response.setPhysicalNetworkId(lbDeviceVO.getPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setDeviceName(lbDeviceVO.getDeviceName()); @@ -450,7 +459,6 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan } else { response.setDeviceCapacity(lbDeviceVO.getCapacity()); } - response.setInlineMode(lbDeviceVO.getIsInLineMode()); response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice()); response.setProvider(lbDeviceVO.getProviderName()); response.setDeviceState(lbDeviceVO.getState().name()); @@ -471,6 +479,15 @@ public class F5ExternalLoadBalancerElement extends ExternalLoadBalancerDeviceMan @Override public IpDeployer getIpDeployer(Network network) { + ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network); + if (lbDevice == null) { + s_logger.error("Cannot find external load balanacer for network " + network.getName()); + s_logger.error("Make F5 as dummy ip deployer, since we likely met this when clean up resource after shutdown network"); + return this; + } + if (_networkManager.isNetworkInlineMode(network)) { + return getIpDeployerForInlineMode(network); + } return this; } } diff --git a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java index 24c76753b47..951bc3cc3b1 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java +++ b/plugins/network-elements/f5/src/com/cloud/network/element/F5ExternalLoadBalancerElementService.java @@ -30,7 +30,7 @@ import com.cloud.api.response.F5LoadBalancerResponse; import com.cloud.host.Host; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.Network; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.utils.component.PluggableService; @SuppressWarnings("deprecation") diff --git a/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java b/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java index a45dd92ca98..c9c3711bfc1 100644 --- a/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java +++ b/plugins/network-elements/f5/src/com/cloud/network/resource/F5BigIpResource.java @@ -119,7 +119,6 @@ public class F5BigIpResource implements ServerResource { private String _privateInterface; private Integer _numRetries; private String _guid; - private boolean _inline; private Interfaces _interfaces; private LocalLBVirtualServerBindingStub _virtualServerApi; @@ -180,8 +179,6 @@ public class F5BigIpResource implements ServerResource { throw new ConfigurationException("Unable to find the guid"); } - _inline = Boolean.parseBoolean((String) params.get("inline")); - login(); return true; @@ -292,45 +289,48 @@ public class F5BigIpResource implements ServerResource { } private synchronized Answer execute(IpAssocCommand cmd, int numRetries) { - String[] results = new String[cmd.getIpAddresses().length]; - int i = 0; - try { - IpAddressTO[] ips = cmd.getIpAddresses(); - for (IpAddressTO ip : ips) { - long guestVlanTag = Long.valueOf(ip.getVlanId()); - String vlanSelfIp = _inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); - String vlanNetmask = ip.getVlanNetmask(); - - // Delete any existing guest VLAN with this tag, self IP, and netmask - deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); - - if (ip.isAdd()) { - // Add a new guest VLAN - addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask); + String[] results = new String[cmd.getIpAddresses().length]; + int i = 0; + try { + IpAddressTO[] ips = cmd.getIpAddresses(); + for (IpAddressTO ip : ips) { + long guestVlanTag = Long.valueOf(ip.getVlanId()); + // It's a hack, using isOneToOneNat field for indicate if it's inline or not + boolean inline = ip.isOneToOneNat(); + String vlanSelfIp = inline ? tagAddressWithRouteDomain(ip.getVlanGateway(), guestVlanTag) : ip.getVlanGateway(); + String vlanNetmask = ip.getVlanNetmask(); + + // Delete any existing guest VLAN with this tag, self IP, and netmask + deleteGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); + + if (ip.isAdd()) { + // Add a new guest VLAN + addGuestVlan(guestVlanTag, vlanSelfIp, vlanNetmask, inline); + } + + saveConfiguration(); + results[i++] = ip.getPublicIp() + " - success"; } - - saveConfiguration(); - results[i++] = ip.getPublicIp() + " - success"; - } - - } catch (ExecutionException e) { - s_logger.error("Failed to execute IPAssocCommand due to " + e); - - if (shouldRetry(numRetries)) { - return retry(cmd, numRetries); - } else { - results[i++] = IpAssocAnswer.errorResult; - } - } - - return new IpAssocAnswer(cmd, results); - } + + } catch (ExecutionException e) { + s_logger.error("Failed to execute IPAssocCommand due to " + e); + + if (shouldRetry(numRetries)) { + return retry(cmd, numRetries); + } else { + results[i++] = IpAssocAnswer.errorResult; + } + } + + return new IpAssocAnswer(cmd, results); + } private synchronized Answer execute(LoadBalancerConfigCommand cmd, int numRetries) { try { long guestVlanTag = Long.parseLong(cmd.getAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG)); LoadBalancerTO[] loadBalancers = cmd.getLoadBalancers(); for (LoadBalancerTO loadBalancer : loadBalancers) { + boolean inline = loadBalancer.isInline(); LbProtocol lbProtocol; try { if (loadBalancer.getProtocol() == null) { @@ -351,7 +351,7 @@ public class F5BigIpResource implements ServerResource { throw new ExecutionException("Got invalid algorithm: " + loadBalancer.getAlgorithm()); } - String srcIp = _inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); + String srcIp = inline ? tagAddressWithRouteDomain(loadBalancer.getSrcIp(), guestVlanTag) : loadBalancer.getSrcIp(); int srcPort = loadBalancer.getSrcPort(); String virtualServerName = genVirtualServerName(lbProtocol, srcIp, srcPort); @@ -363,6 +363,8 @@ public class F5BigIpResource implements ServerResource { } } + // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members + deleteVirtualServerAndDefaultPool(virtualServerName); if (!loadBalancer.isRevoked() && destinationsToAdd) { // Add the pool addPool(virtualServerName, lbAlgorithm); @@ -371,20 +373,14 @@ public class F5BigIpResource implements ServerResource { List activePoolMembers = new ArrayList(); for (DestinationTO destination : loadBalancer.getDestinations()) { if (!destination.isRevoked()) { - String destIp = _inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); + String destIp = inline ? tagAddressWithRouteDomain(destination.getDestIp(), guestVlanTag) : destination.getDestIp(); addPoolMember(virtualServerName, destIp, destination.getDestPort()); activePoolMembers.add(destIp + "-" + destination.getDestPort()); } } - // Delete any pool members that aren't in the current list of destinations - deleteInactivePoolMembers(virtualServerName, activePoolMembers); - // Add the virtual server addVirtualServer(virtualServerName, lbProtocol, srcIp, srcPort, loadBalancer.getStickinessPolicies()); - } else { - // Delete the virtual server with this protocol, source IP, and source port, along with its default pool and all pool members - deleteVirtualServerAndDefaultPool(virtualServerName); } } @@ -421,7 +417,7 @@ public class F5BigIpResource implements ServerResource { } } - private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { + private void addGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { try { String vlanName = genVlanName(vlanTag); List allVlans = getVlans(); @@ -444,7 +440,7 @@ public class F5BigIpResource implements ServerResource { } } - if (_inline) { + if (inline) { List allRouteDomains = getRouteDomains(); if (!allRouteDomains.contains(vlanTag)) { long[] routeDomainIds = genLongArray(vlanTag); @@ -481,7 +477,7 @@ public class F5BigIpResource implements ServerResource { } - private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { + private void deleteGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask, boolean inline) throws ExecutionException { try { // Delete all virtual servers and pools that use this guest VLAN deleteVirtualServersInGuestVlan(vlanSelfIp, vlanNetmask); @@ -496,7 +492,7 @@ public class F5BigIpResource implements ServerResource { } } - if (_inline) { + if (inline) { List allRouteDomains = getRouteDomains(); if (allRouteDomains.contains(vlanTag)) { s_logger.debug("Deleting route domain " + vlanTag); @@ -969,9 +965,7 @@ public class F5BigIpResource implements ServerResource { for (LocalLBVirtualServerVirtualServerStatisticEntry entry : stats.getStatistics()) { String virtualServerIp = entry.getVirtual_server().getAddress(); - if (_inline) { - virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); - } + virtualServerIp = stripRouteDomainFromAddress(virtualServerIp); long[] bytesSentAndReceived = answer.ipBytes.get(virtualServerIp); 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/api/commands/AddExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java index 9b55af644ac..cda27fb8960 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddExternalFirewallCmd.java @@ -16,23 +16,23 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.user.Account; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "addExternalFirewall", description="Adds an external firewall appliance", responseObject = ExternalFirewallResponse.class) public class AddExternalFirewallCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddExternalFirewallCmd.class.getName()); private static final String s_name = "addexternalfirewallresponse"; @@ -41,8 +41,8 @@ public class AddExternalFirewallCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the external firewall appliance.") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java index 6872c8eabfe..a2ad4e5ce2b 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/AddSrxFirewallCmd.java @@ -16,16 +16,16 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +38,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="Adds a SRX firewall device") +@APICommand(name = "addSrxFirewall", responseObject=SrxFirewallResponse.class, description="Adds a SRX firewall device") public class AddSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddSrxFirewallCmd.class.getName()); private static final String s_name = "addsrxfirewallresponse"; @@ -48,8 +48,8 @@ public class AddSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the SRX appliance.") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java index d5d90ff1196..482fcc8c0c7 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ConfigureSrxFirewallCmd.java @@ -18,14 +18,13 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -38,7 +37,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="Configures a SRX firewall device") +@APICommand(name = "configureSrxFirewall", responseObject=SrxFirewallResponse.class, description="Configures a SRX firewall device") public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureSrxFirewallCmd.class.getName()); @@ -49,8 +48,8 @@ public class ConfigureSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, required=true, description="SRX firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required=true, description="SRX firewall device ID") private Long fwDeviceId; @Parameter(name=ApiConstants.FIREWALL_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the firewall device, Capacity will be interpreted as number of networks device can handle") diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java index 8a0af1f05bb..5cdc9e3c92c 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteExternalFirewallCmd.java @@ -16,21 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.Account; -@Implementation(description="Deletes an external firewall appliance.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteExternalFirewall", description="Deletes an external firewall appliance.", responseObject = SuccessResponse.class) public class DeleteExternalFirewallCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteExternalFirewallCmd.class.getName()); private static final String s_name = "deleteexternalfirewallresponse"; @@ -39,8 +39,8 @@ public class DeleteExternalFirewallCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the external firewall appliance.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the external firewall appliance.") private Long id; /////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java index d741c0ca3b9..1dc792a723a 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/DeleteSrxFirewallCmd.java @@ -18,15 +18,15 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.SrxFirewallResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -37,7 +37,7 @@ import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a SRX firewall device") +@APICommand(name = "deleteSrxFirewall", responseObject=SuccessResponse.class, description=" delete a SRX firewall device") public class DeleteSrxFirewallCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteSrxFirewallCmd.class.getName()); private static final String s_name = "deletesrxfirewallresponse"; @@ -47,8 +47,8 @@ public class DeleteSrxFirewallCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, required=true, description="srx firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required=true, description="srx firewall device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java index 111df728095..65aa92ba818 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListExternalFirewallsCmd.java @@ -19,20 +19,21 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.host.Host; import com.cloud.network.element.JuniperSRXFirewallElementService; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; -@Implementation(description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "listExternalFirewalls", description="List external firewall appliances.", responseObject = ExternalFirewallResponse.class) public class ListExternalFirewallsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); private static final String s_name = "listexternalfirewallsresponse"; @@ -41,8 +42,8 @@ public class ListExternalFirewallsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="zone Id") private long zoneId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java index 43a5dff0508..9c2b3962a6f 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallNetworksCmd.java @@ -19,18 +19,13 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import com.cloud.api.response.SrxFirewallResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -40,7 +35,7 @@ import com.cloud.network.Network; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using SRX firewall device") +@APICommand(name = "listSrxFirewallNetworks", responseObject=NetworkResponse.class, description="lists network that are using SRX firewall device") public class ListSrxFirewallNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSrxFirewallNetworksCmd.class.getName()); @@ -51,8 +46,8 @@ public class ListSrxFirewallNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + required = true, description="netscaler load balancer device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java index a4f68566a25..6508cc83c7d 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/commands/ListSrxFirewallsCmd.java @@ -19,17 +19,12 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.SrxFirewallResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -40,7 +35,7 @@ import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.element.JuniperSRXFirewallElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SrxFirewallResponse.class, description="lists SRX firewall devices in a physical network") +@APICommand(name = "listSrxFirewalls", responseObject=SrxFirewallResponse.class, description="lists SRX firewall devices in a physical network") public class ListSrxFirewallsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListSrxFirewallsCmd.class.getName()); @@ -51,12 +46,12 @@ public class ListSrxFirewallsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_firewall_devices") - @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.LONG, description="SRX firewall device ID") + @Parameter(name=ApiConstants.FIREWALL_DEVICE_ID, type=CommandType.UUID, entityType = SrxFirewallResponse.class, + description="SRX firewall device ID") private Long fwDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java b/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java index 08242bdb372..56aab70f2f3 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/api/response/SrxFirewallResponse.java @@ -16,26 +16,29 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalFirewallDeviceVO; +@EntityReference(value=ExternalFirewallDeviceVO.class) @SuppressWarnings("unused") public class SrxFirewallResponse extends BaseResponse { @SerializedName(ApiConstants.FIREWALL_DEVICE_ID) @Param(description="device id of the SRX firewall") - private IdentityProxy id = new IdentityProxy("external_firewall_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this SRX firewall belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.FIREWALL_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.FIREWALL_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -43,7 +46,7 @@ public class SrxFirewallResponse extends BaseResponse { private Long deviceCapacity; @SerializedName(ApiConstants.ZONE_ID) @Param(description="the zone ID of the external firewall") - private IdentityProxy zoneId = new IdentityProxy("data_center"); + private String zoneId; @SerializedName(ApiConstants.IP_ADDRESS) @Param(description="the management IP address of the external firewall") private String ipAddress; @@ -72,12 +75,12 @@ public class SrxFirewallResponse extends BaseResponse { @SerializedName(ApiConstants.TIMEOUT) @Param(description="the timeout (in seconds) for requests to the external firewall") private String timeout; - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { 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 6ff46c58aab..ba0d7a845f9 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 @@ -28,6 +28,7 @@ import javax.inject.Inject; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddExternalFirewallCmd; import com.cloud.api.commands.AddSrxFirewallCmd; import com.cloud.api.commands.ConfigureSrxFirewallCmd; @@ -57,7 +58,7 @@ import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.ExternalFirewallDeviceManagerImpl; import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; @@ -65,6 +66,7 @@ import com.cloud.network.Network.Service; import com.cloud.network.NetworkExternalFirewallVO; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; @@ -78,10 +80,11 @@ import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.resource.JuniperSrxResource; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ServerResource; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.utils.NumbersUtil; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.vm.NicProfile; @@ -92,7 +95,7 @@ import com.cloud.vm.VirtualMachineProfile; @Component @Local(value = NetworkElement.class) public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceManagerImpl implements SourceNatServiceProvider, FirewallServiceProvider, - PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService { + PortForwardingServiceProvider, RemoteAccessVPNServiceProvider, IpDeployer, JuniperSRXFirewallElementService, StaticNatServiceProvider { private static final Logger s_logger = Logger.getLogger(JuniperSRXExternalFirewallElement.class); @@ -127,7 +130,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; } @@ -205,7 +209,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan } @Override - public boolean destroy(Network config) { + public boolean destroy(Network config, ReservationContext context) { return true; } @@ -269,7 +273,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan // Set capabilities for Firewall service Map firewallCapabilities = new HashMap(); - firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp"); + firewallCapabilities.put(Capability.SupportedProtocols, "tcp,udp,icmp"); firewallCapabilities.put(Capability.MultipleIps, "true"); firewallCapabilities.put(Capability.TrafficStatistics, "per public ip"); capabilities.put(Service.Firewall, firewallCapabilities); @@ -303,7 +307,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan return false; } - return applyFirewallRules(network, rules); + return applyPortForwardingRules(network, rules); } @Override @@ -330,7 +334,7 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan @Override public boolean canEnableIndividualServices() { - return false; + return true; } @Override @@ -510,8 +514,11 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan Map fwDetails = _hostDetailDao.findDetails(fwDeviceVO.getHostId()); Host fwHost = _hostDao.findById(fwDeviceVO.getHostId()); - response.setId(fwDeviceVO.getId()); - response.setPhysicalNetworkId(fwDeviceVO.getPhysicalNetworkId()); + response.setId(fwDeviceVO.getUuid()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(fwDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setDeviceName(fwDeviceVO.getDeviceName()); if (fwDeviceVO.getCapacity() == 0) { long defaultFwCapacity = NumbersUtil.parseLong(_configDao.getValue(Config.DefaultExternalFirewallCapacity.key()), 50); @@ -535,6 +542,10 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan @Override public boolean verifyServicesCombination(Set services) { + if (!services.contains(Service.Firewall)) { + s_logger.warn("SRX must be used as Firewall Service Provider in the network"); + return false; + } return true; } @@ -548,4 +559,12 @@ public class JuniperSRXExternalFirewallElement extends ExternalFirewallDeviceMan // return true, as IP will be associated as part of static NAT/port forwarding rule configuration return true; } + + @Override + public boolean applyStaticNats(Network config, List rules) throws ResourceUnavailableException { + if (!canHandle(config, Service.StaticNat)) { + return false; + } + return applyStaticNatRules(config, rules); + } } diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java index 6d07d303128..d5f53843ca1 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/element/JuniperSRXFirewallElementService.java @@ -30,7 +30,7 @@ import com.cloud.api.response.SrxFirewallResponse; import com.cloud.host.Host; import com.cloud.network.ExternalFirewallDeviceVO; import com.cloud.network.Network; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.utils.component.PluggableService; public interface JuniperSRXFirewallElementService extends PluggableService { diff --git a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java index ebb3de6c850..f823ab8af4f 100644 --- a/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java +++ b/plugins/network-elements/juniper-srx/src/com/cloud/network/resource/JuniperSrxResource.java @@ -55,6 +55,7 @@ import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; +import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; @@ -64,6 +65,7 @@ import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.host.Host; +import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.resource.ServerResource; import com.cloud.utils.NumbersUtil; @@ -75,7 +77,6 @@ public class JuniperSrxResource implements ServerResource { private String _name; private String _zoneId; - private String _physicalNetworkId; private String _ip; private String _username; private String _password; @@ -89,6 +90,7 @@ public class JuniperSrxResource implements ServerResource { private Integer _timeoutInSeconds; private String _publicZone; private String _privateZone; + private String _publicZoneInputFilterName; private String _publicInterface; private String _usageInterface; private String _privateInterface; @@ -159,6 +161,9 @@ public class JuniperSrxResource implements ServerResource { ACCESS_PROFILE_ADD("access-profile-add.xml"), ACCESS_PROFILE_GETONE("access-profile-getone.xml"), ACCESS_PROFILE_GETALL("access-profile-getall.xml"), + FIREWALL_FILTER_TERM_ADD("firewall-filter-term-add.xml"), + FIREWALL_FILTER_TERM_GETONE("firewall-filter-term-getone.xml"), + TEMPLATE_ENTRY("template-entry.xml"), OPEN_CONFIGURATION("open-configuration.xml"), CLOSE_CONFIGURATION("close-configuration.xml"), COMMIT("commit.xml"), @@ -231,12 +236,74 @@ public class JuniperSrxResource implements ServerResource { } } + public class FirewallFilterTerm { + private String name; + private List sourceCidrs; + private String destIp; + private String portRange; + private String protocol; + private String icmpType; + private String icmpCode; + private String countName; + + private FirewallFilterTerm(String name, List sourceCidrs, String destIp, String protocol, Integer startPort, Integer endPort, + Integer icmpType, Integer icmpCode, String countName) { + this.name = name; + this.sourceCidrs = sourceCidrs; + this.destIp = destIp; + this.protocol = protocol; + + if (protocol.equals("tcp") || protocol.equals("udp")) { + this.portRange = String.valueOf(startPort) + "-" + String.valueOf(endPort); + } else if (protocol.equals("icmp")) { + this.icmpType = String.valueOf(icmpType); + this.icmpCode = String.valueOf(icmpCode); + } else { + assert protocol.equals("any"); + } + this.countName = countName; + + } + + public String getName() { + return name; + } + + public List getSourceCidrs() { + return sourceCidrs; + } + + public String getDestIp() { + return destIp; + } + + public String getPortRange() { + return portRange; + } + + public String getProtocol() { + return protocol; + } + + public String getIcmpType() { + return icmpType; + } + + public String getIcmpCode() { + return icmpCode; + } + + public String getCountName() { + return countName; + } + } + private enum SrxCommand { LOGIN, OPEN_CONFIGURATION, CLOSE_CONFIGURATION, COMMIT, ROLLBACK, CHECK_IF_EXISTS, CHECK_IF_IN_USE, ADD, DELETE, GET_ALL; } private enum Protocol { - tcp, udp, any; + tcp, udp, icmp, any; } private enum RuleMatchCondition { @@ -277,6 +344,8 @@ public class JuniperSrxResource implements ServerResource { return execute((SetStaticNatRulesCommand) cmd); } else if (cmd instanceof SetPortForwardingRulesCommand) { return execute((SetPortForwardingRulesCommand) cmd); + } else if (cmd instanceof SetFirewallRulesCommand) { + return execute((SetFirewallRulesCommand) cmd); } else if (cmd instanceof ExternalNetworkResourceUsageCommand) { return execute((ExternalNetworkResourceUsageCommand) cmd); } else if (cmd instanceof RemoteAccessVpnCfgCommand) { @@ -300,11 +369,6 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to find zone"); } - _physicalNetworkId = (String) params.get("physicalNetworkId"); - if (_physicalNetworkId == null) { - throw new ConfigurationException("Unable to find physical network id in the configuration parameters"); - } - _ip = (String) params.get("ip"); if (_ip == null) { throw new ConfigurationException("Unable to find IP"); @@ -325,8 +389,6 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to find public interface."); } - _usageInterface = (String) params.get("usageinterface"); - _privateInterface = (String) params.get("privateinterface"); if (_privateInterface == null) { throw new ConfigurationException("Unable to find private interface."); @@ -364,6 +426,8 @@ public class JuniperSrxResource implements ServerResource { throw new ConfigurationException("Unable to open a connection to the SRX."); } + _publicZoneInputFilterName = _publicZone; + _usageFilterVlanInput = new UsageFilter("vlan-input", null, "vlan-input"); _usageFilterVlanOutput = new UsageFilter("vlan-output", null, "vlan-output"); _usageFilterIPInput = new UsageFilter(_publicZone, "destination-address", "-i"); @@ -712,6 +776,50 @@ public class JuniperSrxResource implements ServerResource { s_logger.debug(msg); } + + /* security policies */ + private synchronized Answer execute(SetFirewallRulesCommand cmd) { + refreshSrxConnection(); + return execute(cmd, _numRetries); + } + + private Answer execute(SetFirewallRulesCommand cmd, int numRetries) { + FirewallRuleTO[] rules = cmd.getRules(); + try { + openConfiguration(); + + for (FirewallRuleTO rule : rules) { + int startPort = 0, endPort = 0; + if (rule.getSrcPortRange() != null) { + startPort = rule.getSrcPortRange()[0]; + endPort = rule.getSrcPortRange()[1]; + } + FirewallFilterTerm term = new FirewallFilterTerm(genIpIdentifier(rule.getSrcIp()) + "-" + String.valueOf(rule.getId()), rule.getSourceCidrList(), + rule.getSrcIp(), rule.getProtocol(), startPort, endPort, + rule.getIcmpType(), rule.getIcmpCode(), genIpIdentifier(rule.getSrcIp()) + _usageFilterIPInput.getCounterIdentifier()); + if (!rule.revoked()) { + manageFirewallFilter(SrxCommand.ADD, term, _publicZoneInputFilterName); + } else { + manageFirewallFilter(SrxCommand.DELETE, term, _publicZoneInputFilterName); + } + } + + commitConfiguration(); + return new Answer(cmd); + } catch (ExecutionException e) { + s_logger.error(e); + closeConfiguration(); + + if (numRetries > 0 && refreshSrxConnection()) { + int numRetriesRemaining = numRetries - 1; + s_logger.debug("Retrying SetFirewallRulesCommand. Number of retries remaining: " + numRetriesRemaining); + return execute(cmd, numRetriesRemaining); + } else { + return new Answer(cmd, e); + } + } + } + /* * Static NAT */ @@ -766,7 +874,6 @@ public class JuniperSrxResource implements ServerResource { private void addStaticNatRule(Long publicVlanTag, String publicIp, String privateIp, List rules) throws ExecutionException { manageProxyArp(SrxCommand.ADD, publicVlanTag, publicIp); manageStaticNatRule(SrxCommand.ADD, publicIp, privateIp); - manageUsageFilter(SrxCommand.ADD, _usageFilterIPInput, publicIp, null, genIpFilterTermName(publicIp)); manageAddressBookEntry(SrxCommand.ADD, _privateZone, privateIp, null); // Add a new security policy with the current set of applications @@ -778,7 +885,6 @@ public class JuniperSrxResource implements ServerResource { private void removeStaticNatRule(Long publicVlanTag, String publicIp, String privateIp) throws ExecutionException { manageStaticNatRule(SrxCommand.DELETE, publicIp, privateIp); manageProxyArp(SrxCommand.DELETE, publicVlanTag, publicIp); - manageUsageFilter(SrxCommand.DELETE, _usageFilterIPInput, publicIp, null, genIpFilterTermName(publicIp)); // Remove any existing security policy and clean up applications removeSecurityPolicyAndApplications(SecurityPolicyType.STATIC_NAT, privateIp); @@ -2781,6 +2887,108 @@ public class JuniperSrxResource implements ServerResource { } } + private String genNameValueEntry(String name, String value) { + String xml = SrxXml.TEMPLATE_ENTRY.getXml(); + xml = replaceXmlValue(xml, "name", name); + xml = replaceXmlValue(xml, "value", value); + return xml; + } + + private String genMultipleEntries(String name, List values) { + String result = ""; + for (String value : values) { + result = result + genNameValueEntry(name, value); + } + return result; + } + + private String genPortRangeEntry(String protocol, String portRange) { + String result = ""; + result = result + genNameValueEntry("protocol", protocol); + result = result + genNameValueEntry("destination-port", portRange); + return result; + } + + private String genIcmpEntries(String icmpType, String icmpCode) { + String result = ""; + result = result + genNameValueEntry("protocol", "icmp"); + if (icmpType.equals("-1")) { + result = result + genNameValueEntry("icmp-type", "0-255"); + } else { + result = result + genNameValueEntry("icmp-type", icmpType); + } + if (icmpCode.equals("-1")) { + result = result + genNameValueEntry("icmp-code", "0-255"); + } else { + result = result + genNameValueEntry("icmp-code", icmpCode); + } + return result; + } + + private boolean manageFirewallFilter(SrxCommand command, FirewallFilterTerm term, String filterName) throws ExecutionException { + String xml; + + switch(command) { + + case CHECK_IF_EXISTS: + xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); + xml = setDelete(xml, false); + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + return sendRequestAndCheckResponse(command, xml, "name", term.getName()); + + case ADD: + if (manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { + return true; + } + + xml = SrxXml.FIREWALL_FILTER_TERM_ADD.getXml(); + + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + xml = replaceXmlValue(xml, "source-address-entries", genMultipleEntries("source-address", term.getSourceCidrs())); + xml = replaceXmlValue(xml, "dest-ip-address", term.getDestIp()); + + String protocol = term.getProtocol(); + if (protocol.equals("tcp") || protocol.equals("udp")) { + xml = replaceXmlValue(xml, "protocol-options", genPortRangeEntry(protocol, term.getPortRange())); + } else if (protocol.equals("icmp")) { + xml = replaceXmlValue(xml, "protocol-options", genIcmpEntries(term.getIcmpType(), term.getIcmpCode())); + } else { + assert protocol.equals("any"); + xml = replaceXmlValue(xml, "protocol-options", ""); + } + xml = replaceXmlValue(xml, "count-name", term.getCountName()); + + if (!sendRequestAndCheckResponse(command, xml)) { + throw new ExecutionException("Failed to add firewall filter: " + term.getName()); + } else { + return true; + } + + case DELETE: + if (!manageFirewallFilter(SrxCommand.CHECK_IF_EXISTS, term, filterName)) { + return true; + } + + xml = SrxXml.FIREWALL_FILTER_TERM_GETONE.getXml(); + xml = setDelete(xml, true); + xml = replaceXmlValue(xml, "filter-name", filterName); + xml = replaceXmlValue(xml, "term-name", term.getName()); + + if (!sendRequestAndCheckResponse(command, xml)) { + throw new ExecutionException("Failed to delete firewall filter: " + term.getName()); + } else { + return true; + } + + default: + s_logger.debug("Unrecognized command."); + return false; + + } + } + /* * Usage */ @@ -2913,6 +3121,10 @@ public class JuniperSrxResource implements ServerResource { } UsageFilter filter = getUsageFilter(counterName); + if (filter == null) { + s_logger.debug("Failed to parse counter name in usage answer: " + counterName); + return; + } String usageAnswerKey = getUsageAnswerKey(filter, counterName); Map bytesMap = getBytesMap(answer, filter, usageAnswerKey); updateBytesMap(bytesMap, filter, usageAnswerKey, byteCount); @@ -2981,6 +3193,11 @@ public class JuniperSrxResource implements ServerResource { } private boolean checkResponse(String xmlResponse, boolean errorKeyAndValue, String key, String value) { + if (xmlResponse == null) { + s_logger.error("Failed to communicate with SRX!"); + return false; + } + if (!xmlResponse.contains("authentication-response")) { s_logger.debug("Checking response: " + xmlResponse); } else { 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/api/commands/AddNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java index 1a88de2cb6c..9d902975723 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/AddNetscalerLoadBalancerCmd.java @@ -15,15 +15,10 @@ package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -36,7 +31,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="Adds a netscaler load balancer device") +@APICommand(name = "addNetscalerLoadBalancer", responseObject=NetscalerLoadBalancerResponse.class, description="Adds a netscaler load balancer device") public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(AddNetscalerLoadBalancerCmd.class.getName()); @@ -47,8 +42,8 @@ public class AddNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.URL, type=CommandType.STRING, required = true, description="URL of the netscaler load balancer appliance.") diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java index de1a7c84ef5..e0ec73ad501 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ConfigureNetscalerLoadBalancerCmd.java @@ -16,17 +16,11 @@ package com.cloud.api.commands; import java.util.List; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PodResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; @@ -39,7 +33,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="configures a netscaler load balancer device") +@APICommand(name = "configureNetscalerLoadBalancer", responseObject=NetscalerLoadBalancerResponse.class, description="configures a netscaler load balancer device") public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(ConfigureNetscalerLoadBalancerCmd.class.getName()); @@ -50,8 +44,8 @@ public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="Netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + required=true, description="Netscaler load balancer device ID") private Long lbDeviceId; @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY, type=CommandType.LONG, required=false, description="capacity of the device, Capacity will be interpreted as number of networks device can handle") @@ -63,8 +57,8 @@ public class ConfigureNetscalerLoadBalancerCmd extends BaseAsyncCmd { @Parameter (name=ApiConstants.INLINE, type=CommandType.BOOLEAN, required=false, description="true if netscaler load balancer is intended to be used in in-line with firewall, false if netscaler load balancer will side-by-side with firewall") private Boolean inline; - @IdentityMapper(entityTableName="host_pod_ref") - @Parameter(name=ApiConstants.POD_IDS, type=CommandType.LIST, required=false, description="Used when NetScaler device is provider of EIP service." + + @Parameter(name=ApiConstants.POD_IDS, type=CommandType.LIST, collectionType = CommandType.UUID, entityType = PodResponse.class, + required=false, description="Used when NetScaler device is provider of EIP service." + " This parameter represents the list of pod's, for which there exists a policy based route on datacenter L3 router to " + "route pod's subnet IP to a NetScaler device.") private List podIds; diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java index b063fdf6396..ec7faab39d4 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/DeleteNetscalerLoadBalancerCmd.java @@ -17,15 +17,15 @@ package com.cloud.api.commands; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -36,7 +36,7 @@ import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a netscaler load balancer device") +@APICommand(name = "deleteNetscalerLoadBalancer", responseObject=SuccessResponse.class, description=" delete a netscaler load balancer device") public class DeleteNetscalerLoadBalancerCmd extends BaseAsyncCmd { public static final Logger s_logger = Logger.getLogger(DeleteNetscalerLoadBalancerCmd.class.getName()); @@ -47,8 +47,8 @@ public class DeleteNetscalerLoadBalancerCmd extends BaseAsyncCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required=true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + required=true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java index c0c5950d57e..b5935f34fda 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancerNetworksCmd.java @@ -19,16 +19,16 @@ import java.util.List; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -38,7 +38,7 @@ import com.cloud.network.Network; import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a netscaler load balancer device") +@APICommand(name = "listNetscalerLoadBalancerNetworks", responseObject=NetworkResponse.class, description="lists network that are using a netscaler load balancer device") public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetscalerLoadBalancerNetworksCmd.class.getName()); @@ -49,8 +49,8 @@ public class ListNetscalerLoadBalancerNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, required = true, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, , + required = true, description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java index 98fe6e95df7..bf679fa51c1 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/commands/ListNetscalerLoadBalancersCmd.java @@ -17,17 +17,17 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.NetscalerLoadBalancerResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -38,7 +38,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.element.NetscalerLoadBalancerElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetscalerLoadBalancerResponse.class, description="lists netscaler load balancer devices") +@APICommand(name = "listNetscalerLoadBalancers", responseObject=NetscalerLoadBalancerResponse.class, description="lists netscaler load balancer devices") public class ListNetscalerLoadBalancersCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNetscalerLoadBalancersCmd.class.getName()); @@ -49,12 +49,12 @@ public class ListNetscalerLoadBalancersCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_load_balancer_devices") - @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.LONG, description="netscaler load balancer device ID") + @Parameter(name=ApiConstants.LOAD_BALANCER_DEVICE_ID, type=CommandType.UUID, entityType = NetscalerLoadBalancerResponse.class, + description="netscaler load balancer device ID") private Long lbDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java index bbbfca515a1..40be29e560b 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java +++ b/plugins/network-elements/netscaler/src/com/cloud/api/response/NetscalerLoadBalancerResponse.java @@ -18,28 +18,29 @@ package com.cloud.api.response; import java.util.List; -import com.cloud.api.ApiConstants; -import com.cloud.api.Parameter; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.EntityReference; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import com.cloud.network.ExternalLoadBalancerDeviceVO; +@EntityReference(value=ExternalLoadBalancerDeviceVO.class) @SuppressWarnings("unused") public class NetscalerLoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_ID) @Param(description="device id of the netscaler load balancer") - private IdentityProxy id = new IdentityProxy("external_load_balancer_devices"); + private String id; @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this netscaler device belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); + private String physicalNetworkId; @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_NAME) @Param(description="device name") - private String deviceName; - + private String deviceName; + @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_STATE) @Param(description="device state") private String deviceState; @@ -49,12 +50,9 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { @SerializedName(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) @Param(description="true if device is dedicated for an account") private Boolean dedicatedLoadBalancer; - @SerializedName(ApiConstants.INLINE) @Param(description="true if device is inline with firewall device") - private Boolean inlineLoadBalancer; - @SerializedName(ApiConstants.PUBLIC_INTERFACE) @Param(description="the public interface of the load balancer") private String publicInterface; - + @SerializedName(ApiConstants.PRIVATE_INTERFACE) @Param(description="the private interface of the load balancer") private String privateInterface; @@ -65,13 +63,13 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { " This parameter represents the list of pod's, for which there exists a policy based route on datacenter L3 router to " + "route pod's subnet IP to a NetScaler device.") private List podIds; - - public void setId(long lbDeviceId) { - this.id.setValue(lbDeviceId); + + public void setId(String lbDeviceId) { + this.id = lbDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProvider(String provider) { @@ -94,10 +92,6 @@ public class NetscalerLoadBalancerResponse extends BaseResponse { this.deviceState = deviceState; } - public void setInlineMode(boolean inline) { - this.inlineLoadBalancer = inline; - } - public void setPublicInterface(String publicInterface) { this.publicInterface = publicInterface; } diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java b/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java index f28078749d2..be0bd2f8c23 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/NetScalerPodVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -31,7 +33,7 @@ import javax.persistence.Table; */ @Entity @Table(name="netscaler_pod_ref") -public class NetScalerPodVO { +public class NetScalerPodVO implements InternalIdentity { @Column(name="external_load_balancer_device_id") private long netscalerDeviceId; 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 5f1b8f23fcf..30c51ee5ce1 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 @@ -37,7 +37,9 @@ import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.to.LoadBalancerTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; + +import com.cloud.api.ApiDBUtils; import com.cloud.api.commands.AddNetscalerLoadBalancerCmd; import com.cloud.api.commands.ConfigureNetscalerLoadBalancerCmd; import com.cloud.api.commands.DeleteNetscalerLoadBalancerCmd; @@ -67,7 +69,7 @@ import com.cloud.network.ExternalLoadBalancerDeviceManager; import com.cloud.network.ExternalLoadBalancerDeviceManagerImpl; import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.IpAddress; import com.cloud.network.NetScalerPodVO; import com.cloud.network.Network; @@ -78,9 +80,12 @@ import com.cloud.network.NetworkExternalLoadBalancerVO; 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.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.PublicIpAddress; +import com.cloud.network.as.AutoScaleCounter; +import com.cloud.network.as.AutoScaleCounter.AutoScaleCounterType; import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; import com.cloud.network.dao.NetScalerPodDao; import com.cloud.network.dao.NetworkDao; @@ -96,7 +101,6 @@ import com.cloud.network.rules.LbStickinessMethod; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; -import com.cloud.resource.ServerResource; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; @@ -111,9 +115,11 @@ import com.google.gson.Gson; @Component @Local(value = NetworkElement.class) public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl implements LoadBalancingServiceProvider, NetscalerLoadBalancerElementService, ExternalLoadBalancerDeviceManager, IpDeployer, - StaticNatServiceProvider { +StaticNatServiceProvider { private static final Logger s_logger = Logger.getLogger(NetscalerElement.class); + public static final AutoScaleCounterType AutoScaleCounterSnmp = new AutoScaleCounterType("snmp"); + public static final AutoScaleCounterType AutoScaleCounterNetscaler = new AutoScaleCounterType("netscaler"); @Inject NetworkManager _networkManager; @@ -148,7 +154,8 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl 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)) { @@ -211,7 +218,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl } @Override - public boolean destroy(Network config) { + public boolean destroy(Network config, ReservationContext context) { return true; } @@ -255,6 +262,21 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl // Specifies that load balancing rules can only be made with public IPs that aren't source NAT IPs lbCapabilities.put(Capability.LoadBalancingSupportedIps, "additional"); + // Specifies that load balancing rules can support autoscaling and the list of counters it supports + AutoScaleCounter counter; + List counterList = new ArrayList(); + counter = new AutoScaleCounter(AutoScaleCounterSnmp); + counterList.add(counter); + counter.addParam("snmpcommunity", true, "the community string that has to be used to do a SNMP GET on the AutoScaled Vm", false); + counter.addParam("snmpport", false, "the port at which SNMP agent is running on the AutoScaled Vm", false); + + counter = new AutoScaleCounter(AutoScaleCounterNetscaler); + counterList.add(counter); + + Gson gson = new Gson(); + String autoScaleCounterList = gson.toJson(counterList); + lbCapabilities.put(Capability.AutoScaleCounters, autoScaleCounterList); + LbStickinessMethod method; List methodList = new ArrayList(); method = new LbStickinessMethod(StickinessMethodType.LBCookieBased, "This is cookie based sticky method, can be used only for http"); @@ -269,7 +291,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl methodList.add(method); method.addParam("holdtime", false, "time period for which persistence is in effect.", false); - Gson gson = new Gson(); String stickyMethodList = gson.toJson(methodList); lbCapabilities.put(Capability.SupportedStickinessMethods, stickyMethodList); @@ -317,7 +338,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl throw new InvalidParameterValueException(msg); } - ExternalLoadBalancerDeviceVO lbDeviceVO = addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, (ServerResource) new NetscalerResource()); + ExternalLoadBalancerDeviceVO lbDeviceVO = addExternalLoadBalancer(cmd.getPhysicalNetworkId(), cmd.getUrl(), cmd.getUsername(), cmd.getPassword(), deviceName, new NetscalerResource()); return lbDeviceVO; } @@ -337,18 +358,17 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl public ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(ConfigureNetscalerLoadBalancerCmd cmd) { Long lbDeviceId = cmd.getLoadBalancerDeviceId(); Boolean dedicatedUse = cmd.getLoadBalancerDedicated(); - Boolean inline = cmd.getLoadBalancerInline(); Long capacity = cmd.getLoadBalancerCapacity(); List podIds = cmd.getPodIds(); try { - return configureNetscalerLoadBalancer(lbDeviceId, capacity, inline, dedicatedUse, podIds); + return configureNetscalerLoadBalancer(lbDeviceId, capacity, dedicatedUse, podIds); } catch (Exception e) { throw new CloudRuntimeException("failed to configure netscaler device due to " + e.getMessage()); } } @DB - private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(long lbDeviceId, Long capacity, Boolean inline, Boolean dedicatedUse, List newPodsConfig) { + private ExternalLoadBalancerDeviceVO configureNetscalerLoadBalancer(long lbDeviceId, Long capacity, Boolean dedicatedUse, List newPodsConfig) { ExternalLoadBalancerDeviceVO lbDeviceVo = _lbDeviceDao.findById(lbDeviceId); Map lbDetails = _detailsDao.findDetails(lbDeviceVo.getHostId()); @@ -388,7 +408,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl } String deviceName = lbDeviceVo.getDeviceName(); - if (dedicatedUse != null || capacity != null || inline != null) { + if (dedicatedUse != null || capacity != null) { if (NetworkDevice.NetscalerSDXLoadBalancer.getName().equalsIgnoreCase(deviceName) || NetworkDevice.NetscalerMPXLoadBalancer.getName().equalsIgnoreCase(deviceName)) { if (dedicatedUse != null && dedicatedUse == true) { @@ -406,13 +426,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl if (dedicatedUse != null && dedicatedUse == true) { throw new CloudRuntimeException("There are networks already using this netscaler device to make device dedicated"); } - - if (inline != null) { - boolean _setInline = Boolean.parseBoolean((String) lbDetails.get("inline")); - if (inline != _setInline) { - throw new CloudRuntimeException("There are networks already using this netscaler device to change the device inline or side-by-side configuration"); - } - } } } @@ -428,14 +441,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl lbDeviceVo.setIsDedicatedDevice(dedicatedUse); } - if (inline != null && inline == true) { - lbDeviceVo.setIsInlineMode(true); - lbDetails.put("inline", "true"); - } else { - lbDeviceVo.setIsInlineMode(false); - lbDetails.put("inline", "false"); - } - Transaction txn = Transaction.currentTxn(); txn.start(); @@ -524,9 +529,12 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl Host lbHost = _hostDao.findById(lbDeviceVO.getHostId()); Map lbDetails = _detailsDao.findDetails(lbDeviceVO.getHostId()); - response.setId(lbDeviceVO.getId()); + response.setId(lbDeviceVO.getUuid()); response.setIpAddress(lbHost.getPrivateIpAddress()); - response.setPhysicalNetworkId(lbDeviceVO.getPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(lbDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } response.setPublicInterface(lbDetails.get("publicInterface")); response.setPrivateInterface(lbDetails.get("privateInterface")); response.setDeviceName(lbDeviceVO.getDeviceName()); @@ -536,7 +544,6 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl } else { response.setDeviceCapacity(lbDeviceVO.getCapacity()); } - response.setInlineMode(lbDeviceVO.getIsInLineMode()); response.setDedicatedLoadBalancer(lbDeviceVO.getIsDedicatedDevice()); response.setProvider(lbDeviceVO.getProviderName()); response.setDeviceState(lbDeviceVO.getState().name()); @@ -563,7 +570,7 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl List lbDevices = _lbDeviceDao.listByPhysicalNetworkAndProvider(provider.getPhysicalNetworkId(), Provider.Netscaler.getName()); // true if at-least one Netscaler device is added in to physical network and is in configured (in enabled state) -// state + // state if (lbDevices != null && !lbDevices.isEmpty()) { for (ExternalLoadBalancerDeviceVO lbDevice : lbDevices) { if (lbDevice.getState() == LBDeviceState.Enabled) { @@ -604,12 +611,16 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl // NetScaler can only act as Lb and Static Nat service provider if (services != null && !services.isEmpty() && !netscalerServices.containsAll(services)) { + s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + + services + " is not supported."); String servicesList = ""; for (Service service : services) { servicesList += service.getName() + " "; } s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + servicesList + " is not supported."); + s_logger.warn("NetScaler network element can only support LB and Static NAT services and service combination " + + services + " is not supported."); return false; } @@ -624,6 +635,14 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl @Override public IpDeployer getIpDeployer(Network network) { + ExternalLoadBalancerDeviceVO lbDevice = getExternalLoadBalancerForNetwork(network); + if (lbDevice == null) { + s_logger.error("Cannot find external load balanacer for network " + network.getName()); + return null; + } + if (_networkMgr.isNetworkInlineMode(network)) { + return getIpDeployerForInlineMode(network); + } return this; } @@ -664,12 +683,16 @@ public class NetscalerElement extends ExternalLoadBalancerDeviceManagerImpl impl boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); + String lbUuid = rule.getUuid(); String srcIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); - if (destinations != null && !destinations.isEmpty()) { - LoadBalancerTO loadBalancer = new LoadBalancerTO(srcIp, srcPort, protocol, algorithm, revoked, false, destinations, rule.getStickinessPolicies()); + if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { + LoadBalancerTO loadBalancer = new LoadBalancerTO(lbUuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, rule.getStickinessPolicies()); + if (rule.isAutoScaleConfig()) { + loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); + } loadBalancersToApply.add(loadBalancer); } } diff --git a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java index a709cd4ec91..afb01353e1e 100644 --- a/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java +++ b/plugins/network-elements/netscaler/src/com/cloud/network/resource/NetscalerResource.java @@ -16,14 +16,50 @@ // under the License. package com.cloud.network.resource; +import java.util.Formatter; +import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; + import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.citrix.netscaler.nitro.exception.nitro_exception; +import com.citrix.netscaler.nitro.resource.base.base_response; +import com.citrix.netscaler.nitro.resource.config.autoscale.autoscalepolicy; +import com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleprofile; +import com.citrix.netscaler.nitro.resource.config.basic.server_service_binding; +import com.citrix.netscaler.nitro.resource.config.basic.servicegroup; +import com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding; +import com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable; +import com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable_metric_binding; +import com.citrix.netscaler.nitro.resource.config.lb.lbmonitor; +import com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_metric_binding; +import com.citrix.netscaler.nitro.resource.config.lb.lbvserver; +import com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding; +import com.citrix.netscaler.nitro.resource.config.lb.lbvserver_servicegroup_binding; +import com.citrix.netscaler.nitro.resource.config.network.Interface; +import com.citrix.netscaler.nitro.resource.config.network.inat; +import com.citrix.netscaler.nitro.resource.config.network.vlan; +import com.citrix.netscaler.nitro.resource.config.network.vlan_interface_binding; +import com.citrix.netscaler.nitro.resource.config.network.vlan_nsip_binding; +import com.citrix.netscaler.nitro.resource.config.ns.nsconfig; +import com.citrix.netscaler.nitro.resource.config.ns.nshardware; +import com.citrix.netscaler.nitro.resource.config.ns.nsip; +import com.citrix.netscaler.nitro.resource.config.ns.nstimer; +import com.citrix.netscaler.nitro.resource.config.ns.nstimer_autoscalepolicy_binding; +import com.citrix.netscaler.nitro.resource.stat.lb.lbvserver_stats; +import com.citrix.netscaler.nitro.service.nitro_service; +import com.citrix.netscaler.nitro.util.filtervalue; +import com.citrix.sdx.nitro.resource.config.device_profile; +import com.citrix.sdx.nitro.resource.config.mps; +import com.citrix.sdx.nitro.resource.config.ns; +import com.citrix.sdx.nitro.resource.config.xen_vpx_image; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; -import com.cloud.agent.api.routing.CreateLoadBalancerApplianceCommand; -import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand; import com.cloud.agent.api.ExternalNetworkResourceUsageAnswer; import com.cloud.agent.api.ExternalNetworkResourceUsageCommand; import com.cloud.agent.api.MaintainAnswer; @@ -33,6 +69,8 @@ import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalLoadBalancerCommand; +import com.cloud.agent.api.routing.CreateLoadBalancerApplianceCommand; +import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; @@ -40,9 +78,15 @@ import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.agent.api.to.StaticNatRuleTO; +import com.cloud.agent.api.to.LoadBalancerTO.AutoScalePolicyTO; +import com.cloud.agent.api.to.LoadBalancerTO.AutoScaleVmGroupTO; +import com.cloud.agent.api.to.LoadBalancerTO.AutoScaleVmProfileTO; +import com.cloud.agent.api.to.LoadBalancerTO.ConditionTO; +import com.cloud.agent.api.to.LoadBalancerTO.CounterTO; import com.cloud.agent.api.to.LoadBalancerTO.DestinationTO; import com.cloud.agent.api.to.LoadBalancerTO.StickinessPolicyTO; +import com.cloud.agent.api.to.StaticNatRuleTO; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host; import com.cloud.host.Host.Type; import com.cloud.network.rules.LbStickinessMethod.StickinessMethodType; @@ -54,24 +98,6 @@ import com.cloud.utils.exception.ExecutionException; import com.cloud.utils.net.NetUtils; import com.google.gson.Gson; -import com.citrix.netscaler.nitro.service.nitro_service; -import com.citrix.netscaler.nitro.util.filtervalue; -import com.citrix.netscaler.nitro.resource.base.base_response; -import com.citrix.netscaler.nitro.exception.nitro_exception; -import com.citrix.netscaler.nitro.resource.config.ns.nsconfig; -import com.citrix.netscaler.nitro.resource.config.lb.lbvserver; -import com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding; -import com.citrix.netscaler.nitro.resource.config.network.*; -import com.citrix.netscaler.nitro.resource.config.ns.*; -import com.citrix.netscaler.nitro.resource.config.basic.server_service_binding; -import com.citrix.netscaler.nitro.resource.stat.lb.lbvserver_stats; -import com.citrix.sdx.nitro.resource.config.device_profile; -import com.citrix.sdx.nitro.resource.config.ns; -import com.citrix.sdx.nitro.resource.config.mps; -import com.citrix.sdx.nitro.resource.config.xen_vpx_image; - -import org.apache.log4j.Logger; - class NitroError { static final int NS_RESOURCE_EXISTS = 273; static final int NS_RESOURCE_NOT_EXISTS=258; @@ -82,6 +108,7 @@ class NitroError { public class NetscalerResource implements ServerResource { + public final static int DEFAULT_SNMP_PORT = 161; // deployment configuration private String _name; private String _zoneId; @@ -91,7 +118,7 @@ public class NetscalerResource implements ServerResource { private String _password; private String _publicInterface; private String _privateInterface; - private Integer _numRetries; + private Integer _numRetries; private String _guid; private boolean _inline; private boolean _isSdx; @@ -186,8 +213,8 @@ public class NetscalerResource implements ServerResource { login(); validateDeviceType(_deviceName); validateInterfaces(_publicInterface, _privateInterface); - - //enable load balancing feature + + //enable load balancing feature enableLoadBalancingFeature(); //if the the device is cloud stack provisioned then make it part of the public network @@ -197,10 +224,10 @@ public class NetscalerResource implements ServerResource { _publicIPNetmask = (String) params.get("publicipnetmask"); _publicIPVlan = (String) params.get("publicipvlan"); if ("untagged".equalsIgnoreCase(_publicIPVlan)) { - // if public network is un-tagged just add subnet IP + // if public network is un-tagged just add subnet IP addSubnetIP(_publicIP, _publicIPNetmask); } else { - // if public network is tagged then add vlan and bind subnet IP to the vlan + // if public network is tagged then add vlan and bind subnet IP to the vlan addGuestVlanAndSubnet(Long.parseLong(_publicIPVlan), _publicIP, _publicIPNetmask, false); } } @@ -211,8 +238,26 @@ public class NetscalerResource implements ServerResource { } } + private void logout() throws ExecutionException { + try { + if (!_isSdx) { + if(_netscalerService != null) { + _netscalerService.logout(); + } + } else { + if(_netscalerSdxService != null) { + _netscalerSdxService.logout(); + } + } + } catch (Exception e) { + // Ignore logout exceptions + } + } + private void login() throws ExecutionException { try { + // If a previous session was open, log it out. + logout(); if (!_isSdx) { _netscalerService = new nitro_service(_ip, "https"); _netscalerService.set_credential(_username, _password); @@ -224,9 +269,9 @@ public class NetscalerResource implements ServerResource { } else { _netscalerSdxService = new com.citrix.sdx.nitro.service.nitro_service(_ip, "https"); _netscalerSdxService.set_credential(_username, _password); - com.citrix.sdx.nitro.resource.base.login login = _netscalerSdxService.login(); + com.citrix.sdx.nitro.resource.base.login login = _netscalerSdxService.login(); if (login == null) { - throw new ExecutionException ("Failed to log in to Netscaler device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message); + throw new ExecutionException ("Failed to log in to Netscaler SDX device at " + _ip + " due to error " + apiCallResult.errorcode + " and message " + apiCallResult.message); } } } catch (nitro_exception e) { @@ -371,7 +416,7 @@ public class NetscalerResource implements ServerResource { String[] results = new String[cmd.getIpAddresses().length]; int i = 0; - try { + try { IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { long guestVlanTag = Long.valueOf(ip.getVlanId()); @@ -423,6 +468,11 @@ public class NetscalerResource implements ServerResource { String lbAlgorithm = loadBalancer.getAlgorithm(); String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort); + if(loadBalancer.isAutoScaleVmGroupTO()) { + applyAutoScaleConfig(loadBalancer); + return new Answer(cmd); + } + boolean destinationsToAdd = false; for (DestinationTO destination : loadBalancer.getDestinations()) { if (!destination.isRevoked()) { @@ -434,16 +484,16 @@ public class NetscalerResource implements ServerResource { if (!loadBalancer.isRevoked() && destinationsToAdd) { // create a load balancing virtual server - addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol, loadBalancer.getStickinessPolicies()); + addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol, loadBalancer.getStickinessPolicies(), null); if (s_logger.isDebugEnabled()) { s_logger.debug("Created load balancing virtual server " + nsVirtualServerName + " on the Netscaler device"); } for (DestinationTO destination : loadBalancer.getDestinations()) { - + String nsServerName = generateNSServerName(destination.getDestIp()); String nsServiceName = generateNSServiceName(destination.getDestIp(), destination.getDestPort()); - + if (!destination.isRevoked()) { // add a new destination to deployed load balancing rule @@ -473,13 +523,13 @@ public class NetscalerResource implements ServerResource { } } - //bind service to load balancing virtual server + //bind service to load balancing virtual server if (!nsServiceBindingExists(nsVirtualServerName, nsServiceName)) { com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding svcBinding = new com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding(); svcBinding.set_name(nsVirtualServerName); svcBinding.set_servicename(nsServiceName); apiCallResult = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.add(_netscalerService, svcBinding); - + if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to bind service: " + nsServiceName + " to the lb virtual server: " + nsVirtualServerName + " on Netscaler device"); } @@ -498,7 +548,7 @@ public class NetscalerResource implements ServerResource { if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to delete the binding between the virtual server: " + nsVirtualServerName + " and service:" + nsServiceName + " due to" + apiCallResult.message); } - + // check if service is bound to any other virtual server if (!isServiceBoundToVirtualServer(nsServiceName)) { // no lb virtual servers are bound to this service so delete it @@ -507,7 +557,7 @@ public class NetscalerResource implements ServerResource { throw new ExecutionException("Failed to delete service: " + nsServiceName + " due to " + apiCallResult.message); } } - + // delete the server if there is no associated services server_service_binding[] services = server_service_binding.get(_netscalerService, nsServerName); if ((services == null) || (services.length == 0)) { @@ -519,15 +569,15 @@ public class NetscalerResource implements ServerResource { } } } - } + } } } else { - // delete the implemented load balancing rule and its destinations + // delete the implemented load balancing rule and its destinations lbvserver lbserver = getVirtualServerIfExisits(nsVirtualServerName); if (lbserver != null) { //unbind the all services associated with this virtual server com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding[] serviceBindings = com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding.get(_netscalerService, nsVirtualServerName); - + if (serviceBindings != null) { for (com.citrix.netscaler.nitro.resource.config.lb.lbvserver_service_binding binding : serviceBindings) { String serviceName = binding.get_servicename(); @@ -535,7 +585,7 @@ public class NetscalerResource implements ServerResource { if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to unbind service from the lb virtual server: " + nsVirtualServerName + " due to " + apiCallResult.message); } - + com.citrix.netscaler.nitro.resource.config.basic.service svc = com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName); String nsServerName = svc.get_servername(); @@ -570,20 +620,20 @@ public class NetscalerResource implements ServerResource { saveConfiguration(); return new Answer(cmd); } catch (ExecutionException e) { - s_logger.error("Failed to execute LoadBalancerConfigCommand due to " + e.getMessage()); + s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e); if (shouldRetry(numRetries)) { return retry(cmd, numRetries); } else { return new Answer(cmd, e); } } catch (Exception e) { - s_logger.error("Failed to execute LoadBalancerConfigCommand due to " + e.getMessage()); + s_logger.error("Failed to execute LoadBalancerConfigCommand due to ", e); if (shouldRetry(numRetries)) { return retry(cmd, numRetries); } else { return new Answer(cmd, e); } - } + } } private synchronized Answer execute(CreateLoadBalancerApplianceCommand cmd, int numRetries) { @@ -615,8 +665,8 @@ public class NetscalerResource implements ServerResource { // use the first device profile available on the SDX to create an instance of VPX device_profile[] profiles = device_profile.get(_netscalerSdxService); if (!(profiles != null && profiles.length >= 1)) { - new Answer(cmd, new ExecutionException("Failed to create VPX instance on the netscaler SDX device " + _ip + - " as there are no admin profile to use for creating VPX.")); + new Answer(cmd, new ExecutionException("Failed to create VPX instance on the netscaler SDX device " + _ip + + " as there are no admin profile to use for creating VPX.")); } String profileName = profiles[0].get_name(); ns_obj.set_nsroot_profile(profileName); @@ -625,8 +675,8 @@ public class NetscalerResource implements ServerResource { // TODO: should enable the option to choose the template while adding the SDX device in to CloudStack xen_vpx_image[] vpxImages = xen_vpx_image.get(_netscalerSdxService); if (!(vpxImages != null && vpxImages.length >= 1)) { - new Answer(cmd, new ExecutionException("Failed to create VPX instance on the netscaler SDX device " + _ip + - " as there are no VPX images on SDX to use for creating VPX.")); + new Answer(cmd, new ExecutionException("Failed to create VPX instance on the netscaler SDX device " + _ip + + " as there are no VPX images on SDX to use for creating VPX.")); } String imageName = vpxImages[0].get_file_name(); ns_obj.set_image_name(imageName); @@ -648,7 +698,7 @@ public class NetscalerResource implements ServerResource { long startTick = System.currentTimeMillis(); long startWaitMilliSeconds = 600000; while(!newVpx.get_ns_state().equalsIgnoreCase("up") && System.currentTimeMillis() - startTick < startWaitMilliSeconds) { - try { + try { Thread.sleep(10000); } catch(InterruptedException e) { } @@ -1044,7 +1094,7 @@ public class NetscalerResource implements ServerResource { } // unbind the vlan to subnet - try { + try { vlan_nsip_binding vlanSnipBinding = new vlan_nsip_binding(); vlanSnipBinding.set_netmask(vlanNetmask); vlanSnipBinding.set_ipaddress(vlanSelfIp); @@ -1081,7 +1131,7 @@ public class NetscalerResource implements ServerResource { if (apiCallResult.errorcode != 0) { throw new ExecutionException("Failed to remove vlan with tag:" + vlanTag + "due to" + apiCallResult.message); } - } + } } catch (nitro_exception e) { throw new ExecutionException("Failed to delete guest vlan network on the Netscaler device due to " + e.getMessage()); } catch (Exception e) { @@ -1179,7 +1229,7 @@ public class NetscalerResource implements ServerResource { for (lbvserver vserver : lbservers) { filtervalue[] filter = new filtervalue[1]; filter[0] = new filtervalue("servicename", serviceName); - lbvserver_service_binding[] result = (lbvserver_service_binding[]) lbvserver_service_binding.get_filtered(_netscalerService, vserver.get_name(), filter); + lbvserver_service_binding[] result = lbvserver_service_binding.get_filtered(_netscalerService, vserver.get_name(), filter); if (result != null && result.length > 0) { return true; } @@ -1189,7 +1239,7 @@ public class NetscalerResource implements ServerResource { throw new ExecutionException("Failed to verify service " + serviceName + " is bound to any virtual server due to " + e.getMessage()); } } - + private boolean nsServiceExists(String serviceName) throws ExecutionException { try { if (com.citrix.netscaler.nitro.resource.config.basic.service.get(_netscalerService, serviceName) != null) { @@ -1226,6 +1276,36 @@ public class NetscalerResource implements ServerResource { } } + private boolean isServiceGroupBoundToVirtualServer(String nsVirtualServerName, String serviceGroupName) throws ExecutionException { + + lbvserver_servicegroup_binding vserver_servicegroup_binding = new lbvserver_servicegroup_binding(); + + try { + lbvserver_servicegroup_binding[] result = vserver_servicegroup_binding.get_filtered(_netscalerService, nsVirtualServerName, "servicegroupname:" + serviceGroupName); + if(result != null && result.length > 0){ + return true; + } + } catch (Exception e) { + throw new ExecutionException("Failed to verify lb vserver " + nsVirtualServerName + "and servicegrop " + serviceGroupName + " binding exists due to " + e.getMessage()); + } + return false; + + } + + private boolean nsServiceGroupExists(String lbVServerName ) throws ExecutionException { + try { + return servicegroup.get(_netscalerService, lbVServerName) != null; + } catch (nitro_exception e) { + if (e.getErrorCode() == NitroError.NS_RESOURCE_NOT_EXISTS) { + return false; // service group does not exist + } else { + throw new ExecutionException(e.getMessage()); + } + } catch (Exception e) { + throw new ExecutionException(e.getMessage()); + } + } + private void deleteServersInGuestVlan(long vlanTag, String vlanSelfIp, String vlanNetmask) throws ExecutionException { try { com.citrix.netscaler.nitro.resource.config.basic.server[] serverList = com.citrix.netscaler.nitro.resource.config.basic.server.get(_netscalerService); @@ -1288,7 +1368,8 @@ public class NetscalerResource implements ServerResource { return nsProtocol; } - private void addLBVirtualServer(String virtualServerName, String publicIp, int publicPort, String lbAlgorithm, String protocol, StickinessPolicyTO[] stickyPolicies) throws ExecutionException { + private void addLBVirtualServer(String virtualServerName, String publicIp, int publicPort, String lbAlgorithm, String protocol, StickinessPolicyTO[] stickyPolicies, AutoScaleVmGroupTO vmGroupTO) + throws ExecutionException { try { String lbMethod; if ("roundrobin".equalsIgnoreCase(lbAlgorithm)) { @@ -1303,15 +1384,15 @@ public class NetscalerResource implements ServerResource { boolean vserverExisis = false; lbvserver vserver = getVirtualServerIfExisits(virtualServerName); - if (vserver == null) { - vserver = new lbvserver(); - } else { + if (vserver != null) { if (!vserver.get_servicetype().equalsIgnoreCase(protocol)) { throw new ExecutionException("Can not update virtual server:" + virtualServerName + " as current protocol:" + vserver.get_servicetype() + " of virtual server is different from the " + " intended protocol:" + protocol); } vserverExisis = true; } + // Use new vserver always for configuration + vserver = new lbvserver(); vserver.set_name(virtualServerName); vserver.set_ipv46(publicIp); vserver.set_port(publicPort); @@ -1333,7 +1414,7 @@ public class NetscalerResource implements ServerResource { List> paramsList = stickinessPolicy.getParams(); for(Pair param : paramsList) { if ("holdtime".equalsIgnoreCase(param.first())) { - timeout = Long.parseLong(param.second()); + timeout = Long.parseLong(param.second()); } else if ("name".equalsIgnoreCase(param.first())) { cookieName = param.second(); } @@ -1355,10 +1436,8 @@ public class NetscalerResource implements ServerResource { // set session persistence timeout vserver.set_timeout(timeout); } else { - if (vserver.get_persistencetype() != null) { - // delete the LB stickyness policy - vserver.set_persistencetype("NONE"); - } + // delete the LB stickyness policy + vserver.set_persistencetype("NONE"); } if (vserverExisis) { @@ -1401,6 +1480,680 @@ public class NetscalerResource implements ServerResource { } } + public synchronized void applyAutoScaleConfig(LoadBalancerTO loadBalancer) throws Exception, ExecutionException { + + AutoScaleVmGroupTO vmGroupTO = loadBalancer.getAutoScaleVmGroupTO(); + if(!isAutoScaleSupportedInNetScaler()) { + throw new ExecutionException("AutoScale not supported in this version of NetScaler"); + } + if(vmGroupTO.getState().equals("new")) { + assert !loadBalancer.isRevoked(); + createAutoScaleConfig(loadBalancer); + } + else if(loadBalancer.isRevoked() || vmGroupTO.getState().equals("revoke")) { + removeAutoScaleConfig(loadBalancer); + } + else if(vmGroupTO.getState().equals("enabled")) { + assert !loadBalancer.isRevoked(); + enableAutoScaleConfig(loadBalancer, false); + } + else if(vmGroupTO.getState().equals("disabled")) { + assert !loadBalancer.isRevoked(); + disableAutoScaleConfig(loadBalancer, false); + } else { + ///// This should never happen + throw new ExecutionException("Unknown AutoScale Vm Group State :" + vmGroupTO.getState()); + } + // AutoScale APIs are successful executed, now save the configuration. + saveConfiguration(); + if (s_logger.isInfoEnabled()) { + s_logger.info("Successfully executed resource AutoScaleConfig"); + } + } + + @SuppressWarnings("static-access") + private synchronized boolean createAutoScaleConfig(LoadBalancerTO loadBalancerTO) throws ExecutionException, Exception { + + String srcIp = loadBalancerTO.getSrcIp(); + int srcPort = loadBalancerTO.getSrcPort(); + String lbProtocol = getNetScalerProtocol(loadBalancerTO); + String lbAlgorithm = loadBalancerTO.getAlgorithm(); + String vmGroupIdentifier = generateAutoScaleVmGroupIdentifier(loadBalancerTO); + String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort); + AutoScaleVmGroupTO vmGroupTO = loadBalancerTO.getAutoScaleVmGroupTO(); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Created load balancing virtual server " + nsVirtualServerName + " on the Netscaler device"); + } + addLBVirtualServer(nsVirtualServerName, srcIp, srcPort, lbAlgorithm, lbProtocol, loadBalancerTO.getStickinessPolicies(), vmGroupTO); + + String serviceGroupName = generateAutoScaleServiceGroupName(loadBalancerTO); + if(!nsServiceGroupExists(serviceGroupName)) { + // add servicegroup lb_autoscaleGroup -autoscale POLICY -memberPort 80 + int memberPort = vmGroupTO.getMemberPort(); + try { + servicegroup serviceGroup = new servicegroup(); + serviceGroup.set_servicegroupname(serviceGroupName); + serviceGroup.set_servicetype(lbProtocol); + serviceGroup.set_autoscale("POLICY"); + serviceGroup.set_memberport(memberPort); + serviceGroup.add(_netscalerService, serviceGroup); + } catch (Exception e) { + throw e; + } + } + + if(!isServiceGroupBoundToVirtualServer(nsVirtualServerName, serviceGroupName)) { + // Bind autoscale service group + // bind lb vserver lb lb_autoscaleGroup + lbvserver_servicegroup_binding vserver_servicegroup_binding = new lbvserver_servicegroup_binding(); + + try { + vserver_servicegroup_binding.set_name(nsVirtualServerName); + vserver_servicegroup_binding.set_servicegroupname(serviceGroupName); + vserver_servicegroup_binding.add(_netscalerService, vserver_servicegroup_binding); + } catch (Exception e) { + throw e; + } + } + + // Create the autoscale config + enableAutoScaleConfig(loadBalancerTO, false); + return true; + } + + @SuppressWarnings("static-access") + private synchronized boolean removeAutoScaleConfig(LoadBalancerTO loadBalancerTO) throws Exception, ExecutionException { + String srcIp = loadBalancerTO.getSrcIp(); + int srcPort = loadBalancerTO.getSrcPort(); + String vmGroupIdentifier = generateAutoScaleVmGroupIdentifier(loadBalancerTO); + + String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort); + String serviceGroupName = generateAutoScaleServiceGroupName(loadBalancerTO); + + if(loadBalancerTO.getAutoScaleVmGroupTO().getCurrentState().equals("enabled")) { + disableAutoScaleConfig(loadBalancerTO, false); + } + + if(isServiceGroupBoundToVirtualServer(nsVirtualServerName, serviceGroupName)) { + // UnBind autoscale service group + // unbind lb vserver lb lb_autoscaleGroup + lbvserver_servicegroup_binding vserver_servicegroup_binding = new lbvserver_servicegroup_binding(); + try { + vserver_servicegroup_binding.set_name(nsVirtualServerName); + vserver_servicegroup_binding.set_servicegroupname(serviceGroupName); + vserver_servicegroup_binding.delete(_netscalerService, vserver_servicegroup_binding); + } catch (Exception e) { + throw e; + } + } + + if (nsServiceGroupExists(serviceGroupName)) { + // Remove autoscale service group + com.citrix.netscaler.nitro.resource.config.basic.servicegroup serviceGroup = new com.citrix.netscaler.nitro.resource.config.basic.servicegroup(); + try { + serviceGroup.set_servicegroupname(serviceGroupName); + serviceGroup.delete(_netscalerService, serviceGroup); + } catch (Exception e) { + throw e; + } + } + + removeLBVirtualServer(nsVirtualServerName); + + return true; + } + + @SuppressWarnings("static-access") + private synchronized boolean enableAutoScaleConfig(LoadBalancerTO loadBalancerTO, boolean isCleanUp) throws Exception { + String vmGroupIdentifier = generateAutoScaleVmGroupIdentifier(loadBalancerTO); + String srcIp = loadBalancerTO.getSrcIp(); + int srcPort = loadBalancerTO.getSrcPort(); + + String nsVirtualServerName = generateNSVirtualServerName(srcIp, srcPort); + String serviceGroupName = generateAutoScaleServiceGroupName(loadBalancerTO); + String profileName = generateAutoScaleProfileName(vmGroupIdentifier); + String timerName = generateAutoScaleTimerName(vmGroupIdentifier); + String scaleDownActionName = generateAutoScaleScaleDownActionName(vmGroupIdentifier); + String scaleUpActionName = generateAutoScaleScaleUpActionName(vmGroupIdentifier); + String mtName = generateSnmpMetricTableName(vmGroupIdentifier); + String monitorName = generateSnmpMonitorName(vmGroupIdentifier); + AutoScaleVmGroupTO vmGroupTO = loadBalancerTO.getAutoScaleVmGroupTO(); + AutoScaleVmProfileTO profileTO = vmGroupTO.getProfile(); + List policies = vmGroupTO.getPolicies(); + int interval = vmGroupTO.getInterval(); + List> counterParams = profileTO.getCounterParamList(); + String snmpCommunity = null; + int snmpPort = DEFAULT_SNMP_PORT; + long cur_prirotiy = 1; + + // get the session persistence parameters + List> paramsList = profileTO.getCounterParamList(); + for(Pair param : paramsList) { + if ("snmpcommunity".equalsIgnoreCase(param.first())) { + snmpCommunity = param.second(); + } else if ("snmpport".equalsIgnoreCase(param.first())) { + snmpPort = Integer.parseInt(param.second()); + } + } + + try + { + // Set min and max autoscale members; + // add lb vserver lb http 10.102.31.100 80 -minAutoscaleMinMembers 3 -maxAutoscaleMembers 10 + int minAutoScaleMembers = vmGroupTO.getMinMembers(); + int maxAutoScaleMembers = vmGroupTO.getMaxMembers(); + lbvserver vserver = new lbvserver(); + try { + vserver.set_name(nsVirtualServerName); + vserver.set_minautoscalemembers(minAutoScaleMembers); + vserver.set_maxautoscalemembers(maxAutoScaleMembers); + vserver.update(_netscalerService, vserver); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + /* AutoScale Config */ + // Add AutoScale Profile + // add autoscale profile lb_asprofile CLOUDSTACK -url -http:// 10.102.31.34:8080/client/api- -apiKey abcdef + // -sharedSecret xyzabc + String apiKey = profileTO.getAutoScaleUserApiKey(); + String secretKey = profileTO.getAutoScaleUserSecretKey(); + String url = profileTO.getCloudStackApiUrl(); + + autoscaleprofile autoscaleProfile = new autoscaleprofile(); + try { + autoscaleProfile.set_name(profileName); + autoscaleProfile.set_type("CLOUDSTACK"); + autoscaleProfile.set_apikey(apiKey); + autoscaleProfile.set_sharedsecret(secretKey); + autoscaleProfile.set_url(url); + autoscaleProfile.add(_netscalerService, autoscaleProfile); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Add Timer + nstimer timer = new nstimer(); + try { + timer.set_name(timerName); + timer.set_interval(interval); + timer.add(_netscalerService, timer); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // AutoScale Actions + Integer scaleUpQuietTime = null; + Integer scaleDownQuietTime = null; + for (AutoScalePolicyTO autoScalePolicyTO : policies) { + if(scaleUpQuietTime == null) { + if(isScaleUpPolicy(autoScalePolicyTO)) { + scaleUpQuietTime = autoScalePolicyTO.getQuietTime(); + if(scaleDownQuietTime != null) { + break; + } + } + } + if(scaleDownQuietTime == null) { + if(isScaleDownPolicy(autoScalePolicyTO)) { + scaleDownQuietTime = autoScalePolicyTO.getQuietTime(); + if(scaleUpQuietTime != null) { + break; + } + } + } + } + + // Add AutoScale ScaleUp action + // add autoscale action lb_scaleUpAction provision -vserver lb -profilename lb_asprofile -params + // -lbruleid=1234&command=deployvm&zoneid=10&templateid=5&serviceofferingid=3- -quiettime 300 + com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleUpAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); + try { + scaleUpAction.set_name(scaleUpActionName); + scaleUpAction.set_type("SCALE_UP"); // TODO: will this be called provision? + scaleUpAction.set_vserver(nsVirtualServerName); // Actions Vserver, the one that is autoscaled, with CS + // now both are same. Not exposed in API. + scaleUpAction.set_profilename(profileName); + scaleUpAction.set_quiettime(scaleUpQuietTime); + String scaleUpParameters = "command=deployVirtualMachine" + "&" + + ApiConstants.ZONE_ID + "=" + profileTO.getZoneId()+ "&" + + ApiConstants.SERVICE_OFFERING_ID + "=" + profileTO.getServiceOfferingId()+ "&" + + ApiConstants.TEMPLATE_ID + "=" + profileTO.getTemplateId()+ "&" + + ApiConstants.DISPLAY_NAME + "=" + profileTO.getVmName()+ "&" + + ((profileTO.getNetworkId() == null)? "" : (ApiConstants.NETWORK_IDS + "=" + profileTO.getNetworkId()+ "&")) + + ((profileTO.getOtherDeployParams() == null)? "" : (profileTO.getOtherDeployParams() + "&")) + + "lbruleid=" + loadBalancerTO.getUuid(); + scaleUpAction.set_parameters(scaleUpParameters); + scaleUpAction.add(_netscalerService, scaleUpAction); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleDownAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); + Integer destroyVmGracePeriod = profileTO.getDestroyVmGraceperiod(); + try { + scaleDownAction.set_name(scaleDownActionName); + scaleDownAction.set_type("SCALE_DOWN"); // TODO: will this be called de-provision? + scaleDownAction.set_vserver(nsVirtualServerName); // TODO: no global option as of now through Nitro. + // Testing cannot be done. + scaleDownAction.set_profilename(profileName); + scaleDownAction.set_quiettime(scaleDownQuietTime); + String scaleDownParameters = "command=destroyVirtualMachine" + "&" + + "lbruleid=" + loadBalancerTO.getUuid(); + scaleDownAction.set_parameters(scaleDownParameters); + scaleDownAction.set_vmdestroygraceperiod(destroyVmGracePeriod); + scaleDownAction.add(_netscalerService, scaleDownAction); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + /* Create min member policy */ + String minMemberPolicyName = generateAutoScaleMinPolicyName(vmGroupIdentifier); + String minMemberPolicyExp = "SYS.VSERVER(\"" + nsVirtualServerName + "\").ACTIVESERVICES.LT(SYS.VSERVER(\"" + nsVirtualServerName + "\").MINAUTOSCALEMEMBERS)"; + addAutoScalePolicy(timerName, minMemberPolicyName, cur_prirotiy++, minMemberPolicyExp, scaleUpActionName, + interval, interval, isCleanUp); + + /* Create max member policy */ + String maxMemberPolicyName = generateAutoScaleMaxPolicyName(vmGroupIdentifier); + String maxMemberPolicyExp = "SYS.VSERVER(\"" + nsVirtualServerName + "\").ACTIVESERVICES.GT(SYS.VSERVER(\"" + nsVirtualServerName + "\").MAXAUTOSCALEMEMBERS)"; + addAutoScalePolicy(timerName, maxMemberPolicyName, cur_prirotiy++, maxMemberPolicyExp, scaleDownActionName, + interval, interval, isCleanUp); + + /* Create Counters */ + HashMap snmpMetrics = new HashMap(); + for (AutoScalePolicyTO autoScalePolicyTO : policies) { + List conditions = autoScalePolicyTO.getConditions(); + String policyExpression = ""; + int snmpCounterNumber = 0; + for (ConditionTO conditionTO : conditions) { + CounterTO counterTO = conditionTO.getCounter(); + String counterName = counterTO.getName(); + String operator = conditionTO.getRelationalOperator(); + long threshold = conditionTO.getThreshold(); + + StringBuilder conditionExpression = new StringBuilder(); + Formatter formatter = new Formatter(conditionExpression, Locale.US); + + if(counterTO.getSource().equals("snmp")) + { + counterName = generateSnmpMetricName(counterName); + if(snmpMetrics.size() == 0) { + // Create Metric Table + //add lb metricTable lb_metric_table + lbmetrictable metricTable = new lbmetrictable(); + try { + metricTable.set_metrictable(mtName); + metricTable.add(_netscalerService, metricTable); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Create Monitor + // add lb monitor lb_metric_table_mon LOAD -destPort 161 -snmpCommunity public -metricTable + // lb_metric_table -interval + lbmonitor monitor = new lbmonitor(); + try { + monitor.set_monitorname(monitorName); + monitor.set_type("LOAD"); + monitor.set_destport(snmpPort); + monitor.set_snmpcommunity(snmpCommunity); + monitor.set_metrictable(mtName); + monitor.set_interval((int)(interval * 0.8)); + monitor.add(_netscalerService, monitor); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Bind monitor to servicegroup. + // bind lb monitor lb_metric_table_mon lb_autoscaleGroup -passive + servicegroup_lbmonitor_binding servicegroup_monitor_binding = new servicegroup_lbmonitor_binding(); + try { + servicegroup_monitor_binding.set_servicegroupname(serviceGroupName); + servicegroup_monitor_binding.set_monitor_name(monitorName); + + // Use the monitor for autoscaling purpose only. + // Don't mark service members down when metric breaches threshold + servicegroup_monitor_binding.set_passive(true); + + servicegroup_lbmonitor_binding.add(_netscalerService, servicegroup_monitor_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + } + + boolean newMetric = !snmpMetrics.containsKey(counterName); + if(newMetric) { + snmpMetrics.put(counterName, snmpCounterNumber++); + } + + if(newMetric) + { + // bind lb metricTable lb_metric_table mem 1.3.6.1.4.1.2021.11.9.0 + String counterOid = counterTO.getValue(); + lbmetrictable_metric_binding metrictable_metric_binding = new lbmetrictable_metric_binding(); + try { + metrictable_metric_binding.set_metrictable(mtName); + metrictable_metric_binding.set_metric(counterName); + metrictable_metric_binding.set_Snmpoid(counterOid); + metrictable_metric_binding.add(_netscalerService, metrictable_metric_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // bind lb monitor lb_metric_table_mon -metric cpu -metricThreshold 1 + lbmonitor_metric_binding monitor_metric_binding = new lbmonitor_metric_binding();; + try { + monitor_metric_binding.set_monitorname(monitorName); + monitor_metric_binding.set_metric(counterName); + /* + * Setting it to max to make sure traffic is not affected due to 'LOAD' monitoring. + * For Ex. if CPU is tracked and CPU is greater than 80, it is still < than Integer.MAX_VALUE + * so traffic will continue to flow. + */ + monitor_metric_binding.set_metricthreshold(Integer.MAX_VALUE); + monitor_metric_binding.add(_netscalerService, monitor_metric_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + } + // SYS.VSERVER("abcd").SNMP_TABLE(0).AVERAGE_VALUE.GT(80) + int counterIndex = snmpMetrics.get(counterName); // TODO: temporary fix. later on counter name + // will be added as a param to SNMP_TABLE. + formatter.format("SYS.VSERVER(\"%s\").SNMP_TABLE(%d).AVERAGE_VALUE.%s(%d)",nsVirtualServerName, counterIndex, operator, threshold); + } + else if (counterTO.getSource().equals("netscaler")) + { + //SYS.VSERVER("abcd").RESPTIME.GT(10) + formatter.format("SYS.VSERVER(\"%s\").%s.%s(%d)",nsVirtualServerName, counterTO.getValue(), operator, threshold); + } + if(policyExpression.length() != 0) { + policyExpression += " && "; + } + policyExpression += conditionExpression; + } + policyExpression = "(" + policyExpression + ")"; + + String policyId = Long.toString(autoScalePolicyTO.getId()); + String policyName = generateAutoScalePolicyName(vmGroupIdentifier, policyId); + String action = null; + if(isScaleUpPolicy(autoScalePolicyTO)) { + action = scaleUpActionName; + String scaleUpCondition = "SYS.VSERVER(\"" + nsVirtualServerName + "\").ACTIVESERVICES.LT(SYS.VSERVER(\"" + nsVirtualServerName + "\").MAXAUTOSCALEMEMBERS)"; + policyExpression = scaleUpCondition + " && " + policyExpression; + } else { + action = scaleDownActionName; + String scaleDownCondition = "SYS.VSERVER(\"" + nsVirtualServerName + "\").ACTIVESERVICES.GT(SYS.VSERVER(\"" + nsVirtualServerName + "\").MINAUTOSCALEMEMBERS)"; + policyExpression = scaleDownCondition + " && " + policyExpression; + } + + addAutoScalePolicy(timerName, policyName, cur_prirotiy++, policyExpression, action, + autoScalePolicyTO.getDuration(), interval, isCleanUp); + + } + } catch (Exception ex) { + if(!isCleanUp) { + // Normal course, exception has occurred + disableAutoScaleConfig(loadBalancerTO, true); + throw ex; + + } else { + // Programming error. Exception should never be thrown afterall. + throw ex; + } + } + + return true; + } + + @SuppressWarnings("static-access") + private synchronized boolean disableAutoScaleConfig(LoadBalancerTO loadBalancerTO, boolean isCleanUp) throws Exception { + + String vmGroupIdentifier = generateAutoScaleVmGroupIdentifier(loadBalancerTO); + + String profileName = generateAutoScaleProfileName(vmGroupIdentifier); + String timerName = generateAutoScaleTimerName(vmGroupIdentifier); + String scaleDownActionName = generateAutoScaleScaleDownActionName(vmGroupIdentifier); + String scaleUpActionName = generateAutoScaleScaleUpActionName(vmGroupIdentifier); + String mtName = generateSnmpMetricTableName(vmGroupIdentifier); + String monitorName = generateSnmpMonitorName(vmGroupIdentifier); + String serviceGroupName = generateAutoScaleServiceGroupName(loadBalancerTO); + AutoScaleVmGroupTO vmGroupTO = loadBalancerTO.getAutoScaleVmGroupTO(); + List policies = vmGroupTO.getPolicies(); + String minMemberPolicyName = generateAutoScaleMinPolicyName(vmGroupIdentifier); + String maxMemberPolicyName = generateAutoScaleMaxPolicyName(vmGroupIdentifier); + + try { + + /* Delete min/max member policies */ + + removeAutoScalePolicy(timerName, minMemberPolicyName, isCleanUp); + + removeAutoScalePolicy(timerName, maxMemberPolicyName, isCleanUp); + + boolean isSnmp = false; + /* Create Counters */ + for (AutoScalePolicyTO autoScalePolicyTO : policies) { + List conditions = autoScalePolicyTO.getConditions(); + for (ConditionTO conditionTO : conditions) { + CounterTO counterTO = conditionTO.getCounter(); + if(counterTO.getSource().equals("snmp")) { + isSnmp = true; + break; + } + } + String policyId = Long.toString(autoScalePolicyTO.getId()); + String policyName = generateAutoScalePolicyName(vmGroupIdentifier, policyId); + + // Removing Timer policy + removeAutoScalePolicy(timerName, policyName, isCleanUp); + } + + /* Delete AutoScale Config */ + // Delete AutoScale ScaleDown action + com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleDownAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); + try { + scaleDownAction.set_name(scaleDownActionName); + scaleDownAction.delete(_netscalerService, scaleDownAction); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Delete AutoScale ScaleUp action + com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction scaleUpAction = new com.citrix.netscaler.nitro.resource.config.autoscale.autoscaleaction(); + try { + scaleUpAction.set_name(scaleUpActionName); + scaleUpAction.delete(_netscalerService, scaleUpAction); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Delete Timer + nstimer timer = new nstimer(); + try { + timer.set_name(timerName); + timer.delete(_netscalerService, timer); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Delete AutoScale Profile + autoscaleprofile autoscaleProfile = new autoscaleprofile(); + try { + autoscaleProfile.set_name(profileName); + autoscaleProfile.delete(_netscalerService, autoscaleProfile); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + if(isSnmp) { + servicegroup_lbmonitor_binding servicegroup_monitor_binding = new servicegroup_lbmonitor_binding(); + try { + servicegroup_monitor_binding.set_monitor_name(monitorName); + servicegroup_monitor_binding.set_servicegroupname(serviceGroupName); + servicegroup_lbmonitor_binding.delete(_netscalerService, servicegroup_monitor_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Delete Monitor + // rm lb monitor lb_metric_table_mon + com.citrix.netscaler.nitro.resource.config.lb.lbmonitor monitor = new com.citrix.netscaler.nitro.resource.config.lb.lbmonitor(); + try { + monitor.set_monitorname(monitorName); + monitor.set_type("LOAD"); + monitor.delete(_netscalerService, monitor); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Delete Metric Table + com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable metricTable = new com.citrix.netscaler.nitro.resource.config.lb.lbmetrictable(); + try { + metricTable.set_metrictable(mtName); + metricTable.delete(_netscalerService, metricTable); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + } + } catch (Exception ex) { + if(!isCleanUp) { + // Normal course, exception has occurred + enableAutoScaleConfig(loadBalancerTO, true); + throw ex; + } else { + // Programming error + throw ex; + } + } + + return true; + } + + private synchronized void addAutoScalePolicy(String timerName,String policyName, long priority, String policyExpression, String action, + int duration, int interval, boolean isCleanUp) throws Exception { + // Adding a autoscale policy + // add timer policy lb_policy_scaleUp_cpu_mem -rule - (SYS.CUR_VSERVER.METRIC_TABLE(cpu).AVG_VAL.GT(80)- + // -action lb_scaleUpAction + autoscalepolicy timerPolicy = new autoscalepolicy(); + try { + timerPolicy.set_name(policyName); + timerPolicy.set_action(action); + timerPolicy.set_rule(policyExpression); + timerPolicy.add(_netscalerService, timerPolicy); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // bind timer policy + // For now it is bound globally. + // bind timer trigger lb_astimer -policyName lb_policy_scaleUp -vserver lb -priority 1 -samplesize 5 + // TODO: later bind to lbvserver. bind timer trigger lb_astimer -policyName lb_policy_scaleUp -vserver lb + // -priority 1 -samplesize 5 + // -thresholdsize 5 + nstimer_autoscalepolicy_binding timer_policy_binding = new nstimer_autoscalepolicy_binding(); + int sampleSize = duration/interval; + try { + timer_policy_binding.set_name(timerName); + timer_policy_binding.set_policyname(policyName); + timer_policy_binding.set_samplesize(sampleSize); + timer_policy_binding.set_threshold(sampleSize); // We are not exposing this parameter as of now. + // i.e. n(m) is not exposed to CS user. So thresholdSize == sampleSize + timer_policy_binding.set_priority(priority); + timer_policy_binding.add(_netscalerService, timer_policy_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + } + + private void removeAutoScalePolicy(String timerName, String policyName, boolean isCleanUp) throws Exception { + // unbind timer policy + // unbbind timer trigger lb_astimer -policyName lb_policy_scaleUp + nstimer_autoscalepolicy_binding timer_policy_binding = new nstimer_autoscalepolicy_binding(); + try { + timer_policy_binding.set_name(timerName); + timer_policy_binding.set_policyname(policyName); + timer_policy_binding.delete(_netscalerService, timer_policy_binding); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + // Removing Timer policy + // rm timer policy lb_policy_scaleUp_cpu_mem + autoscalepolicy timerPolicy = new autoscalepolicy(); + try { + timerPolicy.set_name(policyName); + timerPolicy.delete(_netscalerService, timerPolicy); + } catch (Exception e) { + // Ignore Exception on cleanup + if (!isCleanUp) + throw e; + } + + } + + private boolean isAutoScaleSupportedInNetScaler() throws ExecutionException { + autoscaleprofile autoscaleProfile = new autoscaleprofile(); + try { + autoscaleProfile.get(_netscalerService); + } catch (Exception ex) { + // Looks like autoscale is not supported in this netscaler. + // TODO: Config team has introduce a new command to check + // the list of entities supported in a NetScaler. Can use that + // once it is present in AutoScale branch. + s_logger.warn("AutoScale is not supported in NetScaler"); + return false; + } + return true; + } + + private boolean isScaleUpPolicy(AutoScalePolicyTO autoScalePolicyTO) { + return autoScalePolicyTO.getAction().equals("scaleup"); + } + + private boolean isScaleDownPolicy(AutoScalePolicyTO autoScalePolicyTO) { + return autoScalePolicyTO.getAction().equals("scaledown"); + } + private void saveConfiguration() throws ExecutionException { try { apiCallResult = nsconfig.save(_netscalerService); @@ -1429,14 +2182,14 @@ public class NetscalerResource implements ServerResource { lbvserver vserver = lbvserver.get(_netscalerService, lbvserverName); if(vserver != null){ String lbVirtualServerIp = vserver.get_ipv46(); - + long[] bytesSentAndReceived = answer.ipBytes.get(lbVirtualServerIp); if (bytesSentAndReceived == null) { bytesSentAndReceived = new long[]{0, 0}; } bytesSentAndReceived[0] += stat_entry.get_totalrequestbytes(); bytesSentAndReceived[1] += stat_entry.get_totalresponsebytes(); - + if (bytesSentAndReceived[0] >= 0 && bytesSentAndReceived[1] >= 0) { answer.ipBytes.put(lbVirtualServerIp, bytesSentAndReceived); } @@ -1484,6 +2237,61 @@ public class NetscalerResource implements ServerResource { return genObjectName("Cloud-Service", ip, port); } + private String generateAutoScaleVmGroupIdentifier(LoadBalancerTO lbTO) { + return lbTO.getSrcIp() + "-" + lbTO.getSrcPort(); + } + + private String generateAutoScaleServiceGroupName(LoadBalancerTO lbTO) { + /* + * ServiceGroup name in NetScaler wont support long names. Providing special name. + * Need for introducing uuid because every vmgroup creation should be distinguished. + * Ex. (1) create a vm group, delete a vmgroup, create a vmgroup on same lb ip and port + * This will reuse all vms from the original vm group in step (1) + */ + + return "Cloud" + lbTO.getAutoScaleVmGroupTO().getUuid().replace("-", ""); + } + + private String generateAutoScaleTimerName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-Timer", vmGroupIdentifier); + } + + private String generateAutoScaleProfileName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-Profile", vmGroupIdentifier); + } + + private String generateAutoScaleScaleUpActionName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-ScaleUpAction", vmGroupIdentifier); + } + + private String generateAutoScaleScaleDownActionName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-ScaleDownAction", vmGroupIdentifier); + } + + private String generateAutoScalePolicyName(String vmGroupIdentifier, String poilcyId) { + return genObjectName("Cloud-AutoScale-Policy", vmGroupIdentifier, poilcyId); + } + + private String generateAutoScaleMinPolicyName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-Policy-Min", vmGroupIdentifier); + } + + private String generateAutoScaleMaxPolicyName(String vmGroupIdentifier) { + return genObjectName("Cloud-AutoScale-Policy-Max", vmGroupIdentifier); + } + + private String generateSnmpMetricTableName(String vmGroupIdentifier) { + return genObjectName("Cloud-MTbl", vmGroupIdentifier); + } + + private String generateSnmpMonitorName(String vmGroupIdentifier) { + return genObjectName("Cloud-Mon", vmGroupIdentifier); + } + + private String generateSnmpMetricName(String counterName) { + return counterName.replace(' ', '_'); + } + private String genObjectName(Object... args) { String objectName = ""; for (int i = 0; i < args.length; i++) { @@ -1514,7 +2322,7 @@ public class NetscalerResource implements ServerResource { public void setAgentControl(IAgentControl agentControl) { return; } - + @Override public String getName() { return _name; @@ -1528,7 +2336,7 @@ public class NetscalerResource implements ServerResource { @Override public boolean stop() { return true; - } + } @Override public void disconnected() { diff --git a/plugins/network-elements/nicira-nvp/README.NiciraIntegration b/plugins/network-elements/nicira-nvp/README.NiciraIntegration deleted file mode 100644 index 4019c17f9fe..00000000000 --- a/plugins/network-elements/nicira-nvp/README.NiciraIntegration +++ /dev/null @@ -1,87 +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. ------------------------------------------------------------ - - -Nicira Network Virtualization Platform (NVP) integration code is contributed -by Nicira and Schuberg Philis and copyright is donated to the Apache Software -Foundation. - -Authors - Somik Behera - Hugo Trippaers - -== New API Calls - -The following API calls are added to CloudStack to support the integrations with -the Nicira NVP platform. Please see the API documentation of CloudStack for -parameters and return values. - - * addNiciraNvpDevice - * deleteNiciraNvpDevice - * listNiciraNvpDevices - * listNiciraNvpDeviceNetworks - -== How to enable the Nicira NVP integration. - -When configuring a zone create a new physical network for "Guest" traffic and -select "STT" as the isolation type. Set the Xen traffic label for "Guest" -traffic to the label of the integration bridge (refer to the Nicira -Documentation for setting up the integration bridge). Note that this requires -all traffic types to have their traffic labels set. - -These steps are specified by the API calls as there is currently no GUI -available. - -1. addNetworkServiceProvider - name="NiciraNvp", physicalnetworkid=, - servicelist="Connectivity" -2. updateNetworkServiceProvider - id=, state="Enabled" -3. addNiciraNvpDevice - physicalnetworkid=, - hostname= - username= - password= - transportzoneuuid= - -== How to use the Nicira integration - -When creating a guest network make sure it is created in the physical network -with the isolation type set to "STT". When the first virtual machine is -launched in this network the NiciraNvpNetworkGuru will configure a logical -switch on the NVP Controller. During the startup of a virtual machine the -NiciraNvpElement will create a logical port for any NICs in the guest networks -and attach the port to the existing logical swith. - -== Debugging/Troubleshooting - -All elements created on the NVP controller have tags with the name of the -account, this can be used to search the items using the NVP manager. The NVP -uuid of the logical switch is also stored in the BroadcastUri of the -corresponding Guest network in an lswitch uri scheme. The CloudStack uuid of -the NIC is used to make the Vif attachement on the logical switchport. - -The following classes should be set to log level debug when troubleshooting. - com.cloud.network - (Most NiciraNvp related objects live in this package and subpackages) - org.apache.commons.httpclient - (used by NiciraNvpApi to make calls to the SDN Controller) - httpclient.wire - (wirelevel http tracing of httpclient) - -Please report any findings to the developer mailing list. 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/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java new file mode 100644 index 00000000000..40bde6c6e74 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterAnswer.java @@ -0,0 +1,34 @@ +// 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; + +/** + * + */ +public class ConfigurePortForwardingRulesOnLogicalRouterAnswer extends Answer { + + public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, + boolean success, String details) { + super(command, success, details); + } + + public ConfigurePortForwardingRulesOnLogicalRouterAnswer(Command command, + Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java new file mode 100644 index 00000000000..5f0ea384af3 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePortForwardingRulesOnLogicalRouterCommand.java @@ -0,0 +1,60 @@ +// 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 java.util.List; + +import com.cloud.agent.api.to.PortForwardingRuleTO; + +/** + * + */ +public class ConfigurePortForwardingRulesOnLogicalRouterCommand extends Command { + + private String logicalRouterUuid; + private List rules; + + public ConfigurePortForwardingRulesOnLogicalRouterCommand(String logicalRouterUuid, List rules) { + this.logicalRouterUuid = logicalRouterUuid; + this.rules = rules; + } + + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } + + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } + + /* (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java new file mode 100644 index 00000000000..12b1a1ffb3f --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterAnswer.java @@ -0,0 +1,30 @@ +// 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; + +public class ConfigurePublicIpsOnLogicalRouterAnswer extends Answer { + + public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, + boolean success, String details) { + super(command, success, details); + } + + public ConfigurePublicIpsOnLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java new file mode 100644 index 00000000000..8ee3793ed89 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigurePublicIpsOnLogicalRouterCommand.java @@ -0,0 +1,65 @@ +// 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 java.util.List; + +public class ConfigurePublicIpsOnLogicalRouterCommand extends Command { + + private String logicalRouterUuid; + private String l3GatewayServiceUuid; + private List publicCidrs; + + public ConfigurePublicIpsOnLogicalRouterCommand(String logicalRouterUuid, + String l3GatewayServiceUuid, + List publicCidrs) { + super(); + this.logicalRouterUuid = logicalRouterUuid; + this.publicCidrs = publicCidrs; + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } + + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } + + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } + + public String getL3GatewayServiceUuid() { + return l3GatewayServiceUuid; + } + + public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } + + public List getPublicCidrs() { + return publicCidrs; + } + + public void setPublicCidrs(List publicCidrs) { + this.publicCidrs = publicCidrs; + } + + @Override + public boolean executeInSequence() { + return false; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java new file mode 100644 index 00000000000..463dd4628cf --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterAnswer.java @@ -0,0 +1,43 @@ +// 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; + +/** + * + */ +public class ConfigureStaticNatRulesOnLogicalRouterAnswer extends Answer { + + /** + * @param command + * @param success + * @param details + */ + public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, + boolean success, String details) { + super(command, success, details); + } + + /** + * @param command + * @param e + */ + public ConfigureStaticNatRulesOnLogicalRouterAnswer(Command command, + Exception e) { + super(command, e); + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.java new file mode 100644 index 00000000000..960f609cb54 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/ConfigureStaticNatRulesOnLogicalRouterCommand.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.agent.api; + +import java.util.List; + +import com.cloud.agent.api.to.StaticNatRuleTO; + +/** + * + */ +public class ConfigureStaticNatRulesOnLogicalRouterCommand extends Command { + + private String logicalRouterUuid; + private List rules; + + public ConfigureStaticNatRulesOnLogicalRouterCommand( + String logicalRouterUuid, List rules) { + super(); + this.logicalRouterUuid = logicalRouterUuid; + this.rules = rules; + + } + + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } + + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } + + public List getRules() { + return rules; + } + + public void setRules(List rules) { + this.rules = rules; + } + + /* (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java new file mode 100644 index 00000000000..4a09e449af8 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterAnswer.java @@ -0,0 +1,40 @@ +// 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; + +/** + * + */ +public class CreateLogicalRouterAnswer extends Answer { + + private String _logicalRouterUuid; + + public CreateLogicalRouterAnswer(Command command, boolean success, + String details, String logicalRouterUuid) { + super(command, success, details); + this._logicalRouterUuid = logicalRouterUuid; + } + + public CreateLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } + + public String getLogicalRouterUuid() { + return _logicalRouterUuid; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java new file mode 100644 index 00000000000..57440dfc4b0 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/CreateLogicalRouterCommand.java @@ -0,0 +1,115 @@ +// 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; + +/** + * + */ +public class CreateLogicalRouterCommand extends Command { + private String _gatewayServiceUuid; + private String _logicalSwitchUuid; + private long _vlanId; + private String _name; + private String _ownerName; + private String _publicIpCidr; + private String _publicNextHop; + private String _internalIpCidr; + + public CreateLogicalRouterCommand(String gatewayServiceUuid, long vlanId, + String logicalSwitchUuid, String name, + String publicIpCidr, String publicNextHop, + String internalIpCidr, String ownerName) { + super(); + this._gatewayServiceUuid = gatewayServiceUuid; + this._logicalSwitchUuid = logicalSwitchUuid; + this._vlanId = vlanId; + this._name = name; + this._ownerName = ownerName; + this._publicIpCidr = publicIpCidr; + this._publicNextHop = publicNextHop; + this._internalIpCidr = internalIpCidr; + } + + @Override + public boolean executeInSequence() { + return false; + } + + public String getGatewayServiceUuid() { + return _gatewayServiceUuid; + } + + public void setGatewayServiceUuid(String gatewayServiceUuid) { + this._gatewayServiceUuid = gatewayServiceUuid; + } + + public String getLogicalSwitchUuid() { + return _logicalSwitchUuid; + } + + public void setLogicalSwitchUuid(String logicalSwitchUuid) { + _logicalSwitchUuid = logicalSwitchUuid; + } + + public long getVlanId() { + return _vlanId; + } + + public void setVlanId(long vlanId) { + this._vlanId = vlanId; + } + + public String getName() { + return _name; + } + + public void setName(String name) { + this._name = name; + } + + public String getOwnerName() { + return _ownerName; + } + + public void setOwnerName(String ownerName) { + this._ownerName = ownerName; + } + + public String getPublicIpCidr() { + return _publicIpCidr; + } + + public void setPublicIpCidr(String publicIpCidr) { + this._publicIpCidr = publicIpCidr; + } + + public String getInternalIpCidr() { + return _internalIpCidr; + } + + public void setInternalIpCidr(String internalIpCidr) { + this._internalIpCidr = internalIpCidr; + } + + public String getPublicNextHop() { + return _publicNextHop; + } + + public void setPublicNextHop(String publicNextHop) { + this._publicNextHop = publicNextHop; + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java new file mode 100644 index 00000000000..8a6bb9f193a --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterAnswer.java @@ -0,0 +1,32 @@ +// 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; + +/** + * + */ +public class DeleteLogicalRouterAnswer extends Answer { + + public DeleteLogicalRouterAnswer(Command command, boolean success, + String details) { + super(command, success, details); + } + + public DeleteLogicalRouterAnswer(Command command, Exception e) { + super(command, e); + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java new file mode 100644 index 00000000000..4799f9e58fe --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/agent/api/DeleteLogicalRouterCommand.java @@ -0,0 +1,41 @@ +// 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; + +/** + * + */ +public class DeleteLogicalRouterCommand extends Command { + + private String _logicalRouterUuid; + + public DeleteLogicalRouterCommand(String logicalRouterUuid) { + this._logicalRouterUuid = logicalRouterUuid; + } + + /* (non-Javadoc) + * @see com.cloud.agent.api.Command#executeInSequence() + */ + @Override + public boolean executeInSequence() { + return false; + } + + public String getLogicalRouterUuid() { + return _logicalRouterUuid; + } +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java index 6eac21f7255..1734ce2ff3d 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/AddNiciraNvpDeviceCmd.java @@ -16,43 +16,35 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.APICommand; import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalLoadBalancerDeviceVO; import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Adds a Nicira NVP device") -public class AddNiciraNvpDeviceCmd extends BaseCmd { +@APICommand(name = "addNiciraNvpDevice", responseObject=NiciraNvpDeviceResponse.class, description="Adds a Nicira NVP device") +public class AddNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(AddNiciraNvpDeviceCmd.class.getName()); - private static final String s_name = "addniciranvpdevice"; + private static final String s_name = "addniciranvpdeviceresponse"; @PlugService NiciraNvpElementService _niciraNvpElementService; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, required=true, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + required=true, description="the Physical Network ID") private Long physicalNetworkId; @Parameter(name=ApiConstants.HOST_NAME, type=CommandType.STRING, required = true, description="Hostname of ip address of the Nicira NVP Controller.") @@ -67,6 +59,9 @@ public class AddNiciraNvpDeviceCmd extends BaseCmd { @Parameter(name=ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID, type=CommandType.STRING, required = true, description="The Transportzone UUID configured on the Nicira Controller") private String transportzoneuuid; + @Parameter(name=ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID, type=CommandType.STRING, required = false, description="The L3 Gateway Service UUID configured on the Nicira Controller") + private String l3gatewayserviceuuid; + ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// @@ -90,6 +85,10 @@ public class AddNiciraNvpDeviceCmd extends BaseCmd { public String getTransportzoneUuid() { return transportzoneuuid; } + + public String getL3GatewayServiceUuid() { + return l3gatewayserviceuuid; + } ///////////////////////////////////////////////////// /////////////// API Implementation/////////////////// @@ -123,4 +122,14 @@ public class AddNiciraNvpDeviceCmd extends BaseCmd { public long getEntityOwnerId() { return UserContext.current().getCaller().getId(); } + + @Override + public String getEventType() { + return EventTypes.EVENT_EXTERNAL_NVP_CONTROLLER_ADD; + } + + @Override + public String getEventDescription() { + return "Adding a Nicira Nvp Controller"; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java index 01a39466fd3..12544410599 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/DeleteNiciraNvpDeviceCmd.java @@ -16,16 +16,18 @@ // under the License. package com.cloud.api.commands; +import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; +import com.cloud.event.EventTypes; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -35,18 +37,18 @@ import com.cloud.network.element.NiciraNvpElementService; import com.cloud.user.UserContext; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=SuccessResponse.class, description=" delete a nicira nvp device") -public class DeleteNiciraNvpDeviceCmd extends BaseCmd { +@APICommand(name = "deleteNiciraNvpDevice", responseObject=SuccessResponse.class, description=" delete a nicira nvp device") +public class DeleteNiciraNvpDeviceCmd extends BaseAsyncCmd { private static final Logger s_logger = Logger.getLogger(DeleteNiciraNvpDeviceCmd.class.getName()); - private static final String s_name = "addniciranvpdevice"; + private static final String s_name = "deleteniciranvpdeviceresponse"; @PlugService NiciraNvpElementService _niciraNvpElementService; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required=true, description="Nicira device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + required=true, description="Nicira device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// @@ -89,4 +91,14 @@ public class DeleteNiciraNvpDeviceCmd extends BaseCmd { return UserContext.current().getCaller().getId(); } + @Override + public String getEventType() { + return EventTypes.EVENT_EXTERNAL_LB_DEVICE_DELETE; + } + + @Override + public String getEventDescription() { + return "Deleting Nicira Nvp Controller"; + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java index e8456cfa8f7..bea417d3687 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDeviceNetworksCmd.java @@ -19,30 +19,28 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import com.cloud.api.response.NiciraNvpDeviceResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.NetworkResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.NetworkResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Network; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NetworkResponse.class, description="lists network that are using a nicira nvp device") +@APICommand(name = "listNiciraNvpDeviceNetworks", responseObject=NetworkResponse.class, description="lists network that are using a nicira nvp device") public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListNiciraNvpDeviceNetworksCmd.class.getName()); @@ -53,8 +51,8 @@ public class ListNiciraNvpDeviceNetworksCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, required = true, description="nicira nvp device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + required = true, description="nicira nvp device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java index f9c157d9feb..04aab2a296a 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/commands/ListNiciraNvpDevicesCmd.java @@ -19,17 +19,17 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.PlugService; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.PlugService; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.api.response.NiciraNvpDeviceResponse; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -40,22 +40,22 @@ import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.element.NiciraNvpElementService; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices") +@APICommand(name = "listNiciraNvpDevices", responseObject=NiciraNvpDeviceResponse.class, description="Lists Nicira NVP devices") public class ListNiciraNvpDevicesCmd extends BaseListCmd { private static final Logger s_logger = Logger.getLogger(ListNiciraNvpDevicesCmd.class.getName()); - private static final String s_name = "listniciranvpdevices"; + private static final String s_name = "listniciranvpdeviceresponse"; @PlugService NiciraNvpElementService _niciraNvpElementService; ///////////////////////////////////////////////////// //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="physical_network") - @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.LONG, description="the Physical Network ID") + @Parameter(name=ApiConstants.PHYSICAL_NETWORK_ID, type=CommandType.UUID, entityType = PhysicalNetworkResponse.class, + description="the Physical Network ID") private Long physicalNetworkId; - @IdentityMapper(entityTableName="external_nicira_nvp_devices") - @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.LONG, description="nicira nvp device ID") + @Parameter(name=ApiConstants.NICIRA_NVP_DEVICE_ID, type=CommandType.UUID, entityType = NiciraNvpDeviceResponse.class, + description="nicira nvp device ID") private Long niciraNvpDeviceId; ///////////////////////////////////////////////////// diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java index d5c82b34a87..097ecd975b2 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/api/response/NiciraNvpDeviceResponse.java @@ -16,30 +16,42 @@ // under the License. package com.cloud.api.response; -import com.cloud.api.ApiConstants; +import com.cloud.network.NiciraNvpDeviceVO; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; -import com.cloud.utils.IdentityProxy; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; +import org.apache.cloudstack.api.EntityReference; +@EntityReference(value=NiciraNvpDeviceVO.class) public class NiciraNvpDeviceResponse extends BaseResponse { @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_ID) @Param(description="device id of the Nicire Nvp") - private IdentityProxy id = new IdentityProxy("external_nicira_nvp_devices"); - + private String id; + @SerializedName(ApiConstants.PHYSICAL_NETWORK_ID) @Param(description="the physical network to which this Nirica Nvp belongs to") - private IdentityProxy physicalNetworkId = new IdentityProxy("physical_network"); - + private String physicalNetworkId; + @SerializedName(ApiConstants.PROVIDER) @Param(description="name of the provider") private String providerName; - + @SerializedName(ApiConstants.NICIRA_NVP_DEVICE_NAME) @Param(description="device name") private String deviceName; - public void setId(long nvpDeviceId) { - this.id.setValue(nvpDeviceId); + @SerializedName(ApiConstants.HOST_NAME) @Param(description="the controller Ip address") + private String hostName; + + @SerializedName(ApiConstants.NICIRA_NVP_TRANSPORT_ZONE_UUID) @Param(description="the transport zone Uuid") + private String transportZoneUuid; + + @SerializedName(ApiConstants.NICIRA_NVP_GATEWAYSERVICE_UUID) @Param(description="this L3 gateway service Uuid") + private String l3GatewayServiceUuid; + + public void setId(String nvpDeviceId) { + this.id = nvpDeviceId; } - public void setPhysicalNetworkId(long physicalNetworkId) { - this.physicalNetworkId.setValue(physicalNetworkId); + public void setPhysicalNetworkId(String physicalNetworkId) { + this.physicalNetworkId = physicalNetworkId; } public void setProviderName(String providerName) { @@ -48,6 +60,20 @@ public class NiciraNvpDeviceResponse extends BaseResponse { public void setDeviceName(String deviceName) { this.deviceName = deviceName; - } - + } + + + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + public void setTransportZoneUuid(String transportZoneUuid) { + this.transportZoneUuid = transportZoneUuid; + } + + public void setL3GatewayServiceUuid(String l3GatewayServiceUuid) { + this.l3GatewayServiceUuid = l3GatewayServiceUuid; + } + } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java index af6620c722d..a1097b9ef1f 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpDeviceVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; @@ -27,7 +29,7 @@ import javax.persistence.Table; @Entity @Table(name="external_nicira_nvp_devices") -public class NiciraNvpDeviceVO { +public class NiciraNvpDeviceVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java index 0779e691e70..4c948cc965b 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpNicMappingVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="nicira_nvp_nic_map") -public class NiciraNvpNicMappingVO { +public class NiciraNvpNicMappingVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java new file mode 100644 index 00000000000..ced880fe619 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/NiciraNvpRouterMappingVO.java @@ -0,0 +1,81 @@ +// 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; + +import org.apache.cloudstack.api.InternalIdentity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name="nicira_nvp_router_map") +public class NiciraNvpRouterMappingVO implements InternalIdentity { + //FIXME the ddl for this table should be in one of the upgrade scripts + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="logicalrouter_uuid") + private String logicalRouterUuid; + + @Column(name="network_id") + private long networkId; + + public NiciraNvpRouterMappingVO() { + } + + public NiciraNvpRouterMappingVO(String logicalRouterUuid, long networkId) { + this.logicalRouterUuid = logicalRouterUuid; + this.networkId = networkId; + } + + public NiciraNvpRouterMappingVO(long id, String logicalRouterUuid, long networkId) { + this.id = id; + this.logicalRouterUuid = logicalRouterUuid; + this.networkId = networkId; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getLogicalRouterUuid() { + return logicalRouterUuid; + } + + public void setLogicalRouterUuid(String logicalRouterUuid) { + this.logicalRouterUuid = logicalRouterUuid; + } + + public long getNetworkId() { + return networkId; + } + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java new file mode 100644 index 00000000000..c6c58c8846f --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDao.java @@ -0,0 +1,25 @@ +// 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.dao; + +import com.cloud.network.NiciraNvpRouterMappingVO; +import com.cloud.utils.db.GenericDao; + +public interface NiciraNvpRouterMappingDao extends GenericDao { + + public NiciraNvpRouterMappingVO findByNetworkId(long id); +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java new file mode 100644 index 00000000000..091207c8896 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/dao/NiciraNvpRouterMappingDaoImpl.java @@ -0,0 +1,46 @@ +// 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.dao; + +import javax.ejb.Local; + +import com.cloud.network.NiciraNvpRouterMappingVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value=NiciraNvpRouterMappingDao.class) +public class NiciraNvpRouterMappingDaoImpl extends GenericDaoBase implements NiciraNvpRouterMappingDao { + + protected final SearchBuilder networkSearch; + + public NiciraNvpRouterMappingDaoImpl() { + networkSearch = createSearchBuilder(); + networkSearch.and("network_id", networkSearch.entity().getNetworkId(), Op.EQ); + networkSearch.done(); + } + + @Override + public NiciraNvpRouterMappingVO findByNetworkId(long id) { + SearchCriteria sc = networkSearch.create(); + sc.setParameters("network_id", id); + return findOneBy(sc); + } + + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java index c2971f495b5..78fa0832518 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/element/NiciraNvpElement.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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.element; import java.util.ArrayList; @@ -49,21 +32,36 @@ import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; +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.CreateLogicalSwitchPortAnswer; import com.cloud.agent.api.CreateLogicalSwitchPortCommand; +import com.cloud.agent.api.DeleteLogicalRouterAnswer; +import com.cloud.agent.api.DeleteLogicalRouterCommand; 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.StartupCommand; import com.cloud.agent.api.StartupNiciraNvpCommand; -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.api.ApiDBUtils; import com.cloud.api.commands.AddNiciraNvpDeviceCmd; import com.cloud.api.commands.DeleteNiciraNvpDeviceCmd; import com.cloud.api.commands.ListNiciraNvpDeviceNetworksCmd; import com.cloud.api.commands.ListNiciraNvpDevicesCmd; import com.cloud.api.response.NiciraNvpDeviceResponse; +import com.cloud.configuration.ConfigurationManager; +import com.cloud.dc.Vlan; +import com.cloud.dc.dao.VlanDao; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; @@ -75,35 +73,46 @@ 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.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkVO; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.IpAddress; +import com.cloud.network.NetworkManager; import com.cloud.network.NiciraNvpDeviceVO; import com.cloud.network.NiciraNvpNicMappingVO; +import com.cloud.network.NiciraNvpRouterMappingVO; +import com.cloud.network.PhysicalNetwork; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.network.PhysicalNetworkVO; +import com.cloud.network.PublicIpAddress; +import com.cloud.network.addr.PublicIp; import com.cloud.network.dao.NetworkDao; +import com.cloud.network.dao.NetworkServiceMapDao; import com.cloud.network.dao.NiciraNvpDao; import com.cloud.network.dao.NiciraNvpNicMappingDao; +import com.cloud.network.dao.NiciraNvpRouterMappingDao; import com.cloud.network.dao.PhysicalNetworkDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; -import com.cloud.network.guru.NiciraNvpGuestNetworkGuru; import com.cloud.network.resource.NiciraNvpResource; +import com.cloud.network.rules.PortForwardingRule; +import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; +import com.cloud.user.Account; import com.cloud.utils.component.AdapterBase; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; +import com.cloud.utils.net.NetUtils; import com.cloud.vm.NicProfile; import com.cloud.vm.NicVO; import com.cloud.vm.ReservationContext; @@ -113,12 +122,15 @@ import com.cloud.vm.dao.NicDao; @Component @Local(value = NetworkElement.class) -public class NiciraNvpElement extends AdapterBase implements ConnectivityProvider, NiciraNvpElementService, ResourceStateAdapter { - private static final Logger s_logger = Logger.getLogger(NiciraNvpElement.class); +public class NiciraNvpElement extends AdapterBase implements + ConnectivityProvider, SourceNatServiceProvider, + PortForwardingServiceProvider, StaticNatServiceProvider, + NiciraNvpElementService, ResourceStateAdapter, IpDeployer { + private static final Logger s_logger = Logger + .getLogger(NiciraNvpElement.class); private static final Map> capabilities = setCapabilities(); - @Inject NicDao _nicDao; @Inject @@ -138,7 +150,17 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide @Inject NiciraNvpNicMappingDao _niciraNvpNicMappingDao; @Inject + NiciraNvpRouterMappingDao _niciraNvpRouterMappingDao; + @Inject NetworkDao _networkDao; + @Inject + NetworkManager _networkManager; + @Inject + ConfigurationManager _configMgr; + @Inject + NetworkServiceMapDao _ntwkSrvcDao; + @Inject + VlanDao _vlanDao; @Override public Map> getCapabilities() { @@ -150,11 +172,28 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide return Provider.NiciraNvp; } - private boolean canHandle(Network network) { + protected boolean canHandle(Network network, Service service) { + s_logger.debug("Checking if NiciraNvpElement can handle service " + + service.getName() + " on network " + network.getDisplayText()); if (network.getBroadcastDomainType() != BroadcastDomainType.Lswitch) { return false; } + if (!_networkManager.isProviderForNetwork(getProvider(), + network.getId())) { + s_logger.debug("NiciraNvpElement is not a provider for network " + + network.getDisplayText()); + return false; + } + + if (!_ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), + service, Network.Provider.NiciraNvp)) { + s_logger.debug("NiciraNvpElement can't provide the " + + service.getName() + " service on network " + + network.getDisplayText()); + return false; + } + return true; } @@ -162,7 +201,8 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide public boolean configure(String name, Map params) throws ConfigurationException { super.configure(name, params); - _resourceMgr.registerResourceStateAdapter(this.getClass().getSimpleName(), this); + _resourceMgr.registerResourceStateAdapter(this.getClass() + .getSimpleName(), this); return true; } @@ -171,11 +211,90 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide DeployDestination dest, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + s_logger.debug("entering NiciraNvpElement implement function for network " + + network.getDisplayText() + + " (state " + + network.getState() + + ")"); + + if (!canHandle(network, Service.Connectivity)) { + return false; + } - if (!canHandle(network)) { + if (network.getBroadcastUri() == null) { + s_logger.error("Nic has no broadcast Uri with the LSwitch Uuid"); return false; } + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + _hostDao.loadDetails(niciraNvpHost); + + Account owner = context.getAccount(); + + /** + * Lock the network as we might need to do multiple operations that + * should be done only once. + */ + Network lock = _networkDao.acquireInLockTable(network.getId(), + _networkManager.getNetworkLockTimeout()); + if (lock == null) { + throw new ConcurrentOperationException("Unable to lock network " + + network.getId()); + } + try { + // Implement SourceNat immediately as we have al the info already + if (_networkManager.isProviderSupportServiceInNetwork( + network.getId(), Service.SourceNat, Provider.NiciraNvp)) { + s_logger.debug("Apparently we are supposed to provide SourceNat on this network"); + + PublicIp sourceNatIp = _networkManager + .assignSourceNatIpAddressToGuestNetwork(owner, network); + String publicCidr = sourceNatIp.getAddress().addr() + "/" + + NetUtils.getCidrSize(sourceNatIp.getVlanNetmask()); + String internalCidr = network.getGateway() + "/" + + network.getCidr().split("/")[1]; + long vlanid = (Vlan.UNTAGGED.equals(sourceNatIp.getVlanTag())) ? 0 + : Long.parseLong(sourceNatIp.getVlanTag()); + + CreateLogicalRouterCommand cmd = new CreateLogicalRouterCommand( + niciraNvpHost.getDetail("l3gatewayserviceuuid"), vlanid, + network.getBroadcastUri().getSchemeSpecificPart(), + "router-" + network.getDisplayText(), publicCidr, + sourceNatIp.getGateway(), internalCidr, context + .getDomain().getName() + + "-" + + context.getAccount().getAccountName()); + CreateLogicalRouterAnswer answer = (CreateLogicalRouterAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); + if (answer.getResult() == false) { + s_logger.error("Failed to create Logical Router for network " + + network.getDisplayText()); + return false; + } + + // Store the uuid so we can easily find it during cleanup + NiciraNvpRouterMappingVO routermapping = + new NiciraNvpRouterMappingVO(answer.getLogicalRouterUuid(), network.getId()); + _niciraNvpRouterMappingDao.persist(routermapping); + } + } finally { + if (lock != null) { + _networkDao.releaseFromLockTable(lock.getId()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("Lock is released for network id " + + lock.getId() + " as a part of router startup in " + + dest); + } + } + } return true; } @@ -186,7 +305,7 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { - if (!canHandle(network)) { + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -197,44 +316,60 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide NicVO nicVO = _nicDao.findById(nic.getId()); - List devices = _niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); return false; } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - NiciraNvpNicMappingVO existingNicMap = _niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid()); + NiciraNvpNicMappingVO existingNicMap = _niciraNvpNicMappingDao + .findByNicUuid(nicVO.getUuid()); if (existingNicMap != null) { - FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchUuid(), + FindLogicalSwitchPortCommand findCmd = new FindLogicalSwitchPortCommand( + existingNicMap.getLogicalSwitchUuid(), existingNicMap.getLogicalSwitchPortUuid()); - FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) _agentMgr.easySend(niciraNvpHost.getId(), findCmd); + FindLogicalSwitchPortAnswer answer = (FindLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), findCmd); if (answer.getResult()) { - s_logger.warn("Existing Logical Switchport found for nic " + nic.getName() + " with uuid " + existingNicMap.getLogicalSwitchPortUuid()); - UpdateLogicalSwitchPortCommand cmd = new UpdateLogicalSwitchPortCommand(existingNicMap.getLogicalSwitchPortUuid(), - network.getBroadcastUri().getSchemeSpecificPart(), nicVO.getUuid(), - context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName()); + s_logger.warn("Existing Logical Switchport found for nic " + + nic.getName() + " with uuid " + + existingNicMap.getLogicalSwitchPortUuid()); + UpdateLogicalSwitchPortCommand cmd = new UpdateLogicalSwitchPortCommand( + existingNicMap.getLogicalSwitchPortUuid(), network + .getBroadcastUri().getSchemeSpecificPart(), + nicVO.getUuid(), context.getDomain().getName() + "-" + + context.getAccount().getAccountName(), + nic.getName()); _agentMgr.easySend(niciraNvpHost.getId(), cmd); return true; - } - else { - s_logger.error("Stale entry found for nic " + nic.getName() + " with logical switchport uuid " + existingNicMap.getLogicalSwitchPortUuid()); + } else { + s_logger.error("Stale entry found for nic " + nic.getName() + + " with logical switchport uuid " + + existingNicMap.getLogicalSwitchPortUuid()); _niciraNvpNicMappingDao.remove(existingNicMap.getId()); } } - CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand(network.getBroadcastUri().getSchemeSpecificPart(), nicVO.getUuid(), - context.getDomain().getName() + "-" + context.getAccount().getAccountName(), nic.getName()); - CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + CreateLogicalSwitchPortCommand cmd = new CreateLogicalSwitchPortCommand( + network.getBroadcastUri().getSchemeSpecificPart(), + nicVO.getUuid(), context.getDomain().getName() + "-" + + context.getAccount().getAccountName(), nic.getName()); + CreateLogicalSwitchPortAnswer answer = (CreateLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); if (answer == null || !answer.getResult()) { - s_logger.error ("CreateLogicalSwitchPortCommand failed"); + s_logger.error("CreateLogicalSwitchPortCommand failed"); return false; } - NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(network.getBroadcastUri().getSchemeSpecificPart(), answer.getLogicalSwitchPortUuid(), nicVO.getUuid()); + NiciraNvpNicMappingVO nicMap = new NiciraNvpNicMappingVO(network + .getBroadcastUri().getSchemeSpecificPart(), + answer.getLogicalSwitchPortUuid(), nicVO.getUuid()); _niciraNvpNicMappingDao.persist(nicMap); return true; @@ -246,7 +381,7 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network)) { + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -257,25 +392,31 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide NicVO nicVO = _nicDao.findById(nic.getId()); - List devices = _niciraNvpDao.listByPhysicalNetwork(network.getPhysicalNetworkId()); + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); if (devices.isEmpty()) { - s_logger.error("No NiciraNvp Controller on physical network " + network.getPhysicalNetworkId()); + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); return false; } NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); - NiciraNvpNicMappingVO nicMap = _niciraNvpNicMappingDao.findByNicUuid(nicVO.getUuid()); + NiciraNvpNicMappingVO nicMap = _niciraNvpNicMappingDao + .findByNicUuid(nicVO.getUuid()); if (nicMap == null) { s_logger.error("No mapping for nic " + nic.getName()); return false; } - DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand(nicMap.getLogicalSwitchUuid(), nicMap.getLogicalSwitchPortUuid()); - DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + DeleteLogicalSwitchPortCommand cmd = new DeleteLogicalSwitchPortCommand( + nicMap.getLogicalSwitchUuid(), + nicMap.getLogicalSwitchPortUuid()); + DeleteLogicalSwitchPortAnswer answer = (DeleteLogicalSwitchPortAnswer) _agentMgr + .easySend(niciraNvpHost.getId(), cmd); if (answer == null || !answer.getResult()) { - s_logger.error ("DeleteLogicalSwitchPortCommand failed"); + s_logger.error("DeleteLogicalSwitchPortCommand failed"); return false; } @@ -288,17 +429,54 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide public boolean shutdown(Network network, ReservationContext context, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network)) { + if (!canHandle(network, Service.Connectivity)) { + return false; + } + + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + + if (_networkManager.isProviderSupportServiceInNetwork(network.getId(), + Service.SourceNat, Provider.NiciraNvp)) { + s_logger.debug("Apparently we were providing SourceNat on this network"); + + // Deleting the LogicalRouter will also take care of all provisioned + // nat rules. + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.warn("No logical router uuid found for network " + + network.getDisplayText()); + // This might be cause by a failed deployment, so don't make shutdown fail as well. + return true; + } + + DeleteLogicalRouterCommand cmd = new DeleteLogicalRouterCommand(routermapping.getLogicalRouterUuid()); + DeleteLogicalRouterAnswer answer = + (DeleteLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + if (answer.getResult() == false) { + s_logger.error("Failed to delete LogicalRouter for network " + + network.getDisplayText()); return false; } + _niciraNvpRouterMappingDao.remove(routermapping.getId()); + } + return true; } @Override - public boolean destroy(Network network) + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { - if (!canHandle(network)) { + if (!canHandle(network, Service.Connectivity)) { return false; } @@ -320,24 +498,52 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide @Override public boolean canEnableIndividualServices() { - return false; + return true; } @Override public boolean verifyServicesCombination(Set services) { + // This element can only function in a Nicra Nvp based + // SDN network, so Connectivity needs to be present here + if (!services.contains(Service.Connectivity)) { + s_logger.warn("Unable to provide services without Connectivity service enabled for this element"); + return false; + } + if ((services.contains(Service.PortForwarding) || services.contains(Service.StaticNat)) && !services.contains(Service.SourceNat)) { + s_logger.warn("Unable to provide StaticNat and/or PortForwarding without the SourceNat service"); + return false; + } return true; } private static Map> setCapabilities() { Map> capabilities = new HashMap>(); + // L2 Support : SDN provisioning capabilities.put(Service.Connectivity, null); + + // L3 Support : Generic? + capabilities.put(Service.Gateway, null); + + // L3 Support : SourceNat + Map sourceNatCapabilities = new HashMap(); + sourceNatCapabilities.put(Capability.SupportedSourceNatTypes, + "peraccount"); + sourceNatCapabilities.put(Capability.RedundantRouter, "false"); + capabilities.put(Service.SourceNat, sourceNatCapabilities); + + // L3 Support : Port Forwarding + capabilities.put(Service.PortForwarding, null); + + // L3 support : StaticNat + capabilities.put(Service.StaticNat, null); + return capabilities; } @Override - public String getPropertiesFile() { - return "nicira-nvp_commands.properties"; + public String[] getPropertiesFiles() { + return new String[] { "nicira-nvp_commands.properties" }; } @Override @@ -345,30 +551,41 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide public NiciraNvpDeviceVO addNiciraNvpDevice(AddNiciraNvpDeviceCmd cmd) { ServerResource resource = new NiciraNvpResource(); String deviceName = Network.Provider.NiciraNvp.getName(); - NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName); + NetworkDevice networkDevice = NetworkDevice + .getNetworkDevice(deviceName); Long physicalNetworkId = cmd.getPhysicalNetworkId(); NiciraNvpDeviceVO niciraNvpDevice = null; - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find phyical network with ID: " + physicalNetworkId); + throw new InvalidParameterValueException( + "Could not find phyical network with ID: " + + physicalNetworkId); } long zoneId = physicalNetwork.getDataCenterId(); - PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao.findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder()); + PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao + .findByServiceProvider(physicalNetwork.getId(), + networkDevice.getNetworkServiceProvder()); if (ntwkSvcProvider == null) { - throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder() + - " is not enabled in the physical network: " + physicalNetworkId + "to add this device"); + throw new CloudRuntimeException("Network Service Provider: " + + networkDevice.getNetworkServiceProvder() + + " is not enabled in the physical network: " + + physicalNetworkId + "to add this device"); } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) { - throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName() + - " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device"); + throw new CloudRuntimeException("Network Service Provider: " + + ntwkSvcProvider.getProviderName() + + " is in shutdown state in the physical network: " + + physicalNetworkId + "to add this device"); } if (_niciraNvpDao.listByPhysicalNetwork(physicalNetworkId).size() != 0) { - throw new CloudRuntimeException("A NiciraNvp device is already configured on this physical network"); + throw new CloudRuntimeException( + "A NiciraNvp device is already configured on this physical network"); } - Map params = new HashMap(); + Map params = new HashMap(); params.put("guid", UUID.randomUUID().toString()); params.put("zoneId", String.valueOf(physicalNetwork.getDataCenterId())); params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId())); @@ -377,30 +594,40 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide params.put("adminuser", cmd.getUsername()); params.put("adminpass", cmd.getPassword()); params.put("transportzoneuuid", cmd.getTransportzoneUuid()); - params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase()); // FIXME What to do with multiple isolation types + // FIXME What to do with multiple isolation types + params.put("transportzoneisotype", + physicalNetwork.getIsolationMethods().get(0).toLowerCase()); + if (cmd.getL3GatewayServiceUuid() != null) { + params.put("l3gatewayserviceuuid", cmd.getL3GatewayServiceUuid()); + } - Map hostdetails = new HashMap(); + Map hostdetails = new HashMap(); hostdetails.putAll(params); - Transaction txn = Transaction.currentTxn(); try { resource.configure(cmd.getHost(), hostdetails); - Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params); + Host host = _resourceMgr.addHost(zoneId, resource, + Host.Type.L2Networking, params); if (host != null) { txn.start(); - niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName); + niciraNvpDevice = new NiciraNvpDeviceVO(host.getId(), + physicalNetworkId, ntwkSvcProvider.getProviderName(), + deviceName); _niciraNvpDao.persist(niciraNvpDevice); - DetailVO detail = new DetailVO(host.getId(), "niciranvpdeviceid", String.valueOf(niciraNvpDevice.getId())); + DetailVO detail = new DetailVO(host.getId(), + "niciranvpdeviceid", String.valueOf(niciraNvpDevice + .getId())); _hostDetailsDao.persist(detail); txn.commit(); return niciraNvpDevice; } else { - throw new CloudRuntimeException("Failed to add Nicira Nvp Device due to internal error."); + throw new CloudRuntimeException( + "Failed to add Nicira Nvp Device due to internal error."); } } catch (ConfigurationException e) { txn.rollback(); @@ -411,35 +638,51 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide @Override public NiciraNvpDeviceResponse createNiciraNvpDeviceResponse( NiciraNvpDeviceVO niciraNvpDeviceVO) { + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDeviceVO.getHostId()); + _hostDao.loadDetails(niciraNvpHost); + NiciraNvpDeviceResponse response = new NiciraNvpDeviceResponse(); response.setDeviceName(niciraNvpDeviceVO.getDeviceName()); - response.setPhysicalNetworkId(niciraNvpDeviceVO.getPhysicalNetworkId()); - response.setId(niciraNvpDeviceVO.getId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(niciraNvpDeviceVO.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + response.setId(niciraNvpDeviceVO.getUuid()); response.setProviderName(niciraNvpDeviceVO.getProviderName()); + response.setHostName(niciraNvpHost.getDetail("ip")); + response.setTransportZoneUuid(niciraNvpHost.getDetail("transportzoneuuid")); + response.setL3GatewayServiceUuid(niciraNvpHost.getDetail("l3gatewayserviceuuid")); + response.setObjectName("niciranvpdevice"); return response; } @Override public boolean deleteNiciraNvpDevice(DeleteNiciraNvpDeviceCmd cmd) { Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId); + throw new InvalidParameterValueException( + "Could not find a nicira device with id " + niciraDeviceId); } // Find the physical network we work for Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork != null) { // Lets see if there are networks that use us // Find the nicira networks on this physical network - List networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId); + List networkList = _networkDao + .listByPhysicalNetwork(physicalNetworkId); // Networks with broadcast type lswitch are ours for (NetworkVO network : networkList) { if (network.getBroadcastDomainType() == Networks.BroadcastDomainType.Lswitch) { - if ((network.getState() != Network.State.Shutdown) && (network.getState() != Network.State.Destroy)) { - throw new CloudRuntimeException("This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); + if ((network.getState() != Network.State.Shutdown) + && (network.getState() != Network.State.Destroy)) { + throw new CloudRuntimeException( + "This Nicira Nvp device can not be deleted as there are one or more logical networks provisioned by cloudstack."); } } } @@ -453,56 +696,68 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide _resourceMgr.deleteHost(hostId, false, false); _niciraNvpDao.remove(niciraDeviceId); - return true; } @Override - public List listNiciraNvpDevices(ListNiciraNvpDevicesCmd cmd) { + public List listNiciraNvpDevices( + ListNiciraNvpDevicesCmd cmd) { Long physicalNetworkId = cmd.getPhysicalNetworkId(); Long niciraNvpDeviceId = cmd.getNiciraNvpDeviceId(); List responseList = new ArrayList(); if (physicalNetworkId == null && niciraNvpDeviceId == null) { - throw new InvalidParameterValueException("Either physical network Id or nicira device Id must be specified"); + throw new InvalidParameterValueException( + "Either physical network Id or nicira device Id must be specified"); } if (niciraNvpDeviceId != null) { - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraNvpDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraNvpDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find Nicira Nvp device with id: " + niciraNvpDevice); + throw new InvalidParameterValueException( + "Could not find Nicira Nvp device with id: " + + niciraNvpDevice); } responseList.add(niciraNvpDevice); - } - else { - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); + } else { + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { - throw new InvalidParameterValueException("Could not find a physical network with id: " + physicalNetworkId); + throw new InvalidParameterValueException( + "Could not find a physical network with id: " + + physicalNetworkId); } - responseList = _niciraNvpDao.listByPhysicalNetwork(physicalNetworkId); + responseList = _niciraNvpDao + .listByPhysicalNetwork(physicalNetworkId); } return responseList; } @Override - public List listNiciraNvpDeviceNetworks(ListNiciraNvpDeviceNetworksCmd cmd) { + public List listNiciraNvpDeviceNetworks( + ListNiciraNvpDeviceNetworksCmd cmd) { Long niciraDeviceId = cmd.getNiciraNvpDeviceId(); - NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao.findById(niciraDeviceId); + NiciraNvpDeviceVO niciraNvpDevice = _niciraNvpDao + .findById(niciraDeviceId); if (niciraNvpDevice == null) { - throw new InvalidParameterValueException("Could not find a nicira device with id " + niciraDeviceId); + throw new InvalidParameterValueException( + "Could not find a nicira device with id " + niciraDeviceId); } // Find the physical network we work for Long physicalNetworkId = niciraNvpDevice.getPhysicalNetworkId(); - PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId); + PhysicalNetworkVO physicalNetwork = _physicalNetworkDao + .findById(physicalNetworkId); if (physicalNetwork == null) { // No such physical network, so no provisioned networks return Collections.emptyList(); } // Find the nicira networks on this physical network - List networkList = _networkDao.listByPhysicalNetwork(physicalNetworkId); + List networkList = _networkDao + .listByPhysicalNetwork(physicalNetworkId); // Networks with broadcast type lswitch are ours List responseList = new ArrayList(); @@ -542,4 +797,156 @@ public class NiciraNvpElement extends AdapterBase implements ConnectivityProvide return new DeleteHostAnswer(true); } + /** + * From interface SourceNatServiceProvider + */ + @Override + public IpDeployer getIpDeployer(Network network) { + return this; + } + + /** + * From interface IpDeployer + * + * @param network + * @param ipAddress + * @param services + * @return + * @throws ResourceUnavailableException + */ + @Override + public boolean applyIps(Network network, + List ipAddress, Set services) + throws ResourceUnavailableException { + if (services.contains(Service.SourceNat)) { + // Only if we need to provide SourceNat we need to configure the logical router + // SourceNat is required for StaticNat and PortForwarding + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + _hostDao.loadDetails(niciraNvpHost); + + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } + + List cidrs = new ArrayList(); + for (PublicIpAddress ip : ipAddress) { + cidrs.add(ip.getAddress().addr() + "/" + NetUtils.getCidrSize(ip.getNetmask())); + } + ConfigurePublicIpsOnLogicalRouterCommand cmd = new ConfigurePublicIpsOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), + niciraNvpHost.getDetail("l3gatewayserviceuuid"), cidrs); + ConfigurePublicIpsOnLogicalRouterAnswer answer = (ConfigurePublicIpsOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + //FIXME answer can be null if the host is down + return answer.getResult(); + } + else { + s_logger.debug("No need to provision ip addresses as we are not providing L3 services."); + } + + return true; + } + + /** + * From interface StaticNatServiceProvider + */ + @Override + public boolean applyStaticNats(Network network, + List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.StaticNat)) { + return false; + } + + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } + + List staticNatRules = new ArrayList(); + for (StaticNat rule : rules) { + IpAddress sourceIp = _networkManager.getIp(rule.getSourceIpAddressId()); + // Force the nat rule into the StaticNatRuleTO, no use making a new TO object + // we only need the source and destination ip. Unfortunately no mention if a rule + // is new. + StaticNatRuleTO ruleTO = new StaticNatRuleTO(1, + sourceIp.getAddress().addr(), 0, 65535, + rule.getDestIpAddress(), 0, 65535, + "any", rule.isForRevoke(), false); + staticNatRules.add(ruleTO); + } + + ConfigureStaticNatRulesOnLogicalRouterCommand cmd = + new ConfigureStaticNatRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), staticNatRules); + ConfigureStaticNatRulesOnLogicalRouterAnswer answer = (ConfigureStaticNatRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + + return answer.getResult(); + } + + /** + * From interface PortForwardingServiceProvider + */ + @Override + public boolean applyPFRules(Network network, List rules) + throws ResourceUnavailableException { + if (!canHandle(network, Service.PortForwarding)) { + return false; + } + + List devices = _niciraNvpDao + .listByPhysicalNetwork(network.getPhysicalNetworkId()); + if (devices.isEmpty()) { + s_logger.error("No NiciraNvp Controller on physical network " + + network.getPhysicalNetworkId()); + return false; + } + NiciraNvpDeviceVO niciraNvpDevice = devices.get(0); + HostVO niciraNvpHost = _hostDao.findById(niciraNvpDevice.getHostId()); + + NiciraNvpRouterMappingVO routermapping = _niciraNvpRouterMappingDao + .findByNetworkId(network.getId()); + if (routermapping == null) { + s_logger.error("No logical router uuid found for network " + + network.getDisplayText()); + return false; + } + + List portForwardingRules = new ArrayList(); + for (PortForwardingRule rule : rules) { + IpAddress sourceIp = _networkManager.getIp(rule.getSourceIpAddressId()); + Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); + PortForwardingRuleTO ruleTO = new PortForwardingRuleTO((PortForwardingRule) rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); + portForwardingRules.add(ruleTO); + } + + ConfigurePortForwardingRulesOnLogicalRouterCommand cmd = + new ConfigurePortForwardingRulesOnLogicalRouterCommand(routermapping.getLogicalRouterUuid(), portForwardingRules); + ConfigurePortForwardingRulesOnLogicalRouterAnswer answer = (ConfigurePortForwardingRulesOnLogicalRouterAnswer) _agentMgr.easySend(niciraNvpHost.getId(), cmd); + + return answer.getResult(); + } + } 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 7cc42e9771d..4c1bee17c17 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 @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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; @@ -47,6 +30,7 @@ import com.cloud.agent.api.CreateLogicalSwitchAnswer; import com.cloud.agent.api.CreateLogicalSwitchCommand; import com.cloud.agent.api.DeleteLogicalSwitchAnswer; import com.cloud.agent.api.DeleteLogicalSwitchCommand; +import com.cloud.dc.DataCenter; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.dao.DataCenterDao; import com.cloud.deploy.DeployDestination; @@ -57,6 +41,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; @@ -68,9 +53,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; @@ -105,6 +92,8 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { AgentManager _agentMgr; @Inject HostDetailsDao _hostDetailsDao; + @Inject + NetworkOfferingServiceMapDao _ntwkOfferingSrvcDao; public NiciraNvpGuestNetworkGuru() { super(); @@ -117,7 +106,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); @@ -130,8 +120,9 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { Network userSpecified, Account owner) { // Check of the isolation type of the related physical network is STT PhysicalNetworkVO physnet = _physicalNetworkDao.findById(plan.getPhysicalNetworkId()); - if (physnet == null || physnet.getIsolationMethods() == null || !physnet.getIsolationMethods().contains("STT")) { - s_logger.debug("Refusing to design this network, the physical isolation type is not STT"); + DataCenter dc = _dcDao.findById(plan.getDataCenterId()); + if (!canHandle(offering,dc.getNetworkType(),physnet)) { + s_logger.debug("Refusing to design this network"); return null; } @@ -210,6 +201,7 @@ public class NiciraNvpGuestNetworkGuru extends GuestNetworkGuru { s_logger.info("Implemented OK, network linked to = " + implemented.getBroadcastUri().toString()); } catch (URISyntaxException e) { s_logger.error("Unable to store logical switch id in broadcast uri, uuid = " + implemented.getUuid(), e); + return null; } return implemented; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java index 2699b6db020..b1b1ebc3545 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Attachment.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 abstract class Attachment { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java new file mode 100644 index 00000000000..8b807fd9e72 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/L3GatewayAttachment.java @@ -0,0 +1,52 @@ +// 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 L3GatewayAttachment extends Attachment { + private String l3_gateway_service_uuid; + private String type = "L3GatewayAttachment"; + private Long vlan_id; + + public L3GatewayAttachment(String l3_gateway_service_uuid) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + } + + public L3GatewayAttachment(String l3_gateway_service_uuid, long vlan_id) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + this.vlan_id = vlan_id; + } + + public String getL3GatewayServiceUuid() { + return l3_gateway_service_uuid; + } + + public void setL3GatewayServiceUuid(String l3_gateway_service_uuid) { + this.l3_gateway_service_uuid = l3_gateway_service_uuid; + } + + public long getVlanId() { + return vlan_id; + } + + public void setVlanId(long vlan_id) { + this.vlan_id = vlan_id; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java new file mode 100644 index 00000000000..897ee06b844 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterConfig.java @@ -0,0 +1,64 @@ +// 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 java.util.List; + +/** + * + */ +public class LogicalRouterConfig { + private String display_name; + private RoutingConfig routing_config; + private String type = "LogicalRouterConfig"; + private String uuid; + private List tags; + + public RoutingConfig getRoutingConfig() { + return routing_config; + } + + public void setRoutingConfig(RoutingConfig routing_config) { + this.routing_config = routing_config; + } + + public String getDisplayName() { + return display_name; + } + + public void setDisplayName(String display_name) { + this.display_name = display_name; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java new file mode 100644 index 00000000000..196106dbe40 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalRouterPort.java @@ -0,0 +1,90 @@ +// 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 java.util.List; + +/** + * + */ +public class LogicalRouterPort { + private String display_name; + private List tags; + private Integer portno; + private boolean admin_status_enabled; + private List ip_addresses; + private String mac_address; + private String type = "LogicalRouterPortConfig"; + private String uuid; + + public int getPortno() { + return portno; + } + + public void setPortno(int portno) { + this.portno = portno; + } + + public boolean isAdminStatusEnabled() { + return admin_status_enabled; + } + + public void setAdminStatusEnabled(boolean admin_status_enabled) { + this.admin_status_enabled = admin_status_enabled; + } + + public List getIpAddresses() { + return ip_addresses; + } + + public void setIpAddresses(List ip_addresses) { + this.ip_addresses = ip_addresses; + } + + public String getMacAddress() { + return mac_address; + } + + public void setMacAddress(String mac_address) { + this.mac_address = mac_address; + } + + public String getDisplayName() { + return display_name; + } + + public void setDisplayName(String display_name) { + this.display_name = display_name; + } + + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + +} \ No newline at end of file diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java index 14d7753ab6c..f56518924b8 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitch.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 java.util.List; diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java index f8cb5d62212..c5714585c99 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/LogicalSwitchPort.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 java.util.List; 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 new file mode 100644 index 00000000000..0c4e677536c --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/Match.java @@ -0,0 +1,253 @@ +// 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 Match { + private Integer protocol; + private String source_ip_addresses; + private Boolean source_ip_addresses_not; + private String destination_ip_addresses; + private Boolean destination_ip_addresses_not; + private Integer source_port_min; + private Integer source_port_max; + private Boolean source_port_not; + private Integer destination_port_min; + private Integer destination_port_max; + private Boolean destination_port_not; + private String ethertype = "IPv4"; + + public Integer getProtocol() { + return protocol; + } + + public void setProtocol(Integer protocol) { + this.protocol = protocol; + } + + public Integer getSourcePortMin() { + return source_port_min; + } + + public void setSourcePortMin(Integer source_port_min) { + this.source_port_min = source_port_min; + } + + public Integer getSourcePortMax() { + return source_port_max; + } + + public void setSourcePortMax(Integer source_port_max) { + this.source_port_max = source_port_max; + } + + public Boolean isSourcePortNot() { + return source_port_not; + } + + public void setSourcePortNot(Boolean source_port_not) { + this.source_port_not = source_port_not; + } + + public Integer getDestinationPortMin() { + return destination_port_min; + } + + public void setDestinationPortMin(Integer destination_port_min) { + this.destination_port_min = destination_port_min; + } + + public Integer getDestinationPortMax() { + return destination_port_max; + } + + public void setDestinationPortMax(Integer destination_port_max) { + this.destination_port_max = destination_port_max; + } + + public Boolean isDestinationPortNot() { + return destination_port_not; + } + + public void setDestinationPortNot(Boolean destination_port_not) { + this.destination_port_not = destination_port_not; + } + + public String getEthertype() { + return ethertype; + } + + public void setEthertype(String ethertype) { + this.ethertype = ethertype; + } + + public String getSourceIpAddresses() { + return source_ip_addresses; + } + + public void setSourceIpAddresses(String source_ip_addresses) { + this.source_ip_addresses = source_ip_addresses; + } + + public boolean isSourceIpAddressesNot() { + return source_ip_addresses_not; + } + + public void setSourceIpAddresses_not(boolean source_ip_addresses_not) { + this.source_ip_addresses_not = source_ip_addresses_not; + } + + public String getDestinationIpAddresses() { + return destination_ip_addresses; + } + + public void setDestinationIpAddresses(String destination_ip_addresses) { + this.destination_ip_addresses = destination_ip_addresses; + } + + public Boolean isDestinationIpAddressesNot() { + return destination_ip_addresses_not; + } + + 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 new file mode 100644 index 00000000000..b66ffa89b77 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NatRule.java @@ -0,0 +1,282 @@ +// 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 NatRule { + protected Match match; + protected String to_source_ip_address_min; + protected String to_source_ip_address_max; + protected Integer to_source_port_min; + protected Integer to_source_port_max; + protected String uuid; + protected String type; + protected String to_destination_ip_address_min; + protected String to_destination_ip_address_max; + protected Integer to_destination_port; + + public NatRule() {} + + public Match getMatch() { + return match; + } + + public void setMatch(Match match) { + this.match = match; + } + + public String getToSourceIpAddressMin() { + return to_source_ip_address_min; + } + + public void setToSourceIpAddressMin(String to_source_ip_address_min) { + this.to_source_ip_address_min = to_source_ip_address_min; + } + + public String getToSourceIpAddressMax() { + return to_source_ip_address_max; + } + + public void setToSourceIpAddressMax(String to_source_ip_address_max) { + this.to_source_ip_address_max = to_source_ip_address_max; + } + + public Integer getToSourcePortMin() { + return to_source_port_min; + } + + public void setToSourcePortMin(Integer to_source_port_min) { + this.to_source_port_min = to_source_port_min; + } + + public Integer getToSourcePortMax() { + return to_source_port_max; + } + + public void setToSourcePortMax(Integer to_source_port_max) { + this.to_source_port_max = to_source_port_max; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getToDestinationIpAddressMin() { + return to_destination_ip_address_min; + } + + public void setToDestinationIpAddressMin( + String to_destination_ip_address_min) { + this.to_destination_ip_address_min = to_destination_ip_address_min; + } + + public String getToDestinationIpAddressMax() { + return to_destination_ip_address_max; + } + + public void setToDestinationIpAddressMax( + String to_destination_ip_address_max) { + this.to_destination_ip_address_max = to_destination_ip_address_max; + } + + public Integer getToDestinationPort() { + return to_destination_port; + } + + public void setToDestinationPort(Integer to_destination_port) { + this.to_destination_port = to_destination_port; + } + + 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 2c002abdbff..039c174be2d 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 @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 java.io.IOException; @@ -58,9 +41,12 @@ 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; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.DeleteMethod; @@ -78,6 +64,8 @@ import com.google.gson.reflect.TypeToken; public class NiciraNvpApi { private static final Logger s_logger = Logger.getLogger(NiciraNvpApi.class); + private final static String _protocol = "https"; + private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); private String _name; private String _host; @@ -85,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, 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); } + + 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( ); + public NiciraNvpApi() { + _client = createHttpClient(); _client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); try { @@ -107,17 +120,32 @@ 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("https", _host, "/ws.v1/login").toString(); + 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); @@ -133,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) { @@ -180,7 +210,7 @@ public class NiciraNvpApi { NiciraNvpList lspl = executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); - if (lspl == null || lspl.getResult_count() != 1) { + if (lspl == null || lspl.getResultCount() != 1) { throw new NiciraNvpApiException("Unexpected response from API"); } @@ -210,19 +240,111 @@ public class NiciraNvpApi { return lspl; } + public LogicalRouterConfig createLogicalRouter(LogicalRouterConfig logicalRouterConfig) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter"; + + LogicalRouterConfig lrc = executeCreateObject(logicalRouterConfig, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + + return lrc; + } + + public void deleteLogicalRouter(String logicalRouterUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid; + + executeDeleteObject(uri); + } - private void executeUpdateObject(T newObject, String uri, Map parameters) throws NiciraNvpApiException { - String url; - try { - url = new URL("https", _host, uri).toString(); - } catch (MalformedURLException e) { - s_logger.error("Unable to build Nicira API URL", e); - throw new NiciraNvpApiException("Connection to NVP Failed"); + public LogicalRouterPort createLogicalRouterPort(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + + LogicalRouterPort lrp = executeCreateObject(logicalRouterPort, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + return lrp; + } + + public void deleteLogicalRouterPort(String logicalRouterUuid, String logicalRouterPortUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid; + + executeDeleteObject(uri); + } + + public void modifyLogicalRouterPort(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPort.getUuid(); + + executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); + } + + public void modifyLogicalRouterPortAttachment(String logicalRouterUuid, String logicalRouterPortUuid, Attachment attachment) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport/" + logicalRouterPortUuid + "/attachment"; + executeUpdateObject(attachment, uri, Collections.emptyMap()); + } + + public NatRule createLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; + + return executeCreateObject(natRule, new TypeToken(){}.getType(), uri, Collections.emptyMap()); + } + + public void modifyLogicalRouterNatRule(String logicalRouterUuid, NatRule natRule) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRule.getUuid(); + + executeUpdateObject(natRule, uri, Collections.emptyMap()); + } + + public void deleteLogicalRouterNatRule(String logicalRouterUuid, String natRuleUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat/" + natRuleUuid; + + executeDeleteObject(uri); + } + + public NiciraNvpList findLogicalRouterPortByGatewayServiceAndVlanId(String logicalRouterUuid, String gatewayServiceUuid, long vlanId) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + Map params = new HashMap(); + params.put("attachment_gwsvc_uuid", gatewayServiceUuid); + params.put("attachment_vlan", "0"); + params.put("fields","*"); + + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); + } + + public LogicalRouterConfig findOneLogicalRouterByUuid(String logicalRouterUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid; + + return executeRetrieveObject(new TypeToken(){}.getType(), uri, Collections.emptyMap()); + } + + public void updateLogicalRouterPortConfig(String logicalRouterUuid, LogicalRouterPort logicalRouterPort) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport" + logicalRouterPort.getUuid(); + + executeUpdateObject(logicalRouterPort, uri, Collections.emptyMap()); + } + + public NiciraNvpList findNatRulesByLogicalRouterUuid(String logicalRouterUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/nat"; + Map params = new HashMap(); + params.put("fields","*"); + + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); + } + + public NiciraNvpList findLogicalRouterPortByGatewayServiceUuid(String logicalRouterUuid, String l3GatewayServiceUuid) throws NiciraNvpApiException { + String uri = "/ws.v1/lrouter/" + logicalRouterUuid + "/lport"; + Map params = new HashMap(); + params.put("fields", "*"); + params.put("attachment_gwsvc_uuid", l3GatewayServiceUuid); + + return executeRetrieveObject(new TypeToken>(){}.getType(), uri, params); + } + + 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( @@ -235,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("https", _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( @@ -265,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); } @@ -274,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("https", _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("https", _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()); @@ -323,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); } @@ -334,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/NiciraNvpList.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java index 13d352daba3..c97e40ecd81 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpList.java @@ -30,12 +30,16 @@ public class NiciraNvpList { this.results = results; } - public int getResult_count() { + public int getResultCount() { return result_count; } - public void setResult_count(int result_count) { + public void setResultCount(int result_count) { this.result_count = result_count; - } + } + + public boolean isEmpty() { + return result_count == 0; + } } diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java index 81b752cc643..f8282b86d9c 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/NiciraNvpTag.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 NiciraNvpTag { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java new file mode 100644 index 00000000000..e57c2493f1c --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/PatchAttachment.java @@ -0,0 +1,39 @@ +// 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 PatchAttachment extends Attachment { + private final String type = "PatchAttachment"; + private String peer_port_uuid; + + public PatchAttachment(String peerPortUuid) { + this.peer_port_uuid = peerPortUuid; + } + + public String getPeerPortUuid() { + return peer_port_uuid; + } + + public void setPeerPortUuid(String peerPortUuid) { + this.peer_port_uuid = peerPortUuid; + } + + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java new file mode 100644 index 00000000000..c018af37467 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RouterNextHop.java @@ -0,0 +1,38 @@ +// 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 RouterNextHop { + private String gateway_ip_address; + private String type = "RouterNextHop"; + + public RouterNextHop(String gatewayIpAddress) { + this.gateway_ip_address = gatewayIpAddress; + } + + public String getGatewayIpAddress() { + return gateway_ip_address; + } + + public void setGatewayIpAddress(String gateway_ip_address) { + this.gateway_ip_address = gateway_ip_address; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java new file mode 100644 index 00000000000..c5eca5b9bc4 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/RoutingConfig.java @@ -0,0 +1,21 @@ +// 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 RoutingConfig { + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java new file mode 100644 index 00000000000..b4eda447b13 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/SingleDefaultRouteImplictRoutingConfig.java @@ -0,0 +1,38 @@ +// 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 SingleDefaultRouteImplictRoutingConfig extends RoutingConfig { + public RouterNextHop default_route_next_hop; + public String type = "SingleDefaultRouteImplicitRoutingConfig"; + + public SingleDefaultRouteImplictRoutingConfig(RouterNextHop routerNextHop) { + default_route_next_hop = routerNextHop; + } + + public RouterNextHop getDefaultRouteNextHop() { + return default_route_next_hop; + } + + public void setDefaultRouteNextHop(RouterNextHop default_route_next_hop) { + this.default_route_next_hop = default_route_next_hop; + } + +} diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java index f2e4b03a092..e55d759bdad 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/TransportZoneBinding.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 TransportZoneBinding { diff --git a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java index b4dd0e71ba8..dc87a5a58ea 100644 --- a/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java +++ b/plugins/network-elements/nicira-nvp/src/com/cloud/network/nicira/VifAttachment.java @@ -14,23 +14,6 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. -/** 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 VifAttachment extends Attachment { 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 31cac6f000c..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 @@ -27,10 +27,20 @@ import org.apache.log4j.Logger; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.Command; +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; @@ -46,15 +56,25 @@ import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupNiciraNvpCommand; 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.host.Host.Type; import com.cloud.network.nicira.ControlClusterStatus; +import com.cloud.network.nicira.L3GatewayAttachment; +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.Match; +import com.cloud.network.nicira.NatRule; import com.cloud.network.nicira.NiciraNvpApi; import com.cloud.network.nicira.NiciraNvpApiException; import com.cloud.network.nicira.NiciraNvpList; 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.TransportZoneBinding; import com.cloud.network.nicira.VifAttachment; import com.cloud.resource.ServerResource; @@ -63,39 +83,25 @@ 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"); @@ -108,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; } @@ -197,6 +216,21 @@ public class NiciraNvpResource implements ServerResource { else if (cmd instanceof FindLogicalSwitchPortCommand) { return executeRequest((FindLogicalSwitchPortCommand) cmd, numRetries); } + else if (cmd instanceof CreateLogicalRouterCommand) { + return executeRequest((CreateLogicalRouterCommand) cmd, numRetries); + } + else if (cmd instanceof DeleteLogicalRouterCommand) { + return executeRequest((DeleteLogicalRouterCommand) cmd, numRetries); + } + else if (cmd instanceof ConfigureStaticNatRulesOnLogicalRouterCommand) { + return executeRequest((ConfigureStaticNatRulesOnLogicalRouterCommand) cmd, numRetries); + } + else if (cmd instanceof ConfigurePortForwardingRulesOnLogicalRouterCommand) { + return executeRequest((ConfigurePortForwardingRulesOnLogicalRouterCommand) cmd, numRetries); + } + else if (cmd instanceof ConfigurePublicIpsOnLogicalRouterCommand) { + return executeRequest((ConfigurePublicIpsOnLogicalRouterCommand) cmd, numRetries); + } s_logger.debug("Received unsupported command " + cmd.toString()); return Answer.createUnsupportedCommandAnswer(cmd); } @@ -216,7 +250,7 @@ public class NiciraNvpResource implements ServerResource { private Answer executeRequest(CreateLogicalSwitchCommand cmd, int numRetries) { LogicalSwitch logicalSwitch = new LogicalSwitch(); - logicalSwitch.setDisplay_name("lswitch-" + cmd.getName()); + logicalSwitch.setDisplay_name(truncate("lswitch-" + cmd.getName(), 40)); logicalSwitch.setPort_isolation_enabled(false); // Set transport binding @@ -268,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) { @@ -324,7 +364,7 @@ public class NiciraNvpResource implements ServerResource { try { NiciraNvpList ports = _niciraNvpApi.findLogicalSwitchPortsByUuid(logicalSwitchUuid, logicalSwitchPortUuid); - if (ports.getResult_count() == 0) { + if (ports.getResultCount() == 0) { return new FindLogicalSwitchPortAnswer(cmd, false, "Logical switchport " + logicalSwitchPortUuid + " not found", null); } else { @@ -340,6 +380,299 @@ public class NiciraNvpResource implements ServerResource { } } + private Answer executeRequest(CreateLogicalRouterCommand cmd, int numRetries) { + String routerName = cmd.getName(); + String gatewayServiceUuid = cmd.getGatewayServiceUuid(); + String logicalSwitchUuid = cmd.getLogicalSwitchUuid(); + + List tags = new ArrayList(); + tags.add(new NiciraNvpTag("cs_account",cmd.getOwnerName())); + + String publicNetworkNextHopIp = cmd.getPublicNextHop(); + String publicNetworkIpAddress = cmd.getPublicIpCidr(); + String internalNetworkAddress = cmd.getInternalIpCidr(); + + s_logger.debug("Creating a logical router with external ip " + + publicNetworkIpAddress + " and internal ip " + internalNetworkAddress + + "on gateway service " + gatewayServiceUuid); + + try { + // Create the Router + LogicalRouterConfig lrc = new LogicalRouterConfig(); + lrc.setDisplayName(truncate(routerName, 40)); + lrc.setTags(tags); + lrc.setRoutingConfig(new SingleDefaultRouteImplictRoutingConfig( + 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(); + lrpo.setAdminStatusEnabled(true); + lrpo.setDisplayName(truncate(routerName + "-outside-port", 40)); + lrpo.setTags(tags); + List outsideIpAddresses = new ArrayList(); + outsideIpAddresses.add(publicNetworkIpAddress); + lrpo.setIpAddresses(outsideIpAddresses); + lrpo = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpo); + + // Attach the outside port to the gateway service on the correct VLAN + L3GatewayAttachment attachment = new L3GatewayAttachment(gatewayServiceUuid); + if (cmd.getVlanId() != 0) { + attachment.setVlanId(cmd.getVlanId()); + } + _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpo.getUuid(), attachment); + + // Create the inside port for the router + LogicalRouterPort lrpi = new LogicalRouterPort(); + lrpi.setAdminStatusEnabled(true); + lrpi.setDisplayName(truncate(routerName + "-inside-port", 40)); + lrpi.setTags(tags); + List insideIpAddresses = new ArrayList(); + insideIpAddresses.add(internalNetworkAddress); + lrpi.setIpAddresses(insideIpAddresses); + lrpi = _niciraNvpApi.createLogicalRouterPort(lrc.getUuid(),lrpi); + + // Create the inside port on the lswitch + 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 + _niciraNvpApi.modifyLogicalRouterPortAttachment(lrc.getUuid(), lrpi.getUuid(), + new PatchAttachment(lsp.getUuid())); + + // Attach the inside lswitch port to the router with a PatchAttachment + _niciraNvpApi.modifyLogicalSwitchPortAttachment(logicalSwitchUuid, lsp.getUuid(), + new PatchAttachment(lrpi.getUuid())); + + // Setup the source nat rule + NatRule snr = new NatRule(); + snr.setType("SourceNatRule"); + snr.setToSourceIpAddressMin(publicNetworkIpAddress.split("/")[0]); + snr.setToSourceIpAddressMax(publicNetworkIpAddress.split("/")[0]); + Match match = new Match(); + match.setSourceIpAddresses(internalNetworkAddress); + snr.setMatch(match); + _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 and rules + try { + _niciraNvpApi.deleteLogicalRouter(lrc.getUuid()); + if (lsp != null) { + _niciraNvpApi.deleteLogicalSwitchPort(logicalSwitchUuid, lsp.getUuid()); + } + } catch (NiciraNvpApiException ex) {} + + throw e; + } + + return new CreateLogicalRouterAnswer(cmd, true, "Logical Router created (uuid " + lrc.getUuid() + ")", lrc.getUuid()); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new CreateLogicalRouterAnswer(cmd, e); + } + } + } + + private Answer executeRequest(DeleteLogicalRouterCommand cmd, int numRetries) { + try { + _niciraNvpApi.deleteLogicalRouter(cmd.getLogicalRouterUuid()); + return new DeleteLogicalRouterAnswer(cmd, true, "Logical Router deleted (uuid " + cmd.getLogicalRouterUuid() + ")"); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new DeleteLogicalRouterAnswer(cmd, e); + } + } + } + + private Answer executeRequest(ConfigurePublicIpsOnLogicalRouterCommand cmd, int numRetries) { + try { + NiciraNvpList ports = _niciraNvpApi.findLogicalRouterPortByGatewayServiceUuid(cmd.getLogicalRouterUuid(), cmd.getL3GatewayServiceUuid()); + if (ports.getResultCount() != 1) { + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, false, "No logical router ports found, unable to set ip addresses"); + } + LogicalRouterPort lrp = ports.getResults().get(0); + lrp.setIpAddresses(cmd.getPublicCidrs()); + _niciraNvpApi.modifyLogicalRouterPort(cmd.getLogicalRouterUuid(), lrp); + + 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); + } + else { + return new ConfigurePublicIpsOnLogicalRouterAnswer(cmd, e); + } + } + + } + + private Answer executeRequest(ConfigureStaticNatRulesOnLogicalRouterCommand cmd, int numRetries) { + try { + NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); + // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) + // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule + // Any other SourceNat rule should have a corresponding DestinationNat rule + + for (StaticNatRuleTO rule : cmd.getRules()) { + + NatRule[] rulepair = generateStaticNatRulePair(rule.getDstIp(), rule.getSrcIp()); + + NatRule incoming = null; + NatRule outgoing = null; + + for (NatRule storedRule : existingRules.getResults()) { + 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 (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 { + if (rule.revoked()) { + s_logger.warn("Tried deleting a rule that does not exist, " + + rule.getSrcIp() + " -> " + rule.getDstIp()); + break; + } + + 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 + } + + } + } + return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" StaticNat rules applied"); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new ConfigureStaticNatRulesOnLogicalRouterAnswer(cmd, e); + } + } + } + + private Answer executeRequest(ConfigurePortForwardingRulesOnLogicalRouterCommand cmd, int numRetries) { + try { + NiciraNvpList existingRules = _niciraNvpApi.findNatRulesByLogicalRouterUuid(cmd.getLogicalRouterUuid()); + // Rules of the game (also known as assumptions-that-will-make-stuff-break-later-on) + // A SourceNat rule with a match other than a /32 cidr is assumed to be the "main" SourceNat rule + // Any other SourceNat rule should have a corresponding DestinationNat rule + + for (PortForwardingRuleTO rule : cmd.getRules()) { + if (rule.isAlreadyAdded() && !rule.revoked()) { + // Don't need to do anything + continue; + } + + 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 (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 (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 { + if (rule.revoked()) { + s_logger.warn("Tried deleting a rule that does not exist, " + + rule.getSrcIp() + " -> " + rule.getDstIp()); + break; + } + + 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.warn("NiciraNvpApiException during create call, rolling back previous create"); + _niciraNvpApi.deleteLogicalRouterNatRule(cmd.getLogicalRouterUuid(), rulepair[0].getUuid()); + throw ex; // Rethrow the original exception + } + + } + } + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, true, cmd.getRules().size() +" PortForwarding rules applied"); + } catch (NiciraNvpApiException e) { + if (numRetries > 0) { + return retry(cmd, --numRetries); + } + else { + return new ConfigurePortForwardingRulesOnLogicalRouterAnswer(cmd, e); + } + } + + } + private Answer executeRequest(ReadyCommand cmd) { return new ReadyAnswer(cmd); } @@ -349,9 +682,117 @@ 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) { + + StringBuilder natRuleStr = new StringBuilder(); + natRuleStr.append("Rule "); + natRuleStr.append(rule.getUuid()); + natRuleStr.append(" ("); + natRuleStr.append(rule.getType()); + natRuleStr.append(") :"); + Match m = rule.getMatch(); + natRuleStr.append("match ("); + natRuleStr.append(m.getProtocol()); + natRuleStr.append(" "); + natRuleStr.append(m.getSourceIpAddresses()); + natRuleStr.append(" ["); + natRuleStr.append(m.getSourcePortMin()); + natRuleStr.append("-"); + natRuleStr.append(m.getSourcePortMax()); + natRuleStr.append(" ] -> "); + natRuleStr.append(m.getDestinationIpAddresses()); + natRuleStr.append(" ["); + natRuleStr.append(m.getDestinationPortMin()); + natRuleStr.append("-"); + natRuleStr.append(m.getDestinationPortMax()); + natRuleStr.append(" ]) -->"); + if ("SourceNatRule".equals(rule.getType())) { + natRuleStr.append(rule.getToSourceIpAddressMin()); + natRuleStr.append("-"); + natRuleStr.append(rule.getToSourceIpAddressMax()); + natRuleStr.append(" ["); + natRuleStr.append(rule.getToSourcePortMin()); + natRuleStr.append("-"); + natRuleStr.append(rule.getToSourcePortMax()); + natRuleStr.append(" ])"); + } + else { + natRuleStr.append(rule.getToDestinationIpAddressMin()); + natRuleStr.append("-"); + natRuleStr.append(rule.getToDestinationIpAddressMax()); + natRuleStr.append(" ["); + natRuleStr.append(rule.getToDestinationPort()); + natRuleStr.append(" ])"); + } + return natRuleStr.toString(); + } + + private String truncate(String string, int length) { + if (string.length() <= length) { + return string; + } + else { + return string.substring(0, length); + } + } + + 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/element/NiciraNvpElementTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java new file mode 100644 index 00000000000..acfd3bcdb9e --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/element/NiciraNvpElementTest.java @@ -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. +package com.cloud.network.element; + +import java.util.Collections; + +import javax.naming.ConfigurationException; + +import org.junit.Before; +import org.junit.Test; + +import com.cloud.deploy.DeployDestination; +import com.cloud.domain.Domain; +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.GuestType; +import com.cloud.network.Network.Provider; +import com.cloud.network.Network.Service; +import com.cloud.network.NetworkManager; +import com.cloud.network.Networks.BroadcastDomainType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.offering.NetworkOffering; +import com.cloud.resource.ResourceManager; +import com.cloud.user.Account; +import com.cloud.vm.ReservationContext; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class NiciraNvpElementTest { + + NiciraNvpElement _element = new NiciraNvpElement(); + NetworkManager _networkManager = mock(NetworkManager.class); + NetworkServiceMapDao _ntwkSrvcDao = mock (NetworkServiceMapDao.class); + + @Before + public void setUp() throws ConfigurationException { + _element._resourceMgr = mock(ResourceManager.class); + _element._networkManager = _networkManager; + _element._ntwkSrvcDao = _ntwkSrvcDao; + + // Standard responses + when(_networkManager.isProviderForNetwork(Provider.NiciraNvp, 42L)).thenReturn(true); + + _element.configure("NiciraNvpTestElement", Collections. emptyMap()); + } + + @Test + public void canHandleTest() { + Network net = mock(Network.class); + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(net.getId()).thenReturn(42L); + + when(_ntwkSrvcDao.canProviderSupportServiceInNetwork(42L, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); + // Golden path + assertTrue(_element.canHandle(net, Service.Connectivity)); + + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Vlan); + // Only broadcastdomaintype lswitch is supported + assertFalse(_element.canHandle(net, Service.Connectivity)); + + when(net.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(_ntwkSrvcDao.canProviderSupportServiceInNetwork(42L, Service.Connectivity, Provider.NiciraNvp)).thenReturn(false); + // No nvp provider in the network + assertFalse(_element.canHandle(net, Service.Connectivity)); + + when(_networkManager.isProviderForNetwork(Provider.NiciraNvp, 42L)).thenReturn(false); + when(_ntwkSrvcDao.canProviderSupportServiceInNetwork(42L, Service.Connectivity, Provider.NiciraNvp)).thenReturn(true); + // NVP provider does not provide Connectivity for this network + assertFalse(_element.canHandle(net, Service.Connectivity)); + + when(_networkManager.isProviderForNetwork(Provider.NiciraNvp, 42L)).thenReturn(true); + // Only service Connectivity is supported + assertFalse(_element.canHandle(net, Service.Dhcp)); + + } + + @Test + public void implementTest() throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { + Network network = mock(Network.class); + when(network.getBroadcastDomainType()).thenReturn(BroadcastDomainType.Lswitch); + when(network.getId()).thenReturn(42L); + + NetworkOffering offering = mock(NetworkOffering.class); + when(offering.getId()).thenReturn(42L); + when(offering.getTrafficType()).thenReturn(TrafficType.Guest); + when(offering.getGuestType()).thenReturn(GuestType.Isolated); + + DeployDestination dest = mock(DeployDestination.class); + + Domain dom = mock(Domain.class); + when(dom.getName()).thenReturn("domain"); + Account acc = mock(Account.class); + when(acc.getAccountName()).thenReturn("accountname"); + ReservationContext context = mock(ReservationContext.class); + when(context.getDomain()).thenReturn(dom); + when(context.getAccount()).thenReturn(acc); + + //assertTrue(_element.implement(network, offering, dest, context)); + } + +} 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..e37b2f42105 --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/guru/NiciraNvpGuestNetworkGuruTest.java @@ -0,0 +1,457 @@ +// 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(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + 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 testImplementWithCidr() 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); + when(network.getGateway()).thenReturn("10.1.1.1"); + when(network.getCidr()).thenReturn("10.1.1.0/24"); + + + 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(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + when(agentmgr.easySend(eq(42L), (Command)any())).thenReturn(answer); + + Network implementednetwork = guru.implement(network, offering, dest, res); + assertTrue(implementednetwork != null); + assertTrue(implementednetwork.getCidr().equals("10.1.1.0/24")); + assertTrue(implementednetwork.getGateway().equals("10.1.1.1")); + verify(agentmgr, times(1)).easySend(eq(42L), (Command)any()); + } + + @Test + public void testImplementURIException() 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(answer.getLogicalSwitchUuid()).thenReturn("aaaaa"); + 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/test/com/cloud/network/nicira/NatRuleTest.java b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.java new file mode 100644 index 00000000000..88c5402822d --- /dev/null +++ b/plugins/network-elements/nicira-nvp/test/com/cloud/network/nicira/NatRuleTest.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.network.nicira; + +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 d5a776eb94d..6bc08f6c787 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; @@ -50,7 +49,7 @@ public class OvsElement extends AdapterBase implements NetworkElement { OvsTunnelManager _ovsTunnelMgr; @Override - public boolean destroy(Network network) + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java index 43ac806ed94..b66f75c15e4 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelInterfaceVO.java @@ -17,6 +17,8 @@ package com.cloud.network.ovs.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name=("ovs_tunnel_interface")) -public class OvsTunnelInterfaceVO { +public class OvsTunnelInterfaceVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java index d995c1c02af..4c99002f332 100644 --- a/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java +++ b/plugins/network-elements/ovs/src/com/cloud/network/ovs/dao/OvsTunnelNetworkVO.java @@ -17,6 +17,8 @@ package com.cloud.network.ovs.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name=("ovs_tunnel_network")) -public class OvsTunnelNetworkVO { +public class OvsTunnelNetworkVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/plugins/pom.xml b/plugins/pom.xml index a55289f06a1..f0589a1caaf 100644 --- a/plugins/pom.xml +++ b/plugins/pom.xml @@ -32,12 +32,14 @@ test + acl/static-role-based deployment-planners/user-concentrated-pod deployment-planners/user-dispersing host-allocators/random hypervisors/ovm hypervisors/xen hypervisors/kvm + hypervisors/simulator network-elements/elastic-loadbalancer network-elements/ovs network-elements/nicira-nvp @@ -45,8 +47,8 @@ user-authenticators/ldap user-authenticators/md5 user-authenticators/plain-text - storage/volume/solidfire - storage/image/s3 + user-authenticators/sha256salted + network-elements/dns-notifier @@ -124,6 +126,17 @@ hypervisors/vmware + + simulator + + + simulator + + + + 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/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java index a5733cad3f0..00b4c1fef9b 100644 --- a/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java +++ b/plugins/user-authenticators/ldap/src/com/cloud/server/auth/LDAPUserAuthenticator.java @@ -15,12 +15,12 @@ // package com.cloud.server.auth; -import java.util.HashMap; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.util.Hashtable; import java.util.Map; import javax.ejb.Local; -import javax.naming.AuthenticationException; import javax.naming.ConfigurationException; import javax.naming.Context; import javax.naming.NamingEnumeration; @@ -31,16 +31,15 @@ import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; +import org.bouncycastle.util.encoders.Base64; -import com.cloud.api.ApiConstants.LDAPParams; -import com.cloud.configuration.Config; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.server.ManagementServer; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.crypt.DBEncryptionUtil; +import com.cloud.utils.exception.CloudRuntimeException; @Component @@ -161,4 +160,17 @@ public class LDAPUserAuthenticator extends DefaultUserAuthenticator { _userAccountDao = locator.getDao(UserAccountDao.class); return true; } + + @Override + public String encode(String password) { + // Password is not used, so set to a random string + try { + SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG"); + byte bytes[] = new byte[20]; + randomGen.nextBytes(bytes); + return Base64.encode(bytes).toString(); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Failed to generate random password",e); + } + } } 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/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java index edba766ec9e..ab89c92ea6b 100644 --- a/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java +++ b/plugins/user-authenticators/md5/src/com/cloud/server/auth/MD5UserAuthenticator.java @@ -15,6 +15,9 @@ package com.cloud.server.auth; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.Map; import javax.ejb.Local; @@ -27,6 +30,7 @@ import com.cloud.server.ManagementServer; import com.cloud.user.UserAccount; import com.cloud.user.dao.UserAccountDao; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.exception.CloudRuntimeException; /** * Simple UserAuthenticator that performs a MD5 hash of the password before @@ -51,31 +55,7 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { return false; } - /** - MessageDigest md5; - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new CloudRuntimeException("Error", e); - } - md5.reset(); - BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); - - // make sure our MD5 hash value is 32 digits long... - StringBuffer sb = new StringBuffer(); - String pwStr = pwInt.toString(16); - int padding = 32 - pwStr.length(); - for (int i = 0; i < padding; i++) { - sb.append('0'); - } - sb.append(pwStr); - **/ - - // Will: The MD5Authenticator is now a straight pass-through comparison of the - // the passwords because we will not assume that the password passed in has - // already been MD5 hashed. I am keeping the above code in case this requirement changes - // or people need examples of how to MD5 hash passwords in java. - if (!user.getPassword().equals(password)) { + if (!user.getPassword().equals(encode(password))) { s_logger.debug("Password does not match"); return false; } @@ -89,4 +69,25 @@ public class MD5UserAuthenticator extends DefaultUserAuthenticator { _userAccountDao = locator.getDao(UserAccountDao.class); return true; } + + @Override + public String encode(String password) { + MessageDigest md5 = null; + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Unable to hash password", e); + } + + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < padding; i++) { + sb.append('0'); // make sure the MD5 password is 32 digits long + } + sb.append(pwStr); + return sb.toString(); + } } 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/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java index dfd3cfae5cd..bc18e9f03c4 100644 --- a/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java +++ b/plugins/user-authenticators/plain-text/src/com/cloud/server/auth/PlainTextUserAuthenticator.java @@ -89,4 +89,10 @@ public class PlainTextUserAuthenticator extends DefaultUserAuthenticator { _userAccountDao = locator.getDao(UserAccountDao.class); return true; } + + @Override + public String encode(String password) { + // Plaintext so no encoding at all + return password; + } } diff --git a/plugins/user-authenticators/sha256salted/pom.xml b/plugins/user-authenticators/sha256salted/pom.xml new file mode 100644 index 00000000000..3f530f76e17 --- /dev/null +++ b/plugins/user-authenticators/sha256salted/pom.xml @@ -0,0 +1,29 @@ + + + 4.0.0 + cloud-plugin-user-authenticator-sha256salted + Apache CloudStack Plugin - User Authenticator SHA256 Salted + + org.apache.cloudstack + cloudstack-plugins + 4.1.0-SNAPSHOT + ../../pom.xml + + diff --git a/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java new file mode 100644 index 00000000000..26c33a5a9ec --- /dev/null +++ b/plugins/user-authenticators/sha256salted/src/com/cloud/server/auth/SHA256SaltedUserAuthenticator.java @@ -0,0 +1,122 @@ +// 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.server.auth; + +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; +import org.bouncycastle.util.encoders.Base64; + +import com.cloud.server.ManagementServer; +import com.cloud.servlet.CloudStartupServlet; +import com.cloud.user.UserAccount; +import com.cloud.user.dao.UserAccountDao; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.cloud.utils.exception.CloudRuntimeException; + +@Local(value={UserAuthenticator.class}) +public class SHA256SaltedUserAuthenticator extends DefaultUserAuthenticator { + public static final Logger s_logger = Logger.getLogger(SHA256SaltedUserAuthenticator.class); + + @Inject + private UserAccountDao _userAccountDao; + private static int s_saltlen = 20; + + public boolean configure(String name, Map params) + throws ConfigurationException { + super.configure(name, params); + return true; + } + + /* (non-Javadoc) + * @see com.cloud.server.auth.UserAuthenticator#authenticate(java.lang.String, java.lang.String, java.lang.Long, java.util.Map) + */ + @Override + public boolean authenticate(String username, String password, + Long domainId, Map requestParameters) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Retrieving user: " + username); + } + UserAccount user = _userAccountDao.getUserAccount(username, domainId); + if (user == null) { + s_logger.debug("Unable to find user with " + username + " in domain " + domainId); + return false; + } + + try { + String storedPassword[] = user.getPassword().split(":"); + if (storedPassword.length != 2) { + s_logger.warn("The stored password for " + username + " isn't in the right format for this authenticator"); + return false; + } + byte salt[] = Base64.decode(storedPassword[0]); + String hashedPassword = encode(password, salt); + return storedPassword[1].equals(hashedPassword); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Unable to hash password", e); + } catch (UnsupportedEncodingException e) { + throw new CloudRuntimeException("Unable to hash password", e); + } + } + + /* (non-Javadoc) + * @see com.cloud.server.auth.UserAuthenticator#encode(java.lang.String) + */ + @Override + public String encode(String password) { + // 1. Generate the salt + SecureRandom randomGen; + try { + randomGen = SecureRandom.getInstance("SHA1PRNG"); + + byte salt[] = new byte[s_saltlen]; + randomGen.nextBytes(salt); + + String saltString = new String(Base64.encode(salt)); + String hashString = encode(password, salt); + + // 3. concatenate the two and return + return saltString + ":" + hashString; + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Unable to hash password", e); + } catch (UnsupportedEncodingException e) { + throw new CloudRuntimeException("Unable to hash password", e); + } + } + + public String encode(String password, byte[] salt) throws UnsupportedEncodingException, NoSuchAlgorithmException { + byte[] passwordBytes = password.getBytes("UTF-8"); + byte[] hashSource = new byte[passwordBytes.length + s_saltlen]; + System.arraycopy(passwordBytes, 0, hashSource, 0, passwordBytes.length); + System.arraycopy(salt, 0, hashSource, passwordBytes.length, s_saltlen); + + // 2. Hash the password with the salt + MessageDigest md = MessageDigest.getInstance("SHA-256"); + md.update(hashSource); + byte[] digest = md.digest(); + + return new String(Base64.encode(digest)); + } +} diff --git a/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java b/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.java new file mode 100644 index 00000000000..4e23d14fe43 --- /dev/null +++ b/plugins/user-authenticators/sha256salted/test/src/com/cloud/server/auth/test/AuthenticatorTest.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 src.com.cloud.server.auth.test; + +import static org.junit.Assert.*; + +import java.io.UnsupportedEncodingException; +import java.security.NoSuchAlgorithmException; +import java.util.Collections; + +import javax.naming.ConfigurationException; + +import org.bouncycastle.util.encoders.Base64; +import org.junit.Before; +import org.junit.Test; + +import com.cloud.server.auth.SHA256SaltedUserAuthenticator; + +public class AuthenticatorTest { + + @Before + public void setUp() throws Exception { + } + + @Test + public void testEncode() throws UnsupportedEncodingException, NoSuchAlgorithmException { + SHA256SaltedUserAuthenticator authenticator = + new SHA256SaltedUserAuthenticator(); + + try { + authenticator.configure("SHA256", Collections.emptyMap()); + } catch (ConfigurationException e) { + fail(e.toString()); + } + + String encodedPassword = authenticator.encode("password"); + + String storedPassword[] = encodedPassword.split(":"); + assertEquals ("hash must consist of two components", storedPassword.length, 2); + + byte salt[] = Base64.decode(storedPassword[0]); + String hashedPassword = authenticator.encode("password", salt); + + assertEquals("compare hashes", storedPassword[1], hashedPassword); + + } + +} diff --git a/pom.xml b/pom.xml index f2b0cf2e760..1417996630b 100644 --- a/pom.xml +++ b/pom.xml @@ -16,7 +16,8 @@ specific language governing permissions and limitations under the License. --> - + 4.0.0 @@ -30,7 +31,7 @@ 4.1.0-SNAPSHOT pom Apache CloudStack - CloudStack is an IaaS (“Infrastracture as a Serviceâ€) cloud orchestration platform. + Apache CloudStack is an IaaS (“Infrastracture as a Serviceâ€) cloud orchestration platform. http://www.cloudstack.org scm:git:https://git-wip-us.apache.org/repos/asf/incubator-cloudstack.git @@ -64,10 +65,11 @@ build213-svnkit-1.3-patch 1.5.0 1.7.1 + 14.0-rc1 5.6.100-1-SNAPSHOT 3.1 - 4.0 - 5.1.12 + 4.2.1 + 5.1.21 1.3.1 3.1.3 1.4 @@ -79,9 +81,11 @@ 2.4 1.2 1.0-20081010.060147 - 3.1.2.RELEASE - true - + 4.1 + 1.9.5 + 1.3.21.1 + 2.6 + 1.4 @@ -164,6 +168,16 @@ tools/devcloud + + + + mysql + mysql-connector-java + ${cs.mysql.version} + + + + junit @@ -171,100 +185,11 @@ ${cs.junit.version} test - - - org.springframework - spring-core - ${org.springframework.version} - - - - org.springframework - spring-expression - ${org.springframework.version} - - - - org.springframework - spring-beans - ${org.springframework.version} - - - - org.springframework - spring-aop - ${org.springframework.version} - - - - org.springframework - spring-context - ${org.springframework.version} - - - - org.springframework - spring-context-support - ${org.springframework.version} - - - - org.springframework - spring-tx - ${org.springframework.version} - - - - org.springframework - spring-jdbc - ${org.springframework.version} - - - - org.springframework - spring-orm - ${org.springframework.version} - - - - org.springframework - spring-oxm - ${org.springframework.version} - - - - org.springframework - spring-web - ${org.springframework.version} - - - - org.springframework - spring-webmvc - ${org.springframework.version} - - - - org.springframework - spring-test - ${org.springframework.version} - test - - - org.aspectj - aspectjrt - 1.7.1 - - - org.aspectj - aspectjweaver - 1.7.1 - - - javax.inject - javax.inject - 1 + org.mockito + mockito-all + 1.9.5 + test @@ -275,7 +200,7 @@ org.apache.tomcat.maven tomcat7-maven-plugin - 2.0-SNAPSHOT + 2.0 org.apache.rat @@ -285,9 +210,14 @@ 0 false + CHANGES INSTALL.md + .idea/ + *.log + **/*.patch **/.classpath **/.project + **/*.iml **/.settings/** .metadata/** .git/** @@ -350,14 +280,17 @@ patches/systemvm/debian/config/etc/apache2/vhostexample.conf patches/systemvm/debian/config/etc/dnsmasq.conf patches/systemvm/debian/config/etc/vpcdnsmasq.conf - patches/systemvm/debian/config/etc/ssh/sshd_config - patches/systemvm/debian/config/etc/rsyslog.conf + patches/systemvm/debian/config/etc/ssh/sshd_config + + patches/systemvm/debian/config/etc/rsyslog.conf + patches/systemvm/debian/config/etc/logrotate.conf patches/systemvm/debian/config/etc/logrotate.d/* patches/systemvm/debian/config/etc/sysctl.conf patches/systemvm/debian/config/root/redundant_router/keepalived.conf.templ patches/systemvm/debian/config/root/redundant_router/arping_gateways.sh.templ - patches/systemvm/debian/config/root/redundant_router/conntrackd.conf.templ + patches/systemvm/debian/config/root/redundant_router/conntrackd.conf.templ + patches/systemvm/debian/vpn/etc/ipsec.conf patches/systemvm/debian/vpn/etc/ppp/options.xl2tpd patches/systemvm/debian/vpn/etc/xl2tpd/xl2tpd.conf @@ -414,6 +347,11 @@ + + org.apache.maven.plugins + maven-dependency-plugin + 2.5.1 + org.codehaus.mojo cobertura-maven-plugin @@ -429,17 +367,14 @@ - - - deps - - deps - - developer developer + tools/apidoc + tools/devcloud + tools/marvin + tools/cli @@ -453,7 +388,5 @@ vmware-base - - diff --git a/python/lib/cloudutils/serviceConfig.py b/python/lib/cloudutils/serviceConfig.py index 4c36038ff71..6b211eb5074 100755 --- a/python/lib/cloudutils/serviceConfig.py +++ b/python/lib/cloudutils/serviceConfig.py @@ -703,7 +703,7 @@ class firewallConfigServer(firewallConfigBase): if self.syscfg.env.svrMode == "myCloud": self.ports = "443 8080 8250 8443 9090".split() else: - self.ports = "8080 8250 9090".split() + self.ports = "8080 7080 8250 9090".split() class ubuntuFirewallConfigServer(firewallConfigServer): def allowPort(self, port): diff --git a/scripts/network/juniper/firewall-filter-term-add.xml b/scripts/network/juniper/firewall-filter-term-add.xml new file mode 100644 index 00000000000..e7f3a63f8e8 --- /dev/null +++ b/scripts/network/juniper/firewall-filter-term-add.xml @@ -0,0 +1,43 @@ + + + + + + +%filter-name% + +%term-name% + +%source-address-entries% + +%dest-ip-address% + +%protocol-options% + + +%count-name% + + + + + + + + diff --git a/scripts/network/juniper/firewall-filter-term-getone.xml b/scripts/network/juniper/firewall-filter-term-getone.xml new file mode 100644 index 00000000000..2c7e10dd354 --- /dev/null +++ b/scripts/network/juniper/firewall-filter-term-getone.xml @@ -0,0 +1,32 @@ + + + + + + +%filter-name% + +%term-name% + + + + + + diff --git a/scripts/network/juniper/template-entry.xml b/scripts/network/juniper/template-entry.xml new file mode 100644 index 00000000000..ab92d6d7d7d --- /dev/null +++ b/scripts/network/juniper/template-entry.xml @@ -0,0 +1,21 @@ + +<%name%> +%value% + 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/xcposs/NFSSR.py b/scripts/vm/hypervisor/xenserver/xcposs/NFSSR.py index 7342aaf863e..627fed24043 100644 --- a/scripts/vm/hypervisor/xenserver/xcposs/NFSSR.py +++ b/scripts/vm/hypervisor/xenserver/xcposs/NFSSR.py @@ -40,8 +40,8 @@ CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', - 'vendor': 'Citrix Systems Inc', - 'copyright': '(C) 2008 Citrix Systems Inc', + 'vendor': 'The Apache Software Foundation', + 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, diff --git a/scripts/vm/hypervisor/xenserver/xcposs/patch b/scripts/vm/hypervisor/xenserver/xcposs/patch index b121a5628a9..6dc3baae555 100644 --- a/scripts/vm/hypervisor/xenserver/xcposs/patch +++ b/scripts/vm/hypervisor/xenserver/xcposs/patch @@ -64,4 +64,4 @@ cloud-prepare-upgrade.sh=..,0755,/usr/lib/xcp/bin getRouterStatus.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin bumpUpPriority.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin getDomRVersion.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin -storagePlugin=..,0755,/usr/lib/xcp/plugins +router_proxy.sh=../../../../network/domr/,0755,/usr/lib/xcp/bin diff --git a/scripts/vm/hypervisor/xenserver/xcposs/vmops b/scripts/vm/hypervisor/xenserver/xcposs/vmops index c8e6013f532..52625e181e1 100644 --- a/scripts/vm/hypervisor/xenserver/xcposs/vmops +++ b/scripts/vm/hypervisor/xenserver/xcposs/vmops @@ -1515,6 +1515,22 @@ def createISOVHD(session, args): session.xenapi.VBD.destroy(vbd) return vdi_uuid +@echo +def routerProxy(session, args): + sargs = args['args'] + cmd = sargs.split(' ') + cmd.insert(0, "/usr/lib/xcp/bin/router_proxy.sh") + cmd.insert(0, "/bin/bash") + try: + txt = util.pread2(cmd) + if txt is None or len(txt) == 0 : + txt = 'success' + except: + util.SMlog("routerProxy command " + sargs + " failed " ) + txt = '' + + return txt + @echo def getDomRVersion(session, args): sargs = args['args'] @@ -1546,4 +1562,5 @@ if __name__ == "__main__": "bumpUpPriority":bumpUpPriority, "getDomRVersion":getDomRVersion, "kill_copy_process":kill_copy_process, "createISOVHD":createISOVHD, + "routerProxy":routerProxy, "setDNATRule":setDNATRule}) diff --git a/scripts/vm/hypervisor/xenserver/xcpserver/NFSSR.py b/scripts/vm/hypervisor/xenserver/xcpserver/NFSSR.py index 3ed557d3259..11f0491572e 100755 --- a/scripts/vm/hypervisor/xenserver/xcpserver/NFSSR.py +++ b/scripts/vm/hypervisor/xenserver/xcpserver/NFSSR.py @@ -40,8 +40,8 @@ CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', - 'vendor': 'Citrix Systems Inc', - 'copyright': '(C) 2008 Citrix Systems Inc', + 'vendor': 'The Apache Software Foundation', + 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, diff --git a/scripts/vm/hypervisor/xenserver/xenserver56/NFSSR.py b/scripts/vm/hypervisor/xenserver/xenserver56/NFSSR.py index 75da34b8c79..a9cd58d9ca6 100755 --- a/scripts/vm/hypervisor/xenserver/xenserver56/NFSSR.py +++ b/scripts/vm/hypervisor/xenserver/xenserver56/NFSSR.py @@ -40,8 +40,8 @@ CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', - 'vendor': 'Citrix Systems Inc', - 'copyright': '(C) 2008 Citrix Systems Inc', + 'vendor': 'The Apache Software Foundation', + 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, 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/NFSSR.py b/scripts/vm/hypervisor/xenserver/xenserver56fp1/NFSSR.py index e4139535517..290c587aac4 100755 --- a/scripts/vm/hypervisor/xenserver/xenserver56fp1/NFSSR.py +++ b/scripts/vm/hypervisor/xenserver/xenserver56fp1/NFSSR.py @@ -41,8 +41,8 @@ CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', - 'vendor': 'Citrix Systems Inc', - 'copyright': '(C) 2008 Citrix Systems Inc', + 'vendor': 'The Apache Software Foundation', + 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, 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/NFSSR.py b/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py index 5838aceef64..0d6badb4098 100755 --- a/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py +++ b/scripts/vm/hypervisor/xenserver/xenserver60/NFSSR.py @@ -42,8 +42,8 @@ CONFIGURATION = [ [ 'server', 'hostname or IP address of NFS server (required)' DRIVER_INFO = { 'name': 'NFS VHD', 'description': 'SR plugin which stores disks as VHD files on a remote NFS filesystem', - 'vendor': 'Citrix Systems Inc', - 'copyright': '(C) 2008 Citrix Systems Inc', + 'vendor': 'The Apache Software Foundation', + 'copyright': 'Copyright (c) 2012 The Apache Software Foundation', 'driver_version': '1.0', 'required_api_version': '1.0', 'capabilities': CAPABILITIES, 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/scripts/vm/network/vnet/modifyvlan.sh b/scripts/vm/network/vnet/modifyvlan.sh index 5577825ea54..8ed3905a579 100755 --- a/scripts/vm/network/vnet/modifyvlan.sh +++ b/scripts/vm/network/vnet/modifyvlan.sh @@ -67,6 +67,8 @@ addVlan() { return 2 fi fi + + brctl setfd $vlanBr 0 fi #pif is eslaved into vlanBr? diff --git a/server/pom.xml b/server/pom.xml index ed21c37bda8..9e6bc68f8f6 100644 --- a/server/pom.xml +++ b/server/pom.xml @@ -42,6 +42,11 @@ httpcore ${cs.httpcore.version} + + org.apache.httpcomponents + httpclient + ${cs.httpcore.version} + mysql mysql-connector-java @@ -63,6 +68,11 @@ jstl ${cs.jstl.version} + + commons-codec + commons-codec + ${cs.codec.version} + org.apache.cloudstack cloud-utils @@ -71,11 +81,10 @@ test - org.apache.cloudstack - cloud-engine-api - ${project.version} + org.reflections + reflections + 0.9.8 - install @@ -91,8 +100,16 @@ org.apache.maven.plugins maven-surefire-plugin + -Xmx1024m com/cloud/upgrade/* + com/cloud/async/* + com/cloud/cluster/* + com/cloud/snapshot/* + com/cloud/storage/dao/* + com/cloud/vm/dao/* + com/cloud/vpc/* + com/cloud/api/ListPerfTest.java diff --git a/server/src/com/cloud/acl/DomainChecker.java b/server/src/com/cloud/acl/DomainChecker.java index af2798a86c9..40564fe2904 100755 --- a/server/src/com/cloud/acl/DomainChecker.java +++ b/server/src/com/cloud/acl/DomainChecker.java @@ -21,10 +21,11 @@ import javax.inject.Inject; import org.springframework.stereotype.Component; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.api.BaseCmd; import com.cloud.dc.DataCenter; import com.cloud.domain.Domain; -import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.exception.PermissionDeniedException; import com.cloud.network.Network; @@ -41,16 +42,21 @@ import com.cloud.user.User; import com.cloud.user.dao.AccountDao; import com.cloud.utils.component.AdapterBase; -@Component -@Local(value=SecurityChecker.class) +@Local(value = SecurityChecker.class) public class DomainChecker extends AdapterBase implements SecurityChecker { - @Inject DomainDao _domainDao; - @Inject AccountDao _accountDao; - @Inject LaunchPermissionDao _launchPermissionDao; - @Inject ProjectManager _projectMgr; - @Inject ProjectAccountDao _projecAccountDao; - @Inject NetworkManager _networkMgr; + @Inject + DomainDao _domainDao; + @Inject + AccountDao _accountDao; + @Inject + LaunchPermissionDao _launchPermissionDao; + @Inject + ProjectManager _projectMgr; + @Inject + ProjectAccountDao _projecAccountDao; + @Inject + NetworkManager _networkMgr; protected DomainChecker() { super(); @@ -87,7 +93,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { public boolean checkAccess(Account caller, ControlledEntity entity, AccessType accessType) throws PermissionDeniedException { if (entity instanceof VirtualMachineTemplate) { - VirtualMachineTemplate template = (VirtualMachineTemplate)entity; + VirtualMachineTemplate template = (VirtualMachineTemplate) entity; Account owner = _accountDao.findById(template.getAccountId()); // validate that the template is usable by the account if (!template.isPublicTemplate()) { @@ -112,7 +118,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { return true; } else if (entity instanceof Network && accessType != null && accessType == AccessType.UseNetwork) { - _networkMgr.checkNetworkPermissions(caller, (Network)entity); + _networkMgr.checkNetworkPermissions(caller, (Network) entity); } else { if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { Account account = _accountDao.findById(entity.getAccountId()); @@ -123,7 +129,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { if (!_projectMgr.canModifyProjectAccount(caller, account.getId())) { throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity); } - } else if (!_projectMgr.canAccessProjectAccount(caller, account.getId())){ + } else if (!_projectMgr.canAccessProjectAccount(caller, account.getId())) { throw new PermissionDeniedException(caller + " does not have permission to operate with resource " + entity); } } else { @@ -144,40 +150,28 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } @Override - public boolean checkAccess(Account account, DiskOffering dof) throws PermissionDeniedException - { - if(account == null || dof.getDomainId() == null) - {//public offering + public boolean checkAccess(Account account, DiskOffering dof) throws PermissionDeniedException { + if (account == null || dof.getDomainId() == null) {//public offering return true; - } - else - { + } else { //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN) - { + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { return true; } //if account is normal user or domain admin //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for disk offering) - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - { - if(account.getDomainId() == dof.getDomainId()) - { + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == dof.getDomainId()) { return true; //disk offering and account at exact node - } - else - { - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true) - { - if(domainRecord.getId() == dof.getDomainId()) - { + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == dof.getDomainId()) { //found as a child return true; } - if(domainRecord.getParent() != null) { + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; @@ -192,40 +186,28 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } @Override - public boolean checkAccess(Account account, ServiceOffering so) throws PermissionDeniedException - { - if(account == null || so.getDomainId() == null) - {//public offering + public boolean checkAccess(Account account, ServiceOffering so) throws PermissionDeniedException { + if (account == null || so.getDomainId() == null) {//public offering return true; - } - else - { + } else { //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN) - { + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { return true; } //if account is normal user or domain admin //check if account's domain is a child of zone's domain (Note: This is made consistent with the list command for service offering) - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) - { - if(account.getDomainId() == so.getDomainId()) - { + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == so.getDomainId()) { return true; //service offering and account at exact node - } - else - { - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true) - { - if(domainRecord.getId() == so.getDomainId()) - { + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == so.getDomainId()) { //found as a child return true; } - if(domainRecord.getParent() != null) { + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; @@ -241,28 +223,27 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { @Override public boolean checkAccess(Account account, DataCenter zone) throws PermissionDeniedException { - if(account == null || zone.getDomainId() == null){//public zone + if (account == null || zone.getDomainId() == null) {//public zone return true; - }else{ + } else { //admin has all permissions - if(account.getType() == Account.ACCOUNT_TYPE_ADMIN){ + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { return true; } //if account is normal user //check if account's domain is a child of zone's domain - else if(account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_PROJECT){ - if(account.getDomainId() == zone.getDomainId()){ + else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_PROJECT) { + if (account.getDomainId() == zone.getDomainId()) { return true; //zone and account at exact node - }else{ - DomainVO domainRecord = _domainDao.findById(account.getDomainId()); - if(domainRecord != null) - { - while(true){ - if(domainRecord.getId() == zone.getDomainId()){ + } else { + Domain domainRecord = _domainDao.findById(account.getDomainId()); + if (domainRecord != null) { + while (true) { + if (domainRecord.getId() == zone.getDomainId()) { //found as a child return true; } - if(domainRecord.getParent() != null) { + if (domainRecord.getParent() != null) { domainRecord = _domainDao.findById(domainRecord.getParent()); } else { break; @@ -275,21 +256,20 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } //if account is domain admin //check if the account's domain is either child of zone's domain, or if zone's domain is child of account's domain - else if(account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN){ - if(account.getDomainId() == zone.getDomainId()){ + else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) { + if (account.getDomainId() == zone.getDomainId()) { return true; //zone and account at exact node - }else{ - DomainVO zoneDomainRecord = _domainDao.findById(zone.getDomainId()); - DomainVO accountDomainRecord = _domainDao.findById(account.getDomainId()); - if(accountDomainRecord != null) - { - DomainVO localRecord = accountDomainRecord; - while(true){ - if(localRecord.getId() == zone.getDomainId()){ + } else { + Domain zoneDomainRecord = _domainDao.findById(zone.getDomainId()); + Domain accountDomainRecord = _domainDao.findById(account.getDomainId()); + if (accountDomainRecord != null) { + Domain localRecord = accountDomainRecord; + while (true) { + if (localRecord.getId() == zone.getDomainId()) { //found as a child return true; } - if(localRecord.getParent() != null) { + if (localRecord.getParent() != null) { localRecord = _domainDao.findById(localRecord.getParent()); } else { break; @@ -297,7 +277,7 @@ public class DomainChecker extends AdapterBase implements SecurityChecker { } } //didn't find in upper tree - if(zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())){ + if (zoneDomainRecord.getPath().contains(accountDomainRecord.getPath())) { return true; } } diff --git a/server/src/com/cloud/agent/manager/AgentManagerImpl.java b/server/src/com/cloud/agent/manager/AgentManagerImpl.java index d37bd15cb92..1ffab59a357 100755 --- a/server/src/com/cloud/agent/manager/AgentManagerImpl.java +++ b/server/src/com/cloud/agent/manager/AgentManagerImpl.java @@ -221,6 +221,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { @Inject protected AgentMonitor _monitor = null; protected ExecutorService _executor; + protected ThreadPoolExecutor _connectExecutor; protected StateMachine2 _statusStateMachine = Status.getStateMachine(); @@ -277,6 +278,11 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { _executor = new ThreadPoolExecutor(threads, threads, 60l, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("AgentTaskPool")); + _connectExecutor = new ThreadPoolExecutor(100, 500, 60l, TimeUnit.SECONDS, + new LinkedBlockingQueue(), new NamedThreadFactory("AgentConnectTaskPool")); + //allow core threads to time out even when there are no items in the queue + _connectExecutor.allowCoreThreadTimeOut(true); + _connection = new NioServer("AgentManager", _port, workers + 10, this); s_logger.info("Listening on " + _port + " with " + workers + " workers"); @@ -610,19 +616,19 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { ConnectionException ce = (ConnectionException)e; if (ce.isSetupError()) { s_logger.warn("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage()); - handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected); + handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, true); throw ce; } else { s_logger.info("Monitor " + monitor.second().getClass().getSimpleName() + " says not to continue the connect process for " + hostId + " due to " + e.getMessage()); - handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested); + handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested, true); return attache; } } else if (e instanceof HypervisorVersionChangedException) { - handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested); + handleDisconnectWithoutInvestigation(attache, Event.ShutdownRequested, true); throw new CloudRuntimeException("Unable to connect " + attache.getId(), e); } else { s_logger.error("Monitor " + monitor.second().getClass().getSimpleName() + " says there is an error in the connect process for " + hostId + " due to " + e.getMessage(), e); - handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected); + handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, true); throw new CloudRuntimeException("Unable to connect " + attache.getId(), e); } } @@ -630,13 +636,13 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { } Long dcId = host.getDataCenterId(); - ReadyCommand ready = new ReadyCommand(dcId); + ReadyCommand ready = new ReadyCommand(dcId, host.getId()); Answer answer = easySend(hostId, ready); if (answer == null || !answer.getResult()) { // this is tricky part for secondary storage // make it as disconnected, wait for secondary storage VM to be up // return the attache instead of null, even it is disconnectede - handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected); + handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, true); } agentStatusTransitTo(host, Event.Ready, _nodeId); @@ -830,6 +836,8 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { } } } + + _connectExecutor.shutdownNow(); return true; } @@ -838,7 +846,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { return _name; } - protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) { + protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event, boolean transitState) { long hostId = attache.getId(); s_logger.info("Host " + hostId + " is disconnecting with event " + event); @@ -873,8 +881,11 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { s_logger.debug("Deregistering link for " + hostId + " with state " + nextStatus); } + //remove the attache removeAgent(attache, nextStatus); - if (host != null) { + + //update the DB + if (host != null && transitState) { disconnectAgent(host, event, _nodeId); } @@ -944,7 +955,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { } } - handleDisconnectWithoutInvestigation(attache, event); + handleDisconnectWithoutInvestigation(attache, event, true); host = _hostDao.findById(host.getId()); if (host.getStatus() == Status.Alert || host.getStatus() == Status.Down) { _haMgr.scheduleRestartForVmsOnHost(host, true); @@ -970,7 +981,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { if (_investigate == true) { handleDisconnectWithInvestigation(_attache, _event); } else { - handleDisconnectWithoutInvestigation(_attache, _event); + handleDisconnectWithoutInvestigation(_attache, _event, true); } } catch (final Exception e) { s_logger.error("Exception caught while handling disconnect: ", e); @@ -1062,7 +1073,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { AgentAttache attache = null; attache = findAttache(hostId); if (attache != null) { - handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected); + handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, true); } return true; } else if (event == Event.ShutdownRequested) { @@ -1087,91 +1098,37 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { return attache; } - //TODO: handle mycloud specific private AgentAttache handleConnectedAgent(final Link link, final StartupCommand[] startup, Request request) { AgentAttache attache = null; - StartupAnswer[] answers = new StartupAnswer[startup.length]; + ReadyCommand ready = null; try { HostVO host = _resourceMgr.createHostVOForConnectedAgent(startup); if (host != null) { + ready = new ReadyCommand(host.getDataCenterId(), host.getId()); attache = createAttacheForConnect(host, link); + attache = notifyMonitorsOfConnection(attache, startup, false); } - Command cmd; - for (int i = 0; i < startup.length; i++) { - cmd = startup[i]; - if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) { - answers[i] = new StartupAnswer(startup[i], attache.getId(), getPingInterval()); - break; - } - } - }catch (ConnectionException e) { - Command cmd; - for (int i = 0; i < startup.length; i++) { - cmd = startup[i]; - if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) { - answers[i] = new StartupAnswer(startup[i], e.toString()); - break; - } - } - } catch (IllegalArgumentException e) { - Command cmd; - for (int i = 0; i < startup.length; i++) { - cmd = startup[i]; - if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) { - answers[i] = new StartupAnswer(startup[i], e.toString()); - break; - } - } - } catch (CloudRuntimeException e) { - Command cmd; - for (int i = 0; i < startup.length; i++) { - cmd = startup[i]; - if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) { - answers[i] = new StartupAnswer(startup[i], e.toString()); - break; - } - } + } catch (Exception e) { + s_logger.debug("Failed to handle host connection: " + e.toString()); + ready = new ReadyCommand(null); + ready.setDetails(e.toString()); + } finally { + if (ready == null) { + ready = new ReadyCommand(null); } - - Response response = null; - if (attache != null) { - response = new Response(request, answers[0], _nodeId, attache.getId()); - } else { - response = new Response(request, answers[0], _nodeId, -1); } try { - link.send(response.toBytes()); - } catch (ClosedChannelException e) { - s_logger.debug("Failed to send startupanswer: " + e.toString()); - return null; - } if (attache == null) { - return null; - } - - try { - attache = notifyMonitorsOfConnection(attache, startup, false); - return attache; - } catch (ConnectionException e) { - ReadyCommand ready = new ReadyCommand(null); - ready.setDetails(e.toString()); - try { + final Request readyRequest = new Request(-1, -1, ready, false); + link.send(readyRequest.getBytes()); + } else { easySend(attache.getId(), ready); - } catch (Exception e1) { - s_logger.debug("Failed to send readycommand, due to " + e.toString()); } - return null; - } catch (CloudRuntimeException e) { - ReadyCommand ready = new ReadyCommand(null); - ready.setDetails(e.toString()); - try { - easySend(attache.getId(), ready); - } catch (Exception e1) { - s_logger.debug("Failed to send readycommand, due to " + e.toString()); - } - return null; + } catch (Exception e) { + s_logger.debug("Failed to send ready command:" + e.toString()); } + return attache; } protected class SimulateStartTask implements Runnable { @@ -1206,6 +1163,53 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { } } + protected class HandleAgentConnectTask implements Runnable { + Link _link; + Command[] _cmds; + Request _request; + + HandleAgentConnectTask(Link link, final Command[] cmds, final Request request) { + _link = link; + _cmds = cmds; + _request = request; + } + + @Override + public void run() { + _request.logD("Processing the first command "); + StartupCommand[] startups = new StartupCommand[_cmds.length]; + for (int i = 0; i < _cmds.length; i++) { + startups[i] = (StartupCommand) _cmds[i]; + } + + AgentAttache attache = handleConnectedAgent(_link, startups, _request); + if (attache == null) { + s_logger.warn("Unable to create attache for agent: " + _request); + } + } + } + + protected void connectAgent(Link link, final Command[] cmds, final Request request) { + //send startupanswer to agent in the very beginning, so agent can move on without waiting for the answer for an undetermined time, if we put this logic into another thread pool. + StartupAnswer[] answers = new StartupAnswer[cmds.length]; + Command cmd; + for (int i = 0; i < cmds.length; i++) { + cmd = cmds[i]; + if ((cmd instanceof StartupRoutingCommand) || (cmd instanceof StartupProxyCommand) || (cmd instanceof StartupSecondaryStorageCommand) || (cmd instanceof StartupStorageCommand)) { + answers[i] = new StartupAnswer((StartupCommand)cmds[i], 0, getPingInterval()); + break; + } + } + Response response = null; + response = new Response(request, answers[0], _nodeId, -1); + try { + link.send(response.toBytes()); + } catch (ClosedChannelException e) { + s_logger.debug("Failed to send startupanswer: " + e.toString()); + } + _connectExecutor.execute(new HandleAgentConnectTask(link, cmds, request)); + } + public class AgentHandler extends Task { public AgentHandler(Task.Type type, Link link, byte[] data) { super(type, link, data); @@ -1217,21 +1221,13 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { Command cmd = cmds[0]; boolean logD = true; - Response response = null; if (attache == null) { - request.logD("Processing the first command "); if (!(cmd instanceof StartupCommand)) { s_logger.warn("Throwing away a request because it came through as the first command on a connect: " + request); - return; - } - - StartupCommand[] startups = new StartupCommand[cmds.length]; - for (int i = 0; i < cmds.length; i++) { - startups[i] = (StartupCommand) cmds[i]; - } - attache = handleConnectedAgent(link, startups, request); - if (attache == null) { - s_logger.warn("Unable to create attache for agent: " + request); + } else { + //submit the task for execution + request.logD("Scheduling the first command "); + connectAgent(link, cmds, request); } return; } @@ -1297,6 +1293,8 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { if (cmd instanceof PingRoutingCommand) { boolean gatewayAccessible = ((PingRoutingCommand) cmd).isGatewayAccessible(); HostVO host = _hostDao.findById(Long.valueOf(cmdHostId)); + + if (host != null) { if (!gatewayAccessible) { // alert that host lost connection to // gateway (cannot ping the default route) @@ -1309,6 +1307,10 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { } else { _alertMgr.clearAlert(AlertManager.ALERT_TYPE_ROUTING, host.getDataCenterId(), host.getPodId()); } + } else { + s_logger.debug("Not processing " + PingRoutingCommand.class.getSimpleName() + + " for agent id=" + cmdHostId + "; can't find the host in the DB"); + } } answer = new PingAnswer((PingCommand) cmd); } else if (cmd instanceof ReadyAnswer) { @@ -1330,7 +1332,7 @@ public class AgentManagerImpl implements AgentManager, HandlerFactory, Manager { answers[i] = answer; } - response = new Response(request, answers, _nodeId, attache.getId()); + Response response = new Response(request, answers, _nodeId, attache.getId()); if (s_logger.isDebugEnabled()) { if (logD) { s_logger.debug("SeqA " + attache.getId() + "-" + response.getSequence() + ": Sending " + response); diff --git a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java index 4f09954f560..8c6bae8cdce 100755 --- a/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java +++ b/server/src/com/cloud/agent/manager/ClusteredAgentManagerImpl.java @@ -56,6 +56,7 @@ import com.cloud.agent.api.TransferAgentCommand; import com.cloud.agent.transport.Request; import com.cloud.agent.transport.Request.Version; import com.cloud.agent.transport.Response; +import com.cloud.api.ApiDBUtils; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; import com.cloud.cluster.ClusteredAgentRebalanceService; @@ -274,7 +275,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } @Override - protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event) { + protected boolean handleDisconnectWithoutInvestigation(AgentAttache attache, Status.Event event, boolean transitState) { return handleDisconnect(attache, event, false, true); } @@ -286,7 +287,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust protected boolean handleDisconnect(AgentAttache agent, Status.Event event, boolean investigate, boolean broadcast) { boolean res; if (!investigate) { - res = super.handleDisconnectWithoutInvestigation(agent, event); + res = super.handleDisconnectWithoutInvestigation(agent, event, true); } else { res = super.handleDisconnectWithInvestigation(agent, event); } @@ -309,7 +310,27 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } AgentAttache attache = findAttache(hostId); if (attache != null) { - handleDisconnect(attache, Event.AgentDisconnected, false, false); + //don't process disconnect if the host is being rebalanced + if (_clusterMgr.isAgentRebalanceEnabled()) { + HostTransferMapVO transferVO = _hostTransferDao.findById(hostId); + if (transferVO != null) { + if (transferVO.getFutureOwner() == _nodeId && transferVO.getState() == HostTransferState.TransferStarted) { + s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + + hostId +" as the host is being connected to " + _nodeId); + return true; + } + } + } + + //don't process disconnect if the disconnect came for the host via delayed cluster notification, + //but the host has already reconnected to the current management server + if (!attache.forForward()) { + s_logger.debug("Not processing " + Event.AgentDisconnected + " event for the host id=" + + hostId +" as the host is directly connected to the current management server " + _nodeId); + return true; + } + + return super.handleDisconnectWithoutInvestigation(attache, Event.AgentDisconnected, false); } return true; @@ -500,7 +521,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust } if (agent == null) { AgentUnavailableException ex = new AgentUnavailableException("Host with specified id is not in the right state: " + host.getStatus(), hostId); - ex.addProxyObject(host, hostId, "hostId"); + ex.addProxyObject(ApiDBUtils.findHostById(hostId).getUuid()); throw ex; } @@ -575,6 +596,12 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust logD(data, "Cancel request received"); } agent.cancel(cancel.getSequence()); + final Long current = agent._currentSequence; + //if the request is the current request, always have to trigger sending next request in sequence, + //otherwise the agent queue will be blocked + if (req.executeInSequence() && (current != null && current == Request.getSequence(data))) { + agent.sendNext(Request.getSequence(data)); + } return; } @@ -857,7 +884,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust continue; } - if (transferMap.getInitialOwner() != _nodeId || attache.forForward()) { + if (transferMap.getInitialOwner() != _nodeId || attache == null || attache.forForward()) { s_logger.debug("Management server " + _nodeId + " doesn't own host id=" + hostId + " any more, skipping rebalance for the host"); iterator.remove(); _hostTransferDao.completeAgentTransfer(hostId); @@ -940,9 +967,24 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust HostVO host = _hostDao.findById(hostId); try { if (s_logger.isDebugEnabled()) { + s_logger.debug("Disconnecting host " + host.getId() + "(" + host.getName() + " as a part of rebalance process without notification"); + } + + AgentAttache attache = findAttache(hostId); + if (attache != null) { + result = handleDisconnect(attache, Event.AgentDisconnected, false, false); + } + + if (result) { + if (s_logger.isDebugEnabled()) { s_logger.debug("Loading directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process"); } result = loadDirectlyConnectedHost(host, true); + } else { + s_logger.warn("Failed to disconnect " + host.getId() + "(" + host.getName() + + " as a part of rebalance process without notification"); + } + } catch (Exception ex) { s_logger.warn("Failed to load directly connected host " + host.getId() + "(" + host.getName() + ") to the management server " + _nodeId + " as a part of rebalance process due to:", ex); result = false; @@ -1006,7 +1048,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust try { s_logger.debug("Management server " + _nodeId + " failed to rebalance agent " + hostId); _hostTransferDao.completeAgentTransfer(hostId); - handleDisconnectWithoutInvestigation(findAttache(hostId), Event.RebalanceFailed); + handleDisconnectWithoutInvestigation(findAttache(hostId), Event.RebalanceFailed, true); } catch (Exception ex) { s_logger.warn("Failed to reconnect host id=" + hostId + " as a part of failed rebalance task cleanup"); } @@ -1023,7 +1065,7 @@ public class ClusteredAgentManagerImpl extends AgentManagerImpl implements Clust synchronized (_agents) { ClusteredDirectAgentAttache attache = (ClusteredDirectAgentAttache)_agents.get(hostId); if (attache != null && attache.getQueueSize() == 0 && attache.getNonRecurringListenersSize() == 0) { - handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance); + handleDisconnectWithoutInvestigation(attache, Event.StartAgentRebalance, true); ClusteredAgentAttache forwardAttache = (ClusteredAgentAttache)createAttache(hostId); if (forwardAttache == null) { s_logger.warn("Unable to create a forward attache for the host " + hostId + " as a part of rebalance process"); diff --git a/server/src/com/cloud/alert/AlertManagerImpl.java b/server/src/com/cloud/alert/AlertManagerImpl.java index 9fb9a2193ef..4fbc69570ce 100755 --- a/server/src/com/cloud/alert/AlertManagerImpl.java +++ b/server/src/com/cloud/alert/AlertManagerImpl.java @@ -72,7 +72,6 @@ import com.cloud.storage.StoragePoolVO; import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.VolumeDao; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria; @@ -562,35 +561,35 @@ public class AlertManagerImpl implements AlertManager { //Cluster Level case CapacityVO.CAPACITY_TYPE_MEMORY: - msgSubject = "System Alert: Low Available Memory in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Low Available Memory in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = formatBytesToMegabytes(totalCapacity); usedStr = formatBytesToMegabytes(usedCapacity); msgContent = "System memory is low, total: " + totalStr + " MB, used: " + usedStr + " MB (" + pctStr + "%)"; alertType = ALERT_TYPE_MEMORY; break; case CapacityVO.CAPACITY_TYPE_CPU: - msgSubject = "System Alert: Low Unallocated CPU in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Low Unallocated CPU in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = _dfWhole.format(totalCapacity); usedStr = _dfWhole.format(usedCapacity); msgContent = "Unallocated CPU is low, total: " + totalStr + " Mhz, used: " + usedStr + " Mhz (" + pctStr + "%)"; alertType = ALERT_TYPE_CPU; break; case CapacityVO.CAPACITY_TYPE_STORAGE: - msgSubject = "System Alert: Low Available Storage in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Low Available Storage in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = formatBytesToMegabytes(totalCapacity); usedStr = formatBytesToMegabytes(usedCapacity); msgContent = "Available storage space is low, total: " + totalStr + " MB, used: " + usedStr + " MB (" + pctStr + "%)"; alertType = ALERT_TYPE_STORAGE; break; case CapacityVO.CAPACITY_TYPE_STORAGE_ALLOCATED: - msgSubject = "System Alert: Remaining unallocated Storage is low in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Remaining unallocated Storage is low in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = formatBytesToMegabytes(totalCapacity); usedStr = formatBytesToMegabytes(usedCapacity); msgContent = "Unallocated storage space is low, total: " + totalStr + " MB, allocated: " + usedStr + " MB (" + pctStr + "%)"; alertType = ALERT_TYPE_STORAGE_ALLOCATED; break; case CapacityVO.CAPACITY_TYPE_LOCAL_STORAGE: - msgSubject = "System Alert: Remaining unallocated Local Storage is low in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Remaining unallocated Local Storage is low in cluster " +cluster.getName()+ " pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = formatBytesToMegabytes(totalCapacity); usedStr = formatBytesToMegabytes(usedCapacity); msgContent = "Unallocated storage space is low, total: " + totalStr + " MB, allocated: " + usedStr + " MB (" + pctStr + "%)"; @@ -599,7 +598,7 @@ public class AlertManagerImpl implements AlertManager { //Pod Level case CapacityVO.CAPACITY_TYPE_PRIVATE_IP: - msgSubject = "System Alert: Number of unallocated private IPs is low in pod " +pod.getName()+ " of availablity zone " + dc.getName(); + msgSubject = "System Alert: Number of unallocated private IPs is low in pod " +pod.getName()+ " of availability zone " + dc.getName(); totalStr = Double.toString(totalCapacity); usedStr = Double.toString(usedCapacity); msgContent = "Number of unallocated private IPs is low, total: " + totalStr + ", allocated: " + usedStr + " (" + pctStr + "%)"; @@ -608,28 +607,28 @@ public class AlertManagerImpl implements AlertManager { //Zone Level case CapacityVO.CAPACITY_TYPE_SECONDARY_STORAGE: - msgSubject = "System Alert: Low Available Secondary Storage in availablity zone " + dc.getName(); + msgSubject = "System Alert: Low Available Secondary Storage in availability zone " + dc.getName(); totalStr = formatBytesToMegabytes(totalCapacity); usedStr = formatBytesToMegabytes(usedCapacity); msgContent = "Available secondary storage space is low, total: " + totalStr + " MB, used: " + usedStr + " MB (" + pctStr + "%)"; alertType = ALERT_TYPE_SECONDARY_STORAGE; break; case CapacityVO.CAPACITY_TYPE_VIRTUAL_NETWORK_PUBLIC_IP: - msgSubject = "System Alert: Number of unallocated virtual network public IPs is low in availablity zone " + dc.getName(); + msgSubject = "System Alert: Number of unallocated virtual network public IPs is low in availability zone " + dc.getName(); totalStr = Double.toString(totalCapacity); usedStr = Double.toString(usedCapacity); msgContent = "Number of unallocated public IPs is low, total: " + totalStr + ", allocated: " + usedStr + " (" + pctStr + "%)"; alertType = ALERT_TYPE_VIRTUAL_NETWORK_PUBLIC_IP; break; case CapacityVO.CAPACITY_TYPE_DIRECT_ATTACHED_PUBLIC_IP: - msgSubject = "System Alert: Number of unallocated direct attached public IPs is low in availablity zone " + dc.getName(); + msgSubject = "System Alert: Number of unallocated shared network IPs is low in availability zone " + dc.getName(); totalStr = Double.toString(totalCapacity); usedStr = Double.toString(usedCapacity); - msgContent = "Number of unallocated direct attached public IPs is low, total: " + totalStr + ", allocated: " + usedStr + " (" + pctStr + "%)"; + msgContent = "Number of unallocated shared network IPs is low, total: " + totalStr + ", allocated: " + usedStr + " (" + pctStr + "%)"; alertType = ALERT_TYPE_DIRECT_ATTACHED_PUBLIC_IP; break; case CapacityVO.CAPACITY_TYPE_VLAN: - msgSubject = "System Alert: Number of unallocated VLANs is low in availablity zone " + dc.getName(); + msgSubject = "System Alert: Number of unallocated VLANs is low in availability zone " + dc.getName(); totalStr = Double.toString(totalCapacity); usedStr = Double.toString(usedCapacity); msgContent = "Number of unallocated VLANs is low, total: " + totalStr + ", allocated: " + usedStr + " (" + pctStr + "%)"; diff --git a/server/src/com/cloud/api/ApiDBUtils.java b/server/src/com/cloud/api/ApiDBUtils.java index 3fac7a74a7d..343dad9b67a 100755 --- a/server/src/com/cloud/api/ApiDBUtils.java +++ b/server/src/com/cloud/api/ApiDBUtils.java @@ -5,7 +5,7 @@ // 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, @@ -16,13 +16,60 @@ // under the License. package com.cloud.api; -import java.util.Hashtable; +import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; + +import com.cloud.api.query.dao.AccountJoinDao; +import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.HostJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.dao.VolumeJoinDao; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; +import com.cloud.async.dao.AsyncJobDao; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; @@ -43,6 +90,8 @@ import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.DomainVO; import com.cloud.domain.dao.DomainDao; +import com.cloud.event.Event; +import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.ha.HighAvailabilityManager; import com.cloud.host.Host; @@ -62,27 +111,61 @@ import com.cloud.network.NetworkManager; import com.cloud.network.NetworkProfile; import com.cloud.network.NetworkRuleConfigVO; import com.cloud.network.NetworkVO; +import com.cloud.network.PhysicalNetworkServiceProvider; +import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.Site2SiteCustomerGatewayVO; import com.cloud.network.Networks.TrafficType; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.AutoScalePolicyConditionMapVO; +import com.cloud.network.as.AutoScalePolicyVO; +import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; +import com.cloud.network.as.AutoScaleVmGroupVO; +import com.cloud.network.as.AutoScaleVmProfileVO; +import com.cloud.network.as.ConditionVO; +import com.cloud.network.as.CounterVO; +import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; +import com.cloud.network.as.dao.AutoScalePolicyDao; +import com.cloud.network.as.dao.AutoScaleVmGroupDao; +import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; +import com.cloud.network.as.dao.AutoScaleVmProfileDao; +import com.cloud.network.as.dao.ConditionDao; +import com.cloud.network.as.dao.CounterDao; import com.cloud.network.dao.FirewallRulesCidrsDao; +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.PhysicalNetworkDao; import com.cloud.network.dao.NetworkDomainDao; import com.cloud.network.dao.NetworkRuleConfigDao; +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.dao.Site2SiteVpnGatewayDao; import com.cloud.network.dao.Site2SiteCustomerGatewayDao; +import com.cloud.network.router.VirtualRouter; +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.dao.SecurityGroupDao; +import com.cloud.network.vpc.StaticRouteVO; +import com.cloud.network.vpc.VpcGatewayVO; import com.cloud.network.vpc.VpcManager; +import com.cloud.network.vpc.VpcOffering; +import com.cloud.network.vpc.VpcVO; +import com.cloud.network.vpc.dao.StaticRouteDao; +import com.cloud.network.vpc.dao.VpcGatewayDao; +import com.cloud.network.vpc.dao.VpcOfferingDao; import com.cloud.offering.NetworkOffering; import com.cloud.offering.ServiceOffering; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.projects.Project; +import com.cloud.projects.ProjectAccount; +import com.cloud.projects.ProjectInvitation; import com.cloud.projects.ProjectService; import com.cloud.resource.ResourceManager; import com.cloud.server.Criteria; @@ -104,8 +187,10 @@ 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; import com.cloud.storage.Volume.Type; import com.cloud.storage.VolumeHostVO; import com.cloud.storage.VolumeVO; @@ -113,20 +198,24 @@ import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.storage.dao.GuestOSCategoryDao; import com.cloud.storage.dao.GuestOSDao; import com.cloud.storage.dao.SnapshotDao; +import com.cloud.storage.dao.SnapshotPolicyDao; import com.cloud.storage.dao.StoragePoolDao; 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; +import com.cloud.storage.snapshot.SnapshotPolicy; import com.cloud.user.Account; import com.cloud.user.AccountDetailsDao; import com.cloud.user.AccountVO; import com.cloud.user.ResourceLimitService; import com.cloud.user.SSHKeyPairVO; import com.cloud.user.User; +import com.cloud.user.UserAccount; import com.cloud.user.UserStatisticsVO; import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; @@ -139,6 +228,7 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.InstanceGroup; import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.NicProfile; import com.cloud.vm.UserVmDetailVO; @@ -150,9 +240,9 @@ import com.cloud.vm.VmStats; import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.UserVmDao; -import com.cloud.vm.dao.UserVmData; import com.cloud.vm.dao.UserVmDetailsDao; import com.cloud.vm.dao.VMInstanceDao; +import com.cloud.network.vpc.dao.VpcDao; public class ApiDBUtils { private static ManagementServer _ms; @@ -170,12 +260,14 @@ public class ApiDBUtils { private static DiskOfferingDao _diskOfferingDao; private static DomainDao _domainDao; private static DomainRouterDao _domainRouterDao; + private static DomainRouterJoinDao _domainRouterJoinDao; private static GuestOSDao _guestOSDao; private static GuestOSCategoryDao _guestOSCategoryDao; private static HostDao _hostDao; private static IPAddressDao _ipAddressDao; private static LoadBalancerDao _loadBalancerDao; private static SecurityGroupDao _securityGroupDao; + private static SecurityGroupJoinDao _securityGroupJoinDao; private static NetworkRuleConfigDao _networkRuleConfigDao; private static HostPodDao _podDao; private static ServiceOfferingDao _serviceOfferingDao; @@ -185,10 +277,12 @@ 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; private static UserVmDao _userVmDao; + private static UserVmJoinDao _userVmJoinDao; private static VlanDao _vlanDao; private static VolumeDao _volumeDao; private static Site2SiteVpnGatewayDao _site2SiteVpnGatewayDao; @@ -197,6 +291,7 @@ public class ApiDBUtils { private static DataCenterDao _zoneDao; private static NetworkOfferingDao _networkOfferingDao; private static NetworkDao _networkDao; + private static PhysicalNetworkDao _physicalNetworkDao; private static ConfigurationService _configMgr; private static ConfigurationDao _configDao; private static ConsoleProxyDao _consoleProxyDao; @@ -213,9 +308,38 @@ public class ApiDBUtils { private static UserVmDetailsDao _userVmDetailsDao; private static SSHKeyPairDao _sshKeyPairDao; + private static ConditionDao _asConditionDao; + private static AutoScalePolicyConditionMapDao _asPolicyConditionMapDao; + private static AutoScaleVmGroupPolicyMapDao _asVmGroupPolicyMapDao; + private static AutoScalePolicyDao _asPolicyDao; + private static AutoScaleVmProfileDao _asVmProfileDao; + private static AutoScaleVmGroupDao _asVmGroupDao; + private static CounterDao _counterDao; + private static ResourceTagJoinDao _tagJoinDao; + private static EventJoinDao _eventJoinDao; + private static InstanceGroupJoinDao _vmGroupJoinDao; + private static UserAccountJoinDao _userAccountJoinDao; + private static ProjectJoinDao _projectJoinDao; + private static ProjectAccountJoinDao _projectAccountJoinDao; + private static ProjectInvitationJoinDao _projectInvitationJoinDao; + private static HostJoinDao _hostJoinDao; + private static VolumeJoinDao _volJoinDao; + private static AccountJoinDao _accountJoinDao; + private static AsyncJobJoinDao _jobJoinDao; + + private static PhysicalNetworkTrafficTypeDao _physicalNetworkTrafficTypeDao; + private static PhysicalNetworkServiceProviderDao _physicalNetworkServiceProviderDao; + private static FirewallRulesDao _firewallRuleDao; + private static StaticRouteDao _staticRouteDao; + private static VpcGatewayDao _vpcGatewayDao; + private static VpcDao _vpcDao; + private static VpcOfferingDao _vpcOfferingDao; + private static SnapshotPolicyDao _snapshotPolicyDao; + private static AsyncJobDao _asyncJobDao; + static { _ms = (ManagementServer) ComponentLocator.getComponent(ManagementServer.Name); - ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); _asyncMgr = locator.getManager(AsyncJobManager.class); _securityGroupMgr = locator.getManager(SecurityGroupManager.class); _storageMgr = locator.getManager(StorageManager.class); @@ -230,6 +354,7 @@ public class ApiDBUtils { _diskOfferingDao = locator.getDao(DiskOfferingDao.class); _domainDao = locator.getDao(DomainDao.class); _domainRouterDao = locator.getDao(DomainRouterDao.class); + _domainRouterJoinDao = locator.getDao(DomainRouterJoinDao.class); _guestOSDao = locator.getDao(GuestOSDao.class); _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); _hostDao = locator.getDao(HostDao.class); @@ -244,10 +369,12 @@ 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); _userVmDao = locator.getDao(UserVmDao.class); + _userVmJoinDao = locator.getDao(UserVmJoinDao.class); _vlanDao = locator.getDao(VlanDao.class); _volumeDao = locator.getDao(VolumeDao.class); _site2SiteVpnGatewayDao = locator.getDao(Site2SiteVpnGatewayDao.class); @@ -255,8 +382,10 @@ public class ApiDBUtils { _volumeHostDao = locator.getDao(VolumeHostDao.class); _zoneDao = locator.getDao(DataCenterDao.class); _securityGroupDao = locator.getDao(SecurityGroupDao.class); + _securityGroupJoinDao = locator.getDao(SecurityGroupJoinDao.class); _networkOfferingDao = locator.getDao(NetworkOfferingDao.class); _networkDao = locator.getDao(NetworkDao.class); + _physicalNetworkDao = locator.getDao(PhysicalNetworkDao.class); _configDao = locator.getDao(ConfigurationDao.class); _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); _firewallCidrsDao = locator.getDao(FirewallRulesCidrsDao.class); @@ -271,6 +400,34 @@ public class ApiDBUtils { _taggedResourceService = locator.getManager(TaggedResourceService.class); _sshKeyPairDao = locator.getDao(SSHKeyPairDao.class); _userVmDetailsDao = locator.getDao(UserVmDetailsDao.class); + _asConditionDao = locator.getDao(ConditionDao.class); + _asPolicyDao = locator.getDao(AutoScalePolicyDao.class); + _asPolicyConditionMapDao = locator.getDao(AutoScalePolicyConditionMapDao.class); + _counterDao = locator.getDao(CounterDao.class); + _asVmGroupPolicyMapDao = locator.getDao(AutoScaleVmGroupPolicyMapDao.class); + _tagJoinDao = locator.getDao(ResourceTagJoinDao.class); + _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); + _eventJoinDao = locator.getDao(EventJoinDao.class); + _userAccountJoinDao = locator.getDao(UserAccountJoinDao.class); + _projectJoinDao = locator.getDao(ProjectJoinDao.class); + _projectAccountJoinDao = locator.getDao(ProjectAccountJoinDao.class); + _projectInvitationJoinDao = locator.getDao(ProjectInvitationJoinDao.class); + _hostJoinDao = locator.getDao(HostJoinDao.class); + _volJoinDao = locator.getDao(VolumeJoinDao.class); + _accountJoinDao = locator.getDao(AccountJoinDao.class); + _jobJoinDao = locator.getDao(AsyncJobJoinDao.class); + + _physicalNetworkTrafficTypeDao = locator.getDao(PhysicalNetworkTrafficTypeDao.class); + _physicalNetworkServiceProviderDao = locator.getDao(PhysicalNetworkServiceProviderDao.class); + _firewallRuleDao = locator.getDao(FirewallRulesDao.class); + _staticRouteDao = locator.getDao(StaticRouteDao.class); + _vpcGatewayDao = locator.getDao(VpcGatewayDao.class); + _asVmProfileDao = locator.getDao(AutoScaleVmProfileDao.class); + _asVmGroupDao = locator.getDao(AutoScaleVmGroupDao.class); + _vpcDao = locator.getDao(VpcDao.class); + _vpcOfferingDao = locator.getDao(VpcOfferingDao.class); + _snapshotPolicyDao = locator.getDao(SnapshotPolicyDao.class); + _asyncJobDao = locator.getDao(AsyncJobDao.class); // Note: stats collector should already have been initialized by this time, otherwise a null instance is returned _statsCollector = StatsCollector.getInstance(); @@ -299,20 +456,20 @@ public class ApiDBUtils { // into this utils class. return _ms.getMemoryOrCpuCapacityByHost(poolId, capacityType); } - + public static List getCapacityByClusterPodZone(Long zoneId, Long podId, Long clusterId){ - return _capacityDao.findByClusterPodZone(zoneId,podId,clusterId); + return _capacityDao.findByClusterPodZone(zoneId,podId,clusterId); } - + public static List findNonSharedStorageForClusterPodZone(Long zoneId, Long podId, Long clusterId){ - return _capacityDao.findNonSharedStorageForClusterPodZone(zoneId,podId,clusterId); + return _capacityDao.findNonSharedStorageForClusterPodZone(zoneId,podId,clusterId); } - + public static List getCapacityByPod(){ - return null; - + return null; + } - + public static Long getPodIdForVlan(long vlanDbId) { return _networkMgr.getPodIdForVlan(vlanDbId); } @@ -321,12 +478,13 @@ public class ApiDBUtils { return _ms.getVersion(); } - public static List searchForUserVMs(Criteria c, List permittedAccounts) { - return _userVmMgr.searchForUserVMs(c, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), null, false, permittedAccounts, false, null, null); + public static List searchForUserVMs(Criteria c, List permittedAccounts) { + return _userVmMgr.searchForUserVMs(c, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), + null, false, permittedAccounts, false, null, null).first(); } public static List searchForStoragePools(Criteria c) { - return _ms.searchForStoragePools(c); + return _ms.searchForStoragePools(c).first(); } // /////////////////////////////////////////////////////////// @@ -343,6 +501,10 @@ public class ApiDBUtils { return _resourceLimitMgr.findCorrectResourceLimitForAccount(account, type); } + public static long findCorrectResourceLimit(Long limit, short accountType, ResourceType type) { + return _resourceLimitMgr.findCorrectResourceLimitForAccount(accountType, limit, type); + } + public static AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId) { return _asyncMgr.findInstancePendingAsyncJob(instanceType, instanceId); } @@ -374,8 +536,8 @@ public class ApiDBUtils { return _storageMgr.getStoragePoolTags(poolId); } - public static boolean isLocalStorageActiveOnHost(Host host) { - return _storageMgr.isLocalStorageActiveOnHost(host); + public static boolean isLocalStorageActiveOnHost(Long hostId) { + return _storageMgr.isLocalStorageActiveOnHost(hostId); } public static InstanceGroupVO findInstanceGroupForVM(long vmId) { @@ -401,15 +563,15 @@ public class ApiDBUtils { public static StorageStats getSecondaryStorageStatistics(long id) { return _statsCollector.getStorageStats(id); } - + public static CapacityVO getStoragePoolUsedStats(Long poolId, Long clusterId, Long podId, Long zoneId){ - return _storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); + return _storageMgr.getStoragePoolUsedStats(poolId, clusterId, podId, zoneId); } public static CapacityVO getSecondaryStorageUsedStats(Long hostId, Long zoneId){ - return _storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); + return _storageMgr.getSecondaryStorageUsedStats(hostId, zoneId); } - + // /////////////////////////////////////////////////////////// // Dao methods // // /////////////////////////////////////////////////////////// @@ -442,6 +604,10 @@ public class ApiDBUtils { return _domainDao.findByIdIncludingRemoved(domainId); } + public static boolean isChildDomain(long parentId, long childId) { + return _domainDao.isChildDomain(parentId, childId); + } + public static DomainRouterVO findDomainRouterById(Long routerId) { return _domainRouterDao.findByIdIncludingRemoved(routerId); } @@ -453,7 +619,7 @@ public class ApiDBUtils { public static GuestOS findGuestOSByDisplayName(String displayName) { return _guestOSDao.listByDisplayName(displayName); } - + public static HostVO findHostById(Long hostId) { return _hostDao.findByIdIncludingRemoved(hostId); } @@ -519,15 +685,15 @@ public class ApiDBUtils { } public static VMTemplateVO findTemplateById(Long templateId) { - VMTemplateVO template = _templateDao.findByIdIncludingRemoved(templateId); - if(template != null) { - Map details = _templateDetailsDao.findDetails(templateId); - if(details != null && !details.isEmpty()) - template.setDetails(details); - } - return template; + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(templateId); + if(template != null) { + Map details = _templateDetailsDao.findDetails(templateId); + if(details != null && !details.isEmpty()) + template.setDetails(details); + } + return template; } - + public static VMTemplateHostVO findTemplateHostRef(long templateId, long zoneId) { return findTemplateHostRef(templateId, zoneId, false); } @@ -541,16 +707,20 @@ public class ApiDBUtils { return _storageMgr.getTemplateHostRef(zoneId, templateId, readyOnly); } } - - + + public static VolumeHostVO findVolumeHostRef(long volumeId, long zoneId) { return _volumeHostDao.findVolumeByZone(volumeId, zoneId); } - + public static VMTemplateSwiftVO findTemplateSwiftRef(long templateId) { return _templateSwiftDao.findOneByTemplateId(templateId); } + public static VMTemplateS3VO findTemplateS3Ref(long templateId) { + return _templateS3Dao.findOneByTemplateId(templateId); + } + public static UploadVO findUploadById(Long id) { return _uploadDao.findById(id); } @@ -574,11 +744,11 @@ public class ApiDBUtils { public static Site2SiteVpnGatewayVO findVpnGatewayById(Long vpnGatewayId) { return _site2SiteVpnGatewayDao.findById(vpnGatewayId); } - - public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { - return _site2SiteCustomerGatewayDao.findById(customerGatewayId); + + public static Site2SiteCustomerGatewayVO findCustomerGatewayById(Long customerGatewayId) { + return _site2SiteCustomerGatewayDao.findById(customerGatewayId); } - + public static List listUsersByAccount(long accountId) { return _userDao.listByAccount(accountId); } @@ -599,9 +769,9 @@ public class ApiDBUtils { public static HypervisorType getVolumeHyperType(long volumeId) { return _volumeDao.getHypervisorType(volumeId); } - + public static HypervisorType getHypervisorTypeFromFormat(ImageFormat format){ - return _storageMgr.getHypervisorTypeFromFormat(format); + return _storageMgr.getHypervisorTypeFromFormat(format); } public static List listTemplateHostBy(long templateId, Long zoneId, boolean readyOnly) { @@ -655,6 +825,14 @@ public class ApiDBUtils { return _vlanDao.listVlansByNetworkId(networkId); } + public static PhysicalNetworkVO findPhysicalNetworkById(long id) { + return _physicalNetworkDao.findById(id); + } + + public static PhysicalNetworkTrafficTypeVO findPhysicalNetworkTrafficTypeById(long id) { + return _physicalNetworkTrafficTypeDao.findById(id); + } + public static NetworkVO findNetworkById(long id) { return _networkDao.findById(id); } @@ -702,13 +880,13 @@ public class ApiDBUtils { float cpuOverprovisioningFactor = NumbersUtil.parseFloat(opFactor, 1); return cpuOverprovisioningFactor; } - + public static boolean isExtractionDisabled(){ - String disableExtractionString = _configDao.getValue(Config.DisableExtraction.toString()); + String disableExtractionString = _configDao.getValue(Config.DisableExtraction.toString()); boolean disableExtraction = (disableExtractionString == null) ? false : Boolean.parseBoolean(disableExtractionString); return disableExtraction; } - + public static SecurityGroup getSecurityGroup(String groupName, long ownerId) { return _securityGroupMgr.getSecurityGroup(groupName, ownerId); } @@ -716,97 +894,93 @@ public class ApiDBUtils { public static ConsoleProxyVO findConsoleProxy(long id) { return _consoleProxyDao.findById(id); } - + public static List findFirewallSourceCidrs(long id){ - return _firewallCidrsDao.getSourceCidrs(id); + return _firewallCidrsDao.getSourceCidrs(id); } - - public static Hashtable listVmDetails(Hashtable vmData){ - return _userVmDao.listVmDetails(vmData); - } - + public static Account getProjectOwner(long projectId) { return _projectMgr.getProjectOwner(projectId); } - + public static Project findProjectByProjectAccountId(long projectAccountId) { return _projectMgr.findByProjectAccountId(projectAccountId); } - + public static Project findProjectByProjectAccountIdIncludingRemoved(long projectAccountId) { return _projectMgr.findByProjectAccountIdIncludingRemoved(projectAccountId); } - + public static Project findProjectById(long projectId) { return _projectMgr.getProject(projectId); } - + public static long getProjectOwnwerId(long projectId) { return _projectMgr.getProjectOwner(projectId).getId(); } - + public static Map getAccountDetails(long accountId) { - Map details = _accountDetailsDao.findDetails(accountId); - return details.isEmpty() ? null : details; + Map details = _accountDetailsDao.findDetails(accountId); + return details.isEmpty() ? null : details; } public static Map> listNetworkOfferingServices(long networkOfferingId) { return _networkMgr.getNetworkOfferingServiceProvidersMap(networkOfferingId); } - + public static List getElementServices(Provider provider) { - return _networkMgr.getElementServices(provider); + return _networkMgr.getElementServices(provider); } - + public static List getProvidersForService(Service service) { return _networkMgr.listSupportedNetworkServiceProviders(service.getName()); - } + } public static boolean canElementEnableIndividualServices(Provider serviceProvider) { return _networkMgr.canElementEnableIndividualServices(serviceProvider); } - + public static Pair getDomainNetworkDetails(long networkId) { - NetworkDomainVO map = _networkDomainDao.getDomainNetworkMapByNetworkId(networkId); - - boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : _networkMgr.getAllowSubdomainAccessGlobal(); - - return new Pair(map.getDomainId(), subdomainAccess); + NetworkDomainVO map = _networkDomainDao.getDomainNetworkMapByNetworkId(networkId); + + boolean subdomainAccess = (map.isSubdomainAccess() != null) ? map.isSubdomainAccess() : _networkMgr.getAllowSubdomainAccessGlobal(); + + return new Pair(map.getDomainId(), subdomainAccess); } - + public static long countFreePublicIps() { - return _ipAddressDao.countFreePublicIPs(); + return _ipAddressDao.countFreePublicIPs(); } - + public static long findDefaultRouterServiceOffering() { ServiceOfferingVO serviceOffering = _serviceOfferingDao.findByName(ServiceOffering.routerDefaultOffUniqueName); return serviceOffering.getId(); } - + public static IpAddress findIpByAssociatedVmId(long vmId) { return _ipAddressDao.findByAssociatedVmId(vmId); } - + public static String getHaTag() { return _haMgr.getHaTag(); } - + public static Map> listVpcOffServices(long vpcOffId) { return _vpcMgr.getVpcOffSvcProvidersMap(vpcOffId); } - + public static List listVpcNetworks(long vpcId) { return _networkMgr.listNetworksByVpc(vpcId); } - + public static boolean canUseForDeploy(Network network) { return _networkMgr.canUseForDeploy(network); } - + public static String getUuid(String resourceId, TaggedResourceType resourceType) { return _taggedResourceService.getUuid(resourceId, resourceType); } - + public static boolean isOfferingForVpc(NetworkOffering offering) { boolean vpcProvider = _configMgr.isOfferingForVpc(offering); return vpcProvider; @@ -815,7 +989,28 @@ public class ApiDBUtils { public static List listByResourceTypeAndId(TaggedResourceType type, long resourceId) { return _taggedResourceService.listByResourceTypeAndId(type, resourceId); } + public static List getAutoScalePolicyConditions(long policyId) + { + List vos = _asPolicyConditionMapDao.listByAll(policyId, null); + ArrayList conditions = new ArrayList(vos.size()); + for (AutoScalePolicyConditionMapVO vo : vos) { + conditions.add(_asConditionDao.findById(vo.getConditionId())); + } + return conditions; + } + + public static void getAutoScaleVmGroupPolicyIds(long vmGroupId, List scaleUpPolicyIds, List scaleDownPolicyIds) + { + List vos = _asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); + for (AutoScaleVmGroupPolicyMapVO vo : vos) { + AutoScalePolicy autoScalePolicy = _asPolicyDao.findById(vo.getPolicyId()); + if(autoScalePolicy.getAction().equals("scaleup")) + scaleUpPolicyIds.add(autoScalePolicy.getId()); + else + scaleDownPolicyIds.add(autoScalePolicy.getId()); + } + } public static String getKeyPairName(String sshPublicKey) { SSHKeyPairVO sshKeyPair = _sshKeyPairDao.findByPublicKey(sshPublicKey); //key might be removed prior to this point @@ -828,4 +1023,358 @@ public class ApiDBUtils { public static UserVmDetailVO findPublicKeyByVmId(long vmId) { return _userVmDetailsDao.findDetail(vmId, "SSH.PublicKey"); } + + public static void getAutoScaleVmGroupPolicies(long vmGroupId, List scaleUpPolicies, List scaleDownPolicies) + { + List vos = _asVmGroupPolicyMapDao.listByVmGroupId(vmGroupId); + for (AutoScaleVmGroupPolicyMapVO vo : vos) { + AutoScalePolicy autoScalePolicy = _asPolicyDao.findById(vo.getPolicyId()); + if(autoScalePolicy.getAction().equals("scaleup")) + scaleUpPolicies.add(autoScalePolicy); + else + scaleDownPolicies.add(autoScalePolicy); + } + } + + public static CounterVO getCounter(long counterId) { + return _counterDao.findById(counterId); + } + + public static ConditionVO findConditionById(long conditionId){ + return _asConditionDao.findById(conditionId); + } + + public static PhysicalNetworkServiceProviderVO findPhysicalNetworkServiceProviderById(long providerId){ + return _physicalNetworkServiceProviderDao.findById(providerId); + } + + public static FirewallRuleVO findFirewallRuleById(long ruleId){ + return _firewallRuleDao.findById(ruleId); + } + + public static StaticRouteVO findStaticRouteById(long routeId){ + return _staticRouteDao.findById(routeId); + } + + public static VpcGatewayVO findVpcGatewayById(long gatewayId){ + return _vpcGatewayDao.findById(gatewayId); + } + + public static AutoScalePolicyVO findAutoScalePolicyById(long policyId){ + return _asPolicyDao.findById(policyId); + } + + public static AutoScaleVmProfileVO findAutoScaleVmProfileById(long profileId){ + return _asVmProfileDao.findById(profileId); + } + + public static AutoScaleVmGroupVO findAutoScaleVmGroupById(long groupId){ + return _asVmGroupDao.findById(groupId); + } + + public static GuestOSCategoryVO findGuestOsCategoryById(long catId){ + return _guestOSCategoryDao.findById(catId); + } + + public static VpcVO findVpcById(long vpcId){ + return _vpcDao.findById(vpcId); + } + + public static SnapshotPolicy findSnapshotPolicyById(long policyId){ + return _snapshotPolicyDao.findById(policyId); + } + + public static VpcOffering findVpcOfferingById(long offeringId){ + return _vpcOfferingDao.findById(offeringId); + } + + + public static AsyncJob findAsyncJobById(long jobId){ + return _asyncJobDao.findById(jobId); + } + + public static String findJobInstanceUuid(AsyncJob job){ + if ( job == null ) + return null; + String jobInstanceId = null; + if (job.getInstanceType() == AsyncJob.Type.Volume) { + VolumeVO volume = ApiDBUtils.findVolumeById(job.getInstanceId()); + if (volume != null) { + jobInstanceId = volume.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Template || job.getInstanceType() == AsyncJob.Type.Iso) { + VMTemplateVO template = ApiDBUtils.findTemplateById(job.getInstanceId()); + if (template != null) { + jobInstanceId = template.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.VirtualMachine || job.getInstanceType() == AsyncJob.Type.ConsoleProxy + || job.getInstanceType() == AsyncJob.Type.SystemVm || job.getInstanceType() == AsyncJob.Type.DomainRouter) { + VMInstanceVO vm = ApiDBUtils.findVMInstanceById(job.getInstanceId()); + if (vm != null) { + jobInstanceId = vm.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Snapshot) { + Snapshot snapshot = ApiDBUtils.findSnapshotById(job.getInstanceId()); + if (snapshot != null) { + jobInstanceId = snapshot.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Host) { + Host host = ApiDBUtils.findHostById(job.getInstanceId()); + if (host != null) { + jobInstanceId = host.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.StoragePool) { + StoragePoolVO spool = ApiDBUtils.findStoragePoolById(job.getInstanceId()); + if (spool != null) { + jobInstanceId = spool.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.IpAddress) { + IPAddressVO ip = ApiDBUtils.findIpAddressById(job.getInstanceId()); + if (ip != null) { + jobInstanceId = ip.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.SecurityGroup) { + SecurityGroup sg = ApiDBUtils.findSecurityGroupById(job.getInstanceId()); + if (sg != null) { + jobInstanceId = sg.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PhysicalNetwork) { + PhysicalNetworkVO pnet = ApiDBUtils.findPhysicalNetworkById(job.getInstanceId()); + if (pnet != null) { + jobInstanceId = pnet.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.TrafficType) { + PhysicalNetworkTrafficTypeVO trafficType = ApiDBUtils.findPhysicalNetworkTrafficTypeById(job.getInstanceId()); + if (trafficType != null) { + jobInstanceId = trafficType.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PhysicalNetworkServiceProvider) { + PhysicalNetworkServiceProvider sp = ApiDBUtils.findPhysicalNetworkServiceProviderById(job.getInstanceId()); + if (sp != null) { + jobInstanceId = sp.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.FirewallRule) { + FirewallRuleVO fw = ApiDBUtils.findFirewallRuleById(job.getInstanceId()); + if (fw != null) { + jobInstanceId = fw.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Account) { + Account acct = ApiDBUtils.findAccountById(job.getInstanceId()); + if (acct != null) { + jobInstanceId = acct.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.User) { + User usr = ApiDBUtils.findUserById(job.getInstanceId()); + if (usr != null) { + jobInstanceId = usr.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.StaticRoute) { + StaticRouteVO route = ApiDBUtils.findStaticRouteById(job.getInstanceId()); + if (route != null) { + jobInstanceId = route.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.PrivateGateway) { + VpcGatewayVO gateway = ApiDBUtils.findVpcGatewayById(job.getInstanceId()); + if (gateway != null) { + jobInstanceId = gateway.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Counter) { + CounterVO counter = ApiDBUtils.getCounter(job.getInstanceId()); + if (counter != null) { + jobInstanceId = counter.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.Condition) { + ConditionVO condition = ApiDBUtils.findConditionById(job.getInstanceId()); + if (condition != null) { + jobInstanceId = condition.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScalePolicy) { + AutoScalePolicyVO policy = ApiDBUtils.findAutoScalePolicyById(job.getInstanceId()); + if (policy != null) { + jobInstanceId = policy.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScaleVmProfile) { + AutoScaleVmProfileVO profile = ApiDBUtils.findAutoScaleVmProfileById(job.getInstanceId()); + if (profile != null) { + jobInstanceId = profile.getUuid(); + } + } else if (job.getInstanceType() == AsyncJob.Type.AutoScaleVmGroup) { + AutoScaleVmGroupVO group = ApiDBUtils.findAutoScaleVmGroupById(job.getInstanceId()); + if (group != null) { + jobInstanceId = group.getUuid(); + } + } else if (job.getInstanceType() != AsyncJob.Type.None) { + // TODO : when we hit here, we need to add instanceType -> UUID + // entity table mapping + assert (false); + } + return jobInstanceId; + } + + /////////////////////////////////////////////////////////////////////// + // Newly Added Utility Methods for List API refactoring // + /////////////////////////////////////////////////////////////////////// + + public static DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO vr, Account caller) { + return _domainRouterJoinDao.newDomainRouterResponse(vr, caller); + } + + public static DomainRouterResponse fillRouterDetails(DomainRouterResponse vrData, DomainRouterJoinVO vr){ + return _domainRouterJoinDao.setDomainRouterResponse(vrData, vr); + } + + public static List newDomainRouterView(VirtualRouter vr){ + return _domainRouterJoinDao.newDomainRouterView(vr); + } + + public static UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller) { + return _userVmJoinDao.newUserVmResponse(objectName, userVm, details, caller); + } + + public static UserVmResponse fillVmDetails(UserVmResponse vmData, UserVmJoinVO vm){ + return _userVmJoinDao.setUserVmResponse(vmData, vm); + } + + public static List newUserVmView(UserVm... userVms){ + return _userVmJoinDao.newUserVmView(userVms); + } + + public static SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller) { + return _securityGroupJoinDao.newSecurityGroupResponse(vsg, caller); + } + + public static SecurityGroupResponse fillSecurityGroupDetails(SecurityGroupResponse vsgData, SecurityGroupJoinVO sg){ + return _securityGroupJoinDao.setSecurityGroupResponse(vsgData, sg); + } + + public static List newSecurityGroupView(SecurityGroup sg){ + return _securityGroupJoinDao.newSecurityGroupView(sg); + } + + public static List findSecurityGroupViewById(Long sgId){ + return _securityGroupJoinDao.searchByIds(sgId); + } + + public static ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO vsg, boolean keyValueOnly) { + return _tagJoinDao.newResourceTagResponse(vsg, keyValueOnly); + } + + public static ResourceTagJoinVO newResourceTagView(ResourceTag sg){ + return _tagJoinDao.newResourceTagView(sg); + } + + public static ResourceTagJoinVO findResourceTagViewById(Long tagId){ + List tags = _tagJoinDao.searchByIds(tagId); + if ( tags != null && tags.size() > 0 ){ + return tags.get(0); + } + else{ + return null; + } + } + + public static EventResponse newEventResponse(EventJoinVO ve) { + return _eventJoinDao.newEventResponse(ve); + } + + public static EventJoinVO newEventView(Event e){ + return _eventJoinDao.newEventView(e); + } + + public static InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO ve) { + return _vmGroupJoinDao.newInstanceGroupResponse(ve); + } + + public static InstanceGroupJoinVO newInstanceGroupView(InstanceGroup e){ + return _vmGroupJoinDao.newInstanceGroupView(e); + } + + public static UserResponse newUserResponse(UserAccountJoinVO usr) { + return _userAccountJoinDao.newUserResponse(usr); + } + + public static UserAccountJoinVO newUserView(User usr){ + return _userAccountJoinDao.newUserView(usr); + } + + public static UserAccountJoinVO newUserView(UserAccount usr){ + return _userAccountJoinDao.newUserView(usr); + } + + public static ProjectResponse newProjectResponse(ProjectJoinVO proj) { + return _projectJoinDao.newProjectResponse(proj); + } + + public static ProjectResponse fillProjectDetails(ProjectResponse rsp, ProjectJoinVO proj){ + return _projectJoinDao.setProjectResponse(rsp,proj); + } + + public static List newProjectView(Project proj){ + return _projectJoinDao.newProjectView(proj); + } + + public static List findUserViewByAccountId(Long accountId){ + return _userAccountJoinDao.searchByAccountId(accountId); + } + + public static ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj) { + return _projectAccountJoinDao.newProjectAccountResponse(proj); + } + + public static ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj) { + return _projectAccountJoinDao.newProjectAccountView(proj); + } + + public static ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO proj) { + return _projectInvitationJoinDao.newProjectInvitationResponse(proj); + } + + public static ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj) { + return _projectInvitationJoinDao.newProjectInvitationView(proj); + } + + public static HostResponse newHostResponse(HostJoinVO vr, EnumSet details) { + return _hostJoinDao.newHostResponse(vr, details); + } + + public static HostResponse fillHostDetails(HostResponse vrData, HostJoinVO vr){ + return _hostJoinDao.setHostResponse(vrData, vr); + } + + public static List newHostView(Host vr){ + return _hostJoinDao.newHostView(vr); + } + + public static VolumeResponse newVolumeResponse(VolumeJoinVO vr) { + return _volJoinDao.newVolumeResponse(vr); + } + + + public static VolumeResponse fillVolumeDetails(VolumeResponse vrData, VolumeJoinVO vr){ + return _volJoinDao.setVolumeResponse(vrData, vr); + } + + public static List newVolumeView(Volume vr){ + return _volJoinDao.newVolumeView(vr); + } + + public static AccountResponse newAccountResponse(AccountJoinVO ve) { + return _accountJoinDao.newAccountResponse(ve); + } + + public static AccountJoinVO newAccountView(Account e){ + return _accountJoinDao.newAccountView(e); + } + + public static AccountJoinVO findAccountViewById(Long accountId) { + return _accountJoinDao.findByIdIncludingRemoved(accountId); + } + + public static AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO ve) { + return _jobJoinDao.newAsyncJobResponse(ve); + } + + public static AsyncJobJoinVO newAsyncJobView(AsyncJob e){ + return _jobJoinDao.newAsyncJobView(e); + } } diff --git a/server/src/com/cloud/api/ApiDispatcher.java b/server/src/com/cloud/api/ApiDispatcher.java index 3c1b0b0631f..885cf87307b 100755 --- a/server/src/com/cloud/api/ApiDispatcher.java +++ b/server/src/com/cloud/api/ApiDispatcher.java @@ -16,68 +16,99 @@ // 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; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; -import javax.inject.Inject; - +import com.cloud.dao.EntityManager; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.InfrastructureEntity; +import org.apache.cloudstack.acl.Role; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.BaseCmd.CommandType; -import com.cloud.api.commands.ListEventsCmd; +import org.apache.cloudstack.api.BaseCmd.CommandType; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; import com.cloud.async.AsyncCommandQueued; import com.cloud.async.AsyncJobManager; +import com.cloud.configuration.Config; +import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.exception.AccountLimitException; 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.utils.IdentityProxy; +import com.cloud.network.dao.NetworkDao; import com.cloud.server.ManagementServer; +import com.cloud.storage.dao.VMTemplateDao; import com.cloud.user.Account; +import com.cloud.user.AccountManager; import com.cloud.user.UserContext; import com.cloud.utils.DateUtil; +import com.cloud.utils.NumbersUtil; import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; import com.cloud.utils.component.PluggableService; +import com.cloud.utils.db.GenericDao; import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.uuididentity.dao.IdentityDao; -/** - * A class that dispatches API commands to the appropriate manager for execution. - */ -@Component +// ApiDispatcher: A class that dispatches API commands to the appropriate manager for execution. public class ApiDispatcher { private static final Logger s_logger = Logger.getLogger(ApiDispatcher.class.getName()); - @Inject AsyncJobManager _asyncMgr; - @Inject IdentityDao _identityDao; + ComponentLocator _locator; + Long _createSnapshotQueueSizeLimit; + @Inject private AsyncJobManager _asyncMgr = null; + @Inject private AccountManager _accountMgr = null; + @Inject EntityManager _entityMgr = null; + @Inject IdentityDao _identityDao = null; + Map> _daoNameMap = new HashMap>(); // singleton class - private static ApiDispatcher s_instance; + private static ApiDispatcher s_instance = ApiDispatcher.getInstance(); public static ApiDispatcher getInstance() { + if (s_instance == null) { + s_instance = ComponentLocator.inject(ApiDispatcher.class); + } return s_instance; } - public ApiDispatcher() { - s_instance = this; + protected ApiDispatcher() { + super(); + _locator = ComponentLocator.getLocator(ManagementServer.Name); + ConfigurationDao configDao = _locator.getDao(ConfigurationDao.class); + Map configs = configDao.getConfiguration(); + String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key()); + if (strSnapshotLimit != null) { + Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L); + if (snapshotLimit <= 0) { + s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString() + + " is less or equal 0; defaulting to unlimited"); + } else { + _createSnapshotQueueSizeLimit = snapshotLimit; + } + } + _daoNameMap.put("com.cloud.network.Network", NetworkDao.class); + _daoNameMap.put("com.cloud.template.VirtualMachineTemplate", VMTemplateDao.class); } public void dispatchCreateCmd(BaseAsyncCreateCmd cmd, Map params) { - - setupParameters(cmd, params); - plugService(cmd); + processParameters(cmd, params); try { UserContext ctx = UserContext.current(); @@ -118,10 +149,54 @@ public class ApiDispatcher { } } + private void checkACLOnCommand(BaseCmd cmd) { + // TODO Auto-generated method stub + //need to write an commandACLChecker adapter framework to check ACL on commands - default one will use the static roles by referring to commands.properties. + //one can write another commandACLChecker to check access via custom roles. + } + + private List determineRole(Account caller) { + // TODO Auto-generated method stub + List effectiveRoles = new ArrayList(); + return effectiveRoles; + + } + + private void doAccessChecks(BaseCmd cmd, List entitiesToAccess) { + //owner + Account caller = UserContext.current().getCaller(); + Account owner = _accountMgr.getActiveAccountById(cmd.getEntityOwnerId()); + + // REMOVE ME: + // List callerRoles = determineRole(caller); + // List ownerRoles = determineRole(owner); + // check permission to call this command for the caller + // this needs checking of static roles of the caller + // Role based acl is done in ApiServer before api gets to ApiDispatcher + // checkACLOnCommand(cmd); + + if(cmd instanceof BaseAsyncCreateCmd) { + //check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); + } + + if(!entitiesToAccess.isEmpty()){ + //check that caller can access the owner account. + _accountMgr.checkAccess(caller, null, true, owner); + for(Object entity : entitiesToAccess) { + if (entity instanceof ControlledEntity) { + _accountMgr.checkAccess(caller, null, true, (ControlledEntity) entity); + } + else if (entity instanceof InfrastructureEntity) { + //do something here:D + } + } + } + } + public void dispatch(BaseCmd cmd, Map params) { - setupParameters(cmd, params); - ApiDispatcher.plugService(cmd); try { + processParameters(cmd, params); UserContext ctx = UserContext.current(); ctx.setAccountId(cmd.getEntityOwnerId()); if (cmd instanceof BaseAsyncCmd) { @@ -132,7 +207,19 @@ public class ApiDispatcher { // Synchronise job on the object if needed if (asyncCmd.getJob() != null && asyncCmd.getSyncObjId() != null && asyncCmd.getSyncObjType() != null) { - _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), asyncCmd.getSyncObjId().longValue()); + Long queueSizeLimit = null; + if (asyncCmd.getSyncObjType() != null && asyncCmd.getSyncObjType().equalsIgnoreCase(BaseAsyncCmd.snapshotHostSyncObject)) { + queueSizeLimit = _createSnapshotQueueSizeLimit; + } else { + queueSizeLimit = 1L; + } + + if (queueSizeLimit != null) { + _asyncMgr.syncAsyncJobExecution(asyncCmd.getJob(), asyncCmd.getSyncObjType(), + asyncCmd.getSyncObjId().longValue(), queueSizeLimit); + } else { + s_logger.trace("The queue size is unlimited, skipping the synchronizing"); + } } } @@ -146,13 +233,12 @@ public class ApiDispatcher { InvalidParameterValueException ref = (InvalidParameterValueException) t; ServerApiException ex = new ServerApiException(BaseCmd.PARAM_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + " db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + " uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -166,13 +252,12 @@ public class ApiDispatcher { PermissionDeniedException ref = (PermissionDeniedException)t; ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info("PermissionDenied: " + t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info("PermissionDenied: " + t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info("PermissionDenied: " + t.getMessage()); @@ -184,13 +269,12 @@ public class ApiDispatcher { AccountLimitException ref = (AccountLimitException)t; ServerApiException ex = new ServerApiException(BaseCmd.ACCOUNT_RESOURCE_LIMIT_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -202,13 +286,12 @@ public class ApiDispatcher { InsufficientCapacityException ref = (InsufficientCapacityException)t; ServerApiException ex = new ServerApiException(BaseCmd.INSUFFICIENT_CAPACITY_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.info(t.getMessage() + "db_id: " + id.getValue()); + ex.addProxyObject(idList.get(i)); + s_logger.info(t.getMessage() + "uuid: " + idList.get(i)); } } else { s_logger.info(t.getMessage()); @@ -220,13 +303,13 @@ public class ApiDispatcher { ResourceAllocationException ref = (ResourceAllocationException)t; ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_ALLOCATION_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.warn("Exception: " + t.getMessage() + "db_id: " + id.getValue()); + String id = idList.get(i); + ex.addProxyObject(id); + s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); } } else { s_logger.warn("Exception: ", t); @@ -238,13 +321,13 @@ public class ApiDispatcher { ResourceUnavailableException ref = (ResourceUnavailableException)t; ServerApiException ex = new ServerApiException(BaseCmd.RESOURCE_UNAVAILABLE_ERROR, t.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - ex.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); - s_logger.warn("Exception: " + t.getMessage() + "db_id: " + id.getValue()); + String id = idList.get(i); + ex.addProxyObject(id); + s_logger.warn("Exception: " + t.getMessage() + "uuid: " + id); } } else { s_logger.warn("Exception: ", t); @@ -271,7 +354,9 @@ public class ApiDispatcher { } } - public static void setupParameters(BaseCmd cmd, Map params) { + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static void processParameters(BaseCmd cmd, Map params) { + List entitiesToAccess = new ArrayList(); Map unpackedParams = cmd.unpackParams(params); if (cmd instanceof BaseListCmd) { @@ -290,6 +375,7 @@ public class ApiDispatcher { } } + // Process all the fields of the cmd object using reflection to recursively process super class Field[] fields = cmd.getClass().getDeclaredFields(); Class superClass = cmd.getClass().getSuperclass(); while (BaseCmd.class.isAssignableFrom(superClass)) { @@ -304,13 +390,18 @@ public class ApiDispatcher { } for (Field field : fields) { + PlugService plugServiceAnnotation = field.getAnnotation(PlugService.class); + if(plugServiceAnnotation != null){ + plugService(field, cmd); + } + Parameter parameterAnnotation = field.getAnnotation(Parameter.class); if ((parameterAnnotation == null) || !parameterAnnotation.expose()) { continue; } - IdentityMapper identityMapper = field.getAnnotation(IdentityMapper.class); - + //TODO: Annotate @Validate on API Cmd classes, FIXME how to process Validate + Validate validateAnnotation = field.getAnnotation(Validate.class); Object paramObj = unpackedParams.get(parameterAnnotation.name()); if (paramObj == null) { if (parameterAnnotation.required()) { @@ -322,7 +413,7 @@ public class ApiDispatcher { // marshall the parameter into the correct type and set the field value try { - setFieldValue(field, cmd, paramObj, parameterAnnotation, identityMapper); + setFieldValue(field, cmd, paramObj, parameterAnnotation); } catch (IllegalArgumentException argEx) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to execute API command " + cmd.getCommandName() + " due to invalid value " + paramObj + " for parameter " + parameterAnnotation.name()); @@ -340,16 +431,164 @@ public class ApiDispatcher { throw new ServerApiException(BaseCmd.PARAM_ERROR, "Unable to execute API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8) + " due to invalid value. " + invEx.getMessage()); } catch (CloudRuntimeException cloudEx) { // FIXME: Better error message? This only happens if the API command is not executable, which typically -// means + //means // there was // and IllegalAccessException setting one of the parameters. throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error executing API command " + cmd.getCommandName().substring(0, cmd.getCommandName().length() - 8)); } + + //check access on the resource this field points to + try { + ACL checkAccess = field.getAnnotation(ACL.class); + CommandType fieldType = parameterAnnotation.type(); + + if (checkAccess != null) { + // Verify that caller can perform actions in behalf of vm owner + //acumulate all Controlled Entities together. + + //parse the array of resource types and in case of map check access on key or value or both as specified in @acl + //implement external dao for classes that need findByName + //for maps, specify access to be checkd on key or value. + + // find the controlled entity DBid by uuid + if (parameterAnnotation.entityType() != null) { + Class[] entityList = parameterAnnotation.entityType()[0].getAnnotation(EntityReference.class).value(); + + for (Class entity : entityList) { + // Check if the parameter type is a single + // Id or list of id's/name's + switch (fieldType) { + case LIST: + CommandType listType = parameterAnnotation.collectionType(); + switch (listType) { + case LONG: + case UUID: + List listParam = new ArrayList(); + listParam = (List) field.get(cmd); + for (Long entityId : listParam) { + Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd)); + entitiesToAccess.add(entityObj); + } + break; + /* + * case STRING: List listParam = + * new ArrayList(); listParam = + * (List)field.get(cmd); for(String + * entityName: listParam){ + * ControlledEntity entityObj = + * (ControlledEntity + * )daoClassInstance(entityId); + * entitiesToAccess.add(entityObj); } + * break; + */ + default: + break; } + break; + case LONG: + case UUID: + Object entityObj = s_instance._entityMgr.findById(entity, (Long) field.get(cmd)); + entitiesToAccess.add(entityObj); + break; + default: + break; + } + + if (ControlledEntity.class.isAssignableFrom(entity)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("ControlledEntity name is:" + entity.getName()); + } + } + + if (InfrastructureEntity.class.isAssignableFrom(entity)) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("InfrastructureEntity name is:" + entity.getName()); + } + } + } + + } + + } + + } catch (IllegalArgumentException e) { + s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } catch (IllegalAccessException e) { + s_logger.error("Error initializing command " + cmd.getCommandName() + ", field " + field.getName() + " is not accessible."); + throw new CloudRuntimeException("Internal error initializing parameters for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); + } + + } + + //check access on the entities. + s_instance.doAccessChecks(cmd, entitiesToAccess); + + } + + private static Long translateUuidToInternalId(String uuid, Parameter annotation) + { + if (uuid.equals("-1")) { + // FIXME: This is to handle a lot of hardcoded special cases where -1 is sent + // APITODO: Find and get rid of all hardcoded params in API Cmds and service layer + return -1L; + } + Long internalId = null; + // If annotation's empty, the cmd existed before 3.x try conversion to long + // FIXME: Fails if someone adds since field for any pre 3.x apis + boolean isPre3x = annotation.since().isEmpty(); + // Match against Java's UUID regex to check if input is uuid string + boolean isUuid = uuid.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"); + // Enforce that it's uuid for newly added apis from version 3.x + if (!isPre3x && !isUuid) + return null; + // Allow both uuid and internal id for pre3x apis + if (isPre3x && !isUuid) { + try { + internalId = Long.parseLong(uuid); + } catch(NumberFormatException e) { + // In case regex failed, and it's still uuid string + internalId = null; + } + if (internalId != null) + return internalId; + } + // There may be multiple entities defined on the @EntityReference of a Response.class + // UUID CommandType would expect only one entityType, so use the first entityType + Class[] entities = annotation.entityType()[0].getAnnotation(EntityReference.class).value(); + // Go through each entity which is an interface to a VO class and get a VO object + // Try to getId() for the object using reflection, break on first non-null value + for (Class entity: entities) { + // findByUuid returns one VO object using uuid, use reflect to get the Id + Object objVO = s_instance._entityMgr.findByUuid(entity, uuid); + if (objVO == null) { + continue; + } + // Invoke the getId method, get the internal long ID + // If that fails hide exceptions as the uuid may not exist + try { + internalId = (Long) ((InternalIdentity)objVO).getId(); + } catch (IllegalArgumentException e) { + } catch (NullPointerException e) { + } + // Return on first non-null Id for the uuid entity + if (internalId != null) + break; + } + if (internalId == null) { + if (s_logger.isDebugEnabled()) { + s_logger.debug("Object entity with uuid=" + uuid + " does not exist in the database."); + } + if (annotation.required()) { + throw new InvalidParameterValueException("Invalid parameter with uuid=" + uuid + + ". Entity not found, or an annotation bug."); + } + } + return internalId; } @SuppressWarnings({ "unchecked", "rawtypes" }) - private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation, IdentityMapper identityMapper) throws IllegalArgumentException, ParseException { + private static void setFieldValue(Field field, BaseCmd cmdObj, Object paramObj, Parameter annotation) throws IllegalArgumentException, ParseException { try { field.setAccessible(true); CommandType fieldType = annotation.type(); @@ -358,9 +597,9 @@ public class ApiDispatcher { field.set(cmdObj, Boolean.valueOf(paramObj.toString())); break; case DATE: - // This piece of code is for maintaining backward compatibility and support both the date formats(Bug -// 9724) - // Do the date massaging for ListEventsCmd only + // This piece of code is for maintaining backward compatibility + // and support both the date formats(Bug 9724) + // Do the date messaging for ListEventsCmd only if (cmdObj instanceof ListEventsCmd) { boolean isObjInNewDateFormat = isObjInNewDateFormat(paramObj.toString()); if (isObjInNewDateFormat) { @@ -373,9 +612,9 @@ public class ApiDispatcher { synchronized (format) { Date date = format.parse(paramObj.toString()); if (field.getName().equals("startDate")) { - date = massageDate(date, 0, 0, 0); + date = messageDate(date, 0, 0, 0); } else if (field.getName().equals("endDate")) { - date = massageDate(date, 23, 59, 59); + date = messageDate(date, 23, 59, 59); } field.set(cmdObj, date); } @@ -389,10 +628,20 @@ public class ApiDispatcher { } break; case FLOAT: + // 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: + // 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(); @@ -404,14 +653,14 @@ public class ApiDispatcher { case INTEGER: listParam.add(Integer.valueOf(token)); break; + case UUID: + if (token.isEmpty()) + break; + Long internalId = translateUuidToInternalId(token, annotation); + listParam.add(internalId); + break; case LONG: { - Long val = null; - if (identityMapper != null) - val = s_instance._identityDao.getIdentityId(identityMapper, token); - else - val = Long.valueOf(token); - - listParam.add(val); + listParam.add(Long.valueOf(token)); } break; case SHORT: @@ -423,10 +672,13 @@ public class ApiDispatcher { } field.set(cmdObj, listParam); break; + case UUID: + if (paramObj.toString().isEmpty()) + break; + Long internalId = translateUuidToInternalId(paramObj.toString(), annotation); + field.set(cmdObj, internalId); + break; case LONG: - if (identityMapper != null) - field.set(cmdObj, s_instance._identityDao.getIdentityId(identityMapper, paramObj.toString())); - else field.set(cmdObj, Long.valueOf(paramObj.toString())); break; case SHORT: @@ -458,7 +710,7 @@ public class ApiDispatcher { return matcher.matches(); } - private static Date massageDate(Date date, int hourOfDay, int minute, int second) { + private static Date messageDate(Date date, int hourOfDay, int minute, int second) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, hourOfDay); @@ -467,20 +719,9 @@ public class ApiDispatcher { return cal.getTime(); } - public static void plugService(BaseCmd cmd) { - - if (!ApiServer.isPluggableServiceCommand(cmd.getClass().getName())) { - return; - } - Class clazz = cmd.getClass(); + public static void plugService(Field field, BaseCmd cmd) { ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); - do { - Field[] fields = clazz.getDeclaredFields(); - for (Field field : fields) { - PlugService plugService = field.getAnnotation(PlugService.class); - if (plugService == null) { - continue; - } + Class fc = field.getType(); Object instance = null; if (PluggableService.class.isAssignableFrom(fc)) { @@ -488,7 +729,7 @@ public class ApiDispatcher { } if (instance == null) { - throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + clazz.getSimpleName()); + throw new CloudRuntimeException("Unable to plug service " + fc.getSimpleName() + " in command " + cmd.getClass().getSimpleName()); } try { @@ -502,10 +743,6 @@ public class ApiDispatcher { throw new CloudRuntimeException("Internal error at plugService for command " + cmd.getCommandName() + " [field " + field.getName() + " is not accessible]"); } } - clazz = clazz.getSuperclass(); - } while (clazz != Object.class && clazz != null); - } - public static Long getIdentiyId(String tableName, String token) { return s_instance._identityDao.getIdentityId(tableName, token); diff --git a/server/src/com/cloud/api/ApiGsonHelper.java b/server/src/com/cloud/api/ApiGsonHelper.java index 503ff13db3a..6e64f7124e0 100644 --- a/server/src/com/cloud/api/ApiGsonHelper.java +++ b/server/src/com/cloud/api/ApiGsonHelper.java @@ -18,6 +18,8 @@ package com.cloud.api; import com.google.gson.GsonBuilder; import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ResponseObject; + import java.util.Map; public class ApiGsonHelper { diff --git a/server/src/com/cloud/api/ApiResponseGsonHelper.java b/server/src/com/cloud/api/ApiResponseGsonHelper.java index 0b578793344..c71193e8908 100644 --- a/server/src/com/cloud/api/ApiResponseGsonHelper.java +++ b/server/src/com/cloud/api/ApiResponseGsonHelper.java @@ -18,6 +18,7 @@ package com.cloud.api; import com.google.gson.GsonBuilder; import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ResponseObject; /** * The ApiResonseGsonHelper is different from ApiGsonHelper - it registeres one more adapter for String type required for api response encoding diff --git a/server/src/com/cloud/api/ApiResponseHelper.java b/server/src/com/cloud/api/ApiResponseHelper.java index 2b6a31b4cca..d5cbb71dd9a 100755 --- a/server/src/com/cloud/api/ApiResponseHelper.java +++ b/server/src/com/cloud/api/ApiResponseHelper.java @@ -5,7 +5,7 @@ // 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, @@ -16,103 +16,127 @@ // 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; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; -import java.util.Hashtable; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ResponseGenerator; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.ApiConstants.HostDetails; -import com.cloud.api.ApiConstants.VMDetails; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.AccountResponse; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.response.AccountResponse; + +import com.cloud.api.query.ViewResponseHelper; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.ControlledViewEntity; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.CapabilityResponse; -import com.cloud.api.response.CapacityResponse; -import com.cloud.api.response.ClusterResponse; -import com.cloud.api.response.ConfigurationResponse; -import com.cloud.api.response.ControlledEntityResponse; -import com.cloud.api.response.CreateCmdResponse; -import com.cloud.api.response.DiskOfferingResponse; -import com.cloud.api.response.DomainResponse; -import com.cloud.api.response.DomainRouterResponse; -import com.cloud.api.response.EventResponse; -import com.cloud.api.response.ExtractResponse; -import com.cloud.api.response.FirewallResponse; -import com.cloud.api.response.FirewallRuleResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.HypervisorCapabilitiesResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.InstanceGroupResponse; -import com.cloud.api.response.IpForwardingRuleResponse; -import com.cloud.api.response.LBStickinessPolicyResponse; -import com.cloud.api.response.LBStickinessResponse; -import com.cloud.api.response.LDAPConfigResponse; -import com.cloud.api.response.ListResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.NetworkACLResponse; -import com.cloud.api.response.NetworkOfferingResponse; -import com.cloud.api.response.NetworkResponse; -import com.cloud.api.response.NicResponse; -import com.cloud.api.response.PhysicalNetworkResponse; -import com.cloud.api.response.PodResponse; -import com.cloud.api.response.PrivateGatewayResponse; -import com.cloud.api.response.ProjectAccountResponse; -import com.cloud.api.response.ProjectInvitationResponse; -import com.cloud.api.response.ProjectResponse; -import com.cloud.api.response.ProviderResponse; -import com.cloud.api.response.RemoteAccessVpnResponse; -import com.cloud.api.response.ResourceCountResponse; -import com.cloud.api.response.ResourceLimitResponse; -import com.cloud.api.response.ResourceTagResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SecurityGroupResultObject; -import com.cloud.api.response.SecurityGroupRuleResponse; -import com.cloud.api.response.SecurityGroupRuleResultObject; -import com.cloud.api.response.ServiceOfferingResponse; -import com.cloud.api.response.ServiceResponse; -import com.cloud.api.response.Site2SiteCustomerGatewayResponse; -import com.cloud.api.response.Site2SiteVpnConnectionResponse; -import com.cloud.api.response.Site2SiteVpnGatewayResponse; -import com.cloud.api.response.SnapshotPolicyResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StaticRouteResponse; -import com.cloud.api.response.StorageNetworkIpRangeResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.SwiftResponse; -import com.cloud.api.response.SystemVmInstanceResponse; -import com.cloud.api.response.SystemVmResponse; -import com.cloud.api.response.TemplatePermissionsResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.TrafficTypeResponse; -import com.cloud.api.response.UserResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VirtualRouterProviderResponse; -import com.cloud.api.response.VlanIpRangeResponse; -import com.cloud.api.response.VolumeResponse; -import com.cloud.api.response.VpcOfferingResponse; -import com.cloud.api.response.VpcResponse; -import com.cloud.api.response.VpnUsersResponse; -import com.cloud.api.response.ZoneResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.AutoScalePolicyResponse; +import org.apache.cloudstack.api.response.AutoScaleVmGroupResponse; +import org.apache.cloudstack.api.response.AutoScaleVmProfileResponse; +import org.apache.cloudstack.api.response.CapabilityResponse; +import org.apache.cloudstack.api.response.CapacityResponse; +import org.apache.cloudstack.api.response.ClusterResponse; +import org.apache.cloudstack.api.response.ConditionResponse; +import org.apache.cloudstack.api.response.ConfigurationResponse; +import org.apache.cloudstack.api.response.ControlledEntityResponse; +import org.apache.cloudstack.api.response.CounterResponse; +import org.apache.cloudstack.api.response.CreateCmdResponse; +import org.apache.cloudstack.api.response.DiskOfferingResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.ExtractResponse; +import org.apache.cloudstack.api.response.FirewallResponse; +import org.apache.cloudstack.api.response.FirewallRuleResponse; +import org.apache.cloudstack.api.response.GuestOSResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.HypervisorCapabilitiesResponse; +import org.apache.cloudstack.api.response.ControlledViewEntityResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.IpForwardingRuleResponse; +import org.apache.cloudstack.api.response.LBStickinessPolicyResponse; +import org.apache.cloudstack.api.response.LBStickinessResponse; +import org.apache.cloudstack.api.response.LDAPConfigResponse; +import org.apache.cloudstack.api.response.LoadBalancerResponse; +import org.apache.cloudstack.api.response.NetworkACLResponse; +import org.apache.cloudstack.api.response.NetworkOfferingResponse; +import org.apache.cloudstack.api.response.NetworkResponse; +import org.apache.cloudstack.api.response.PhysicalNetworkResponse; +import org.apache.cloudstack.api.response.PodResponse; +import org.apache.cloudstack.api.response.PrivateGatewayResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ProviderResponse; +import org.apache.cloudstack.api.response.RemoteAccessVpnResponse; +import org.apache.cloudstack.api.response.ResourceCountResponse; +import org.apache.cloudstack.api.response.ResourceLimitResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.ServiceOfferingResponse; +import org.apache.cloudstack.api.response.ServiceResponse; +import org.apache.cloudstack.api.response.Site2SiteCustomerGatewayResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnConnectionResponse; +import org.apache.cloudstack.api.response.Site2SiteVpnGatewayResponse; +import org.apache.cloudstack.api.response.SnapshotPolicyResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.SnapshotScheduleResponse; +import org.apache.cloudstack.api.response.StaticRouteResponse; +import org.apache.cloudstack.api.response.StorageNetworkIpRangeResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.SwiftResponse; +import org.apache.cloudstack.api.response.SystemVmInstanceResponse; +import org.apache.cloudstack.api.response.SystemVmResponse; +import org.apache.cloudstack.api.response.TemplatePermissionsResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.TrafficTypeResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VirtualRouterProviderResponse; +import org.apache.cloudstack.api.response.VlanIpRangeResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +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.apache.cloudstack.api.response.S3Response; import com.cloud.async.AsyncJob; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Configuration; import com.cloud.configuration.Resource.ResourceOwnerType; -import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.ResourceCount; import com.cloud.configuration.ResourceLimit; import com.cloud.dc.ClusterVO; @@ -126,9 +150,7 @@ import com.cloud.dc.Vlan.VlanType; import com.cloud.dc.VlanVO; import com.cloud.domain.Domain; import com.cloud.event.Event; -import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; -import com.cloud.host.HostStats; import com.cloud.host.HostVO; import com.cloud.hypervisor.HypervisorCapabilities; import com.cloud.network.IPAddressVO; @@ -138,27 +160,33 @@ import com.cloud.network.Network.Capability; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.NetworkProfile; +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.PhysicalNetworkTrafficType; +import com.cloud.network.PhysicalNetworkVO; import com.cloud.network.RemoteAccessVpn; import com.cloud.network.Site2SiteCustomerGateway; -import com.cloud.network.Site2SiteCustomerGatewayVO; import com.cloud.network.Site2SiteVpnConnection; import com.cloud.network.Site2SiteVpnGateway; -import com.cloud.network.Site2SiteVpnGatewayVO; import com.cloud.network.VirtualRouterProvider; import com.cloud.network.VpnUser; +import com.cloud.network.as.AutoScalePolicy; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.AutoScaleVmProfileVO; +import com.cloud.network.as.Condition; +import com.cloud.network.as.ConditionVO; +import com.cloud.network.as.Counter; import com.cloud.network.router.VirtualRouter; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.FirewallRuleVO; import com.cloud.network.rules.LoadBalancer; import com.cloud.network.rules.PortForwardingRule; import com.cloud.network.rules.StaticNatRule; import com.cloud.network.rules.StickinessPolicy; import com.cloud.network.security.SecurityGroup; -import com.cloud.network.security.SecurityGroupRules; -import com.cloud.network.security.SecurityGroupVO; import com.cloud.network.security.SecurityRule; import com.cloud.network.security.SecurityRule.SecurityRuleType; import com.cloud.network.vpc.PrivateGateway; @@ -175,11 +203,10 @@ import com.cloud.projects.ProjectInvitation; import com.cloud.server.Criteria; import com.cloud.server.ResourceTag; 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; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Storage.TemplateType; @@ -189,37 +216,28 @@ 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; import com.cloud.storage.Volume; import com.cloud.storage.VolumeVO; import com.cloud.storage.snapshot.SnapshotPolicy; +import com.cloud.storage.snapshot.SnapshotSchedule; import com.cloud.template.VirtualMachineTemplate; -import com.cloud.test.PodZoneConfig; import com.cloud.user.Account; import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; -import com.cloud.user.UserStatisticsVO; -import com.cloud.user.UserVO; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.net.NetUtils; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.InstanceGroup; -import com.cloud.vm.InstanceGroupVO; import com.cloud.vm.NicProfile; -import com.cloud.vm.UserVmDetailVO; -import com.cloud.vm.VMInstanceVO; import com.cloud.vm.VirtualMachine; -import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachine.Type; -import com.cloud.vm.VmStats; -import com.cloud.vm.dao.UserVmData; -import com.cloud.vm.dao.UserVmData.NicData; -import com.cloud.vm.dao.UserVmData.SecurityGroupData; public class ApiResponseHelper implements ResponseGenerator { @@ -228,215 +246,43 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public UserResponse createUserResponse(User user) { - UserResponse userResponse = new UserResponse(); - Account account = ApiDBUtils.findAccountById(user.getAccountId()); - userResponse.setAccountName(account.getAccountName()); - userResponse.setAccountType(account.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(account.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState().toString()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setObjectName("user"); - - return userResponse; + UserAccountJoinVO vUser = ApiDBUtils.newUserView(user); + return ApiDBUtils.newUserResponse(vUser); } + + // this method is used for response generation via createAccount (which creates an account + user) @Override public AccountResponse createUserAccountResponse(UserAccount user) { - return createAccountResponse(ApiDBUtils.findAccountById(user.getAccountId())); + return ApiDBUtils.newAccountResponse(ApiDBUtils.findAccountViewById(user.getAccountId())); } @Override public AccountResponse createAccountResponse(Account account) { - boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); - AccountResponse accountResponse = new AccountResponse(); - accountResponse.setId(account.getId()); - accountResponse.setName(account.getAccountName()); - accountResponse.setAccountType(account.getType()); - accountResponse.setDomainId(account.getDomainId()); - accountResponse.setDomainName(ApiDBUtils.findDomainById(account.getDomainId()).getName()); - accountResponse.setState(account.getState().toString()); - accountResponse.setNetworkDomain(account.getNetworkDomain()); - accountResponse.setDefaultZone(account.getDefaultZoneId()); - - // get network stat - List stats = ApiDBUtils.listUserStatsBy(account.getId()); - if (stats == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); - } - - Long bytesSent = 0L; - Long bytesReceived = 0L; - for (UserStatisticsVO stat : stats) { - Long rx = stat.getNetBytesReceived() + stat.getCurrentBytesReceived(); - Long tx = stat.getNetBytesSent() + stat.getCurrentBytesSent(); - bytesReceived = bytesReceived + Long.valueOf(rx); - bytesSent = bytesSent + Long.valueOf(tx); - } - accountResponse.setBytesReceived(bytesReceived); - accountResponse.setBytesSent(bytesSent); - - // Get resource limits and counts - - Long vmLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.user_vm, account.getId()); - String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); - Long vmTotal = ApiDBUtils.getResourceCount(ResourceType.user_vm, account.getId()); - String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); - accountResponse.setVmLimit(vmLimitDisplay); - accountResponse.setVmTotal(vmTotal); - accountResponse.setVmAvailable(vmAvail); - - Long ipLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.public_ip, account.getId()); - String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); - Long ipTotal = ApiDBUtils.getResourceCount(ResourceType.public_ip, account.getId()); - - Long ips = ipLimit - ipTotal; - // check how many free ips are left, and if it's less than max allowed number of ips from account - use this - // value - Long ipsLeft = ApiDBUtils.countFreePublicIps(); - boolean unlimited = true; - if (ips.longValue() > ipsLeft.longValue()) { - ips = ipsLeft; - unlimited = false; - } - - String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); - - accountResponse.setIpLimit(ipLimitDisplay); - accountResponse.setIpTotal(ipTotal); - accountResponse.setIpAvailable(ipAvail); - - Long volumeLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.volume, account.getId()); - String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); - Long volumeTotal = ApiDBUtils.getResourceCount(ResourceType.volume, account.getId()); - String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); - accountResponse.setVolumeLimit(volumeLimitDisplay); - accountResponse.setVolumeTotal(volumeTotal); - accountResponse.setVolumeAvailable(volumeAvail); - - Long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.snapshot, account.getId()); - String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); - Long snapshotTotal = ApiDBUtils.getResourceCount(ResourceType.snapshot, account.getId()); - String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); - accountResponse.setSnapshotLimit(snapshotLimitDisplay); - accountResponse.setSnapshotTotal(snapshotTotal); - accountResponse.setSnapshotAvailable(snapshotAvail); - - Long templateLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.template, account.getId()); - String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); - Long templateTotal = ApiDBUtils.getResourceCount(ResourceType.template, account.getId()); - String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); - accountResponse.setTemplateLimit(templateLimitDisplay); - accountResponse.setTemplateTotal(templateTotal); - accountResponse.setTemplateAvailable(templateAvail); - - // Get stopped and running VMs - int vmStopped = 0; - int vmRunning = 0; - - List permittedAccounts = new ArrayList(); - permittedAccounts.add(account.getId()); - - List virtualMachines = ApiDBUtils.searchForUserVMs(new Criteria(), permittedAccounts); - - // get Running/Stopped VMs - for (Iterator iter = virtualMachines.iterator(); iter.hasNext();) { - // count how many stopped/running vms we have - UserVm vm = iter.next(); - - if (vm.getState() == State.Stopped) { - vmStopped++; - } else if (vm.getState() == State.Running) { - vmRunning++; - } - } - - accountResponse.setVmStopped(vmStopped); - accountResponse.setVmRunning(vmRunning); - accountResponse.setObjectName("account"); - - //get resource limits for projects - Long projectLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.project, account.getId()); - String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); - Long projectTotal = ApiDBUtils.getResourceCount(ResourceType.project, account.getId()); - String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); - accountResponse.setProjectLimit(projectLimitDisplay); - accountResponse.setProjectTotal(projectTotal); - accountResponse.setProjectAvailable(projectAvail); - - //get resource limits for networks - Long networkLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.network, account.getId()); - String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); - Long networkTotal = ApiDBUtils.getResourceCount(ResourceType.network, account.getId()); - String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); - accountResponse.setNetworkLimit(networkLimitDisplay); - accountResponse.setNetworkTotal(networkTotal); - accountResponse.setNetworkAvailable(networkAvail); - - //get resource limits for vpcs - Long vpcLimit = ApiDBUtils.findCorrectResourceLimit(ResourceType.vpc, account.getId()); - String vpcLimitDisplay = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit); - Long vpcTotal = ApiDBUtils.getResourceCount(ResourceType.vpc, account.getId()); - String vpcAvail = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit - vpcTotal); - accountResponse.setNetworkLimit(vpcLimitDisplay); - accountResponse.setNetworkTotal(vpcTotal); - accountResponse.setNetworkAvailable(vpcAvail); - - // adding all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - accountResponse.setUsers(userResponseList); - accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); - return accountResponse; + AccountJoinVO vUser = ApiDBUtils.newAccountView(account); + return ApiDBUtils.newAccountResponse(vUser); } - - + + @Override public UserResponse createUserResponse(UserAccount user) { - UserResponse userResponse = new UserResponse(); - userResponse.setAccountName(user.getAccountName()); - userResponse.setAccountType(user.getType()); - userResponse.setCreated(user.getCreated()); - userResponse.setDomainId(user.getDomainId()); - userResponse.setDomainName(ApiDBUtils.findDomainById(user.getDomainId()).getName()); - userResponse.setEmail(user.getEmail()); - userResponse.setFirstname(user.getFirstname()); - userResponse.setId(user.getId()); - userResponse.setLastname(user.getLastname()); - userResponse.setState(user.getState()); - userResponse.setTimezone(user.getTimezone()); - userResponse.setUsername(user.getUsername()); - userResponse.setApiKey(user.getApiKey()); - userResponse.setSecretKey(user.getSecretKey()); - userResponse.setAccountId((user.getAccountId())); - userResponse.setObjectName("user"); - - return userResponse; + UserAccountJoinVO vUser = ApiDBUtils.newUserView(user); + return ApiDBUtils.newUserResponse(vUser); } @Override public DomainResponse createDomainResponse(Domain domain) { DomainResponse domainResponse = new DomainResponse(); domainResponse.setDomainName(domain.getName()); - domainResponse.setId(domain.getId()); + domainResponse.setId(domain.getUuid()); domainResponse.setLevel(domain.getLevel()); domainResponse.setNetworkDomain(domain.getNetworkDomain()); - domainResponse.setParentDomainId(domain.getParent()); - StringBuilder domainPath = new StringBuilder("ROOT"); + Domain parentDomain = ApiDBUtils.findDomainById(domain.getParent()); + if (parentDomain != null) { + domainResponse.setParentDomainId(parentDomain.getUuid()); + } + StringBuilder domainPath = new StringBuilder("ROOT"); (domainPath.append(domain.getPath())).deleteCharAt(domainPath.length() - 1); domainResponse.setPath(domainPath.toString()); if (domain.getParent() != null) { @@ -452,14 +298,17 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public DiskOfferingResponse createDiskOfferingResponse(DiskOffering offering) { DiskOfferingResponse diskOfferingResponse = new DiskOfferingResponse(); - diskOfferingResponse.setId(offering.getId()); + diskOfferingResponse.setId(offering.getUuid()); diskOfferingResponse.setName(offering.getName()); diskOfferingResponse.setDisplayText(offering.getDisplayText()); diskOfferingResponse.setCreated(offering.getCreated()); diskOfferingResponse.setDiskSize(offering.getDiskSize() / (1024 * 1024 * 1024)); if (offering.getDomainId() != null) { - diskOfferingResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - diskOfferingResponse.setDomainId(offering.getDomainId()); + Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); + if (domain != null) { + diskOfferingResponse.setDomain(domain.getName()); + diskOfferingResponse.setDomainId(domain.getUuid()); + } } diskOfferingResponse.setTags(offering.getTags()); diskOfferingResponse.setCustomized(offering.isCustomized()); @@ -508,7 +357,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ServiceOfferingResponse createServiceOfferingResponse(ServiceOffering offering) { ServiceOfferingResponse offeringResponse = new ServiceOfferingResponse(); - offeringResponse.setId(offering.getId()); + offeringResponse.setId(offering.getUuid()); offeringResponse.setName(offering.getName()); offeringResponse.setIsSystemOffering(offering.getSystemUse()); offeringResponse.setDefaultUse(offering.getDefaultUse()); @@ -523,8 +372,11 @@ public class ApiResponseHelper implements ResponseGenerator { offeringResponse.setLimitCpuUse(offering.getLimitCpuUse()); offeringResponse.setTags(offering.getTags()); if (offering.getDomainId() != null) { - offeringResponse.setDomain(ApiDBUtils.findDomainById(offering.getDomainId()).getName()); - offeringResponse.setDomainId(offering.getDomainId()); + Domain domain = ApiDBUtils.findDomainById(offering.getDomainId()); + if (domain != null) { + offeringResponse.setDomain(domain.getName()); + offeringResponse.setDomainId(domain.getUuid()); + } } offeringResponse.setNetworkRate(offering.getRateMbps()); offeringResponse.setHostTag(offering.getHostTag()); @@ -548,15 +400,15 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public SnapshotResponse createSnapshotResponse(Snapshot snapshot) { SnapshotResponse snapshotResponse = new SnapshotResponse(); - snapshotResponse.setId(snapshot.getId()); + snapshotResponse.setId(snapshot.getUuid()); populateOwner(snapshotResponse, snapshot); VolumeVO volume = findVolumeById(snapshot.getVolumeId()); String snapshotTypeStr = snapshot.getType().name(); snapshotResponse.setSnapshotType(snapshotTypeStr); - snapshotResponse.setVolumeId(snapshot.getVolumeId()); if (volume != null) { + snapshotResponse.setVolumeId(volume.getUuid()); snapshotResponse.setVolumeName(volume.getName()); snapshotResponse.setVolumeType(volume.getVolumeType().name()); } @@ -564,7 +416,7 @@ public class ApiResponseHelper implements ResponseGenerator { snapshotResponse.setName(snapshot.getName()); snapshotResponse.setIntervalType(ApiDBUtils.getSnapshotIntervalTypes(snapshot.getId())); snapshotResponse.setState(snapshot.getStatus()); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Snapshot, snapshot.getId()); List tagResponses = new ArrayList(); @@ -573,7 +425,7 @@ public class ApiResponseHelper implements ResponseGenerator { tagResponses.add(tagResponse); } snapshotResponse.setTags(tagResponses); - + snapshotResponse.setObjectName("snapshot"); return snapshotResponse; } @@ -581,8 +433,11 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public SnapshotPolicyResponse createSnapshotPolicyResponse(SnapshotPolicy policy) { SnapshotPolicyResponse policyResponse = new SnapshotPolicyResponse(); - policyResponse.setId(policy.getId()); - policyResponse.setVolumeId(policy.getVolumeId()); + policyResponse.setId(policy.getUuid()); + Volume vol = ApiDBUtils.findVolumeById(policy.getVolumeId()); + if (vol != null) { + policyResponse.setVolumeId(vol.getUuid()); + } policyResponse.setSchedule(policy.getSchedule()); policyResponse.setIntervalType(policy.getInterval()); policyResponse.setMaxSnaps(policy.getMaxSnaps()); @@ -599,132 +454,16 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public HostResponse createHostResponse(Host host, EnumSet details) { - HostResponse hostResponse = new HostResponse(); - hostResponse.setId(host.getId()); - hostResponse.setCapabilities(host.getCapabilities()); - hostResponse.setClusterId(host.getClusterId()); - hostResponse.setCpuNumber(host.getCpus()); - hostResponse.setZoneId(host.getDataCenterId()); - hostResponse.setDisconnectedOn(host.getDisconnectedOn()); - hostResponse.setHypervisor(host.getHypervisorType()); - hostResponse.setHostType(host.getType()); - hostResponse.setLastPinged(new Date(host.getLastPinged())); - hostResponse.setManagementServerId(host.getManagementServerId()); - hostResponse.setName(host.getName()); - hostResponse.setPodId(host.getPodId()); - hostResponse.setRemoved(host.getRemoved()); - hostResponse.setCpuSpeed(host.getSpeed()); - hostResponse.setState(host.getStatus()); - hostResponse.setIpAddress(host.getPrivateIpAddress()); - hostResponse.setVersion(host.getVersion()); - hostResponse.setCreated(host.getCreated()); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) - || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { - - GuestOSCategoryVO guestOSCategory = ApiDBUtils.getHostGuestOSCategory(host.getId()); - if (guestOSCategory != null) { - hostResponse.setOsCategoryId(guestOSCategory.getId()); - hostResponse.setOsCategoryName(guestOSCategory.getName()); - } - hostResponse.setZoneName(ApiDBUtils.findZoneById(host.getDataCenterId()).getName()); - - if (host.getPodId() != null) { - HostPodVO pod = ApiDBUtils.findPodById(host.getPodId()); - if (pod != null) { - hostResponse.setPodName(pod.getName()); - } - } - - if (host.getClusterId() != null) { - ClusterVO cluster = ApiDBUtils.findClusterById(host.getClusterId()); - hostResponse.setClusterName(cluster.getName()); - hostResponse.setClusterType(cluster.getClusterType().toString()); - } - } - - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - if (host.getType() == Host.Type.Routing) { - if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { - // set allocated capacities - Long mem = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_MEMORY); - Long cpu = ApiDBUtils.getMemoryOrCpuCapacitybyHost(host.getId(), Capacity.CAPACITY_TYPE_CPU); - - hostResponse.setMemoryAllocated(mem); - hostResponse.setMemoryTotal(host.getTotalMemory()); - String hostTags = ApiDBUtils.getHostTags(host.getId()); - hostResponse.setHostTags(hostTags); - - String haTag = ApiDBUtils.getHaTag(); - if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) { - if (haTag.equalsIgnoreCase(hostTags)) { - hostResponse.setHaHost(true); - } else { - hostResponse.setHaHost(false); - } - } else { - hostResponse.setHaHost(false); - } - - hostResponse.setHypervisorVersion(host.getHypervisorVersion()); - - String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; - hostResponse.setCpuAllocated(cpuAlloc); - String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); - hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); - } - - if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { - // set CPU/RAM/Network stats - String cpuUsed = null; - HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); - if (hostStats != null) { - float cpuUtil = (float) hostStats.getCpuUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - hostResponse.setCpuUsed(cpuUsed); - hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); - hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); - hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); - - } - } - - } else if (host.getType() == Host.Type.SecondaryStorage) { - StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); - if (secStorageStats != null) { - hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); - hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); - } - } - - hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host)); - - if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { - Set possibleEvents = host.getStatus().getPossibleEvents(); - if ((possibleEvents != null) && !possibleEvents.isEmpty()) { - String events = ""; - Iterator iter = possibleEvents.iterator(); - while (iter.hasNext()) { - com.cloud.host.Status.Event event = iter.next(); - events += event.toString(); - if (iter.hasNext()) { - events += "; "; - } - } - hostResponse.setEvents(events); - } - } - - hostResponse.setResourceState(host.getResourceState().toString()); - hostResponse.setObjectName("host"); - - return hostResponse; + List viewHosts = ApiDBUtils.newHostView(host); + List listHosts = ViewResponseHelper.createHostResponse(details, viewHosts.toArray(new HostJoinVO[viewHosts.size()])); + assert listHosts != null && listHosts.size() == 1 : "There should be one host returned"; + return listHosts.get(0); } @Override public SwiftResponse createSwiftResponse(Swift swift) { SwiftResponse swiftResponse = new SwiftResponse(); - swiftResponse.setId(swift.getId()); + swiftResponse.setId(swift.getUuid()); swiftResponse.setUrl(swift.getUrl()); swiftResponse.setAccount(swift.getAccount()); swiftResponse.setUsername(swift.getUserName()); @@ -732,20 +471,44 @@ 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()); VlanIpRangeResponse vlanResponse = new VlanIpRangeResponse(); - vlanResponse.setId(vlan.getId()); - vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); + vlanResponse.setId(vlan.getUuid()); + if (vlan.getVlanType() != null) { + vlanResponse.setForVirtualNetwork(vlan.getVlanType().equals(VlanType.VirtualNetwork)); + } vlanResponse.setVlan(vlan.getVlanTag()); - vlanResponse.setZoneId(vlan.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(vlan.getDataCenterId()); + if (zone != null) { + vlanResponse.setZoneId(zone.getUuid()); + } if (podId != null) { HostPodVO pod = ApiDBUtils.findPodById(podId); - vlanResponse.setPodId(podId); if (pod != null) { + vlanResponse.setPodId(pod.getUuid()); vlanResponse.setPodName(pod.getName()); } } @@ -759,15 +522,24 @@ public class ApiResponseHelper implements ResponseGenerator { vlanResponse.setStartIp(range[0]); vlanResponse.setEndIp(range[1]); - vlanResponse.setNetworkId(vlan.getNetworkId()); + if (vlan.getNetworkId() != null) { + Network nw = ApiDBUtils.findNetworkById(vlan.getNetworkId()); + if (nw != null) { + vlanResponse.setNetworkId(nw.getUuid()); + } + } Account owner = ApiDBUtils.getVlanAccount(vlan.getId()); if (owner != null) { populateAccount(vlanResponse, owner.getId()); populateDomain(vlanResponse, owner.getDomainId()); } - vlanResponse.setPhysicalNetworkId(vlan.getPhysicalNetworkId()); - + if (vlan.getPhysicalNetworkId() != null) { + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(vlan.getPhysicalNetworkId()); + if (pnw != null) { + vlanResponse.setPhysicalNetworkId(pnw.getUuid()); + } + } vlanResponse.setObjectName("vlan"); return vlanResponse; } @@ -779,13 +551,16 @@ public class ApiResponseHelper implements ResponseGenerator { long zoneId = ipAddr.getDataCenterId(); IPAddressResponse ipResponse = new IPAddressResponse(); - ipResponse.setId(ipAddr.getId()); + ipResponse.setId(ipAddr.getUuid()); ipResponse.setIpAddress(ipAddr.getAddress().toString()); if (ipAddr.getAllocatedTime() != null) { ipResponse.setAllocated(ipAddr.getAllocatedTime()); } - ipResponse.setZoneId(zoneId); - ipResponse.setZoneName(ApiDBUtils.findZoneById(ipAddr.getDataCenterId()).getName()); + DataCenter zone = ApiDBUtils.findZoneById(ipAddr.getDataCenterId()); + if (zone != null) { + ipResponse.setZoneId(zone.getUuid()); + ipResponse.setZoneName(zone.getName()); + } ipResponse.setSourceNat(ipAddr.isSourceNat()); ipResponse.setIsSystem(ipAddr.getSystem()); @@ -799,24 +574,34 @@ public class ApiResponseHelper implements ResponseGenerator { if (ipAddr.getAssociatedWithVmId() != null) { UserVm vm = ApiDBUtils.findUserVmById(ipAddr.getAssociatedWithVmId()); - ipResponse.setVirtualMachineId(vm.getId()); - ipResponse.setVirtualMachineName(vm.getHostName()); - if (vm.getDisplayName() != null) { - ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); - } else { - ipResponse.setVirtualMachineDisplayName(vm.getHostName()); + if (vm != null) { + ipResponse.setVirtualMachineId(vm.getUuid()); + ipResponse.setVirtualMachineName(vm.getHostName()); + if (vm.getDisplayName() != null) { + ipResponse.setVirtualMachineDisplayName(vm.getDisplayName()); + } else { + ipResponse.setVirtualMachineDisplayName(vm.getHostName()); + } } } if (ipAddr.getAssociatedWithNetworkId() != null) { Network ntwk = ApiDBUtils.findNetworkById(ipAddr.getAssociatedWithNetworkId()); - ipResponse.setAssociatedNetworkId(ipAddr.getAssociatedWithNetworkId()); - ipResponse.setAssociatedNetworkName(ntwk.getName()); + if (ntwk != null) { + ipResponse.setAssociatedNetworkId(ntwk.getUuid()); + ipResponse.setAssociatedNetworkName(ntwk.getName()); + } } - ipResponse.setVpcId(ipAddr.getVpcId()); + if (ipAddr.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(ipAddr.getVpcId()); + if (vpc != null) { + ipResponse.setVpcId(vpc.getUuid()); + } + } - // Network id the ip is associated with (if associated networkId is null, try to get this information from vlan) + // Network id the ip is associated with (if associated networkId is + // null, try to get this information from vlan) Long vlanNetworkId = ApiDBUtils.getVlanNetworkId(ipAddr.getVlanId()); // Network id the ip belongs to @@ -827,17 +612,31 @@ public class ApiResponseHelper implements ResponseGenerator { networkId = ApiDBUtils.getPublicNetworkIdByZone(zoneId); } - ipResponse.setNetworkId(networkId); + if (networkId != null) { + NetworkVO nw = ApiDBUtils.findNetworkById(networkId); + if (nw != null) { + ipResponse.setNetworkId(nw.getUuid()); + } + } ipResponse.setState(ipAddr.getState().toString()); - ipResponse.setPhysicalNetworkId(ipAddr.getPhysicalNetworkId()); + + if (ipAddr.getPhysicalNetworkId() != null) { + PhysicalNetworkVO pnw = ApiDBUtils.findPhysicalNetworkById(ipAddr.getPhysicalNetworkId()); + if (pnw != null) { + ipResponse.setPhysicalNetworkId(pnw.getUuid()); + } + } // show this info to admin only Account account = UserContext.current().getCaller(); - if ((account == null) || account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - ipResponse.setVlanId(ipAddr.getVlanId()); - ipResponse.setVlanName(ApiDBUtils.findVlanById(ipAddr.getVlanId()).getVlanTag()); + if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { + VlanVO vl = ApiDBUtils.findVlanById(ipAddr.getVlanId()); + if (vl != null) { + ipResponse.setVlanId(vl.getUuid()); + ipResponse.setVlanName(vl.getVlanTag()); + } } - + if (ipAddr.getSystem()) { if (ipAddr.isOneToOneNat()) { ipResponse.setPurpose(IpAddress.Purpose.StaticNat.toString()); @@ -845,7 +644,7 @@ public class ApiResponseHelper implements ResponseGenerator { ipResponse.setPurpose(IpAddress.Purpose.Lb.toString()); } } - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.PublicIpAddress, ipAddr.getId()); List tagResponses = new ArrayList(); @@ -854,7 +653,7 @@ public class ApiResponseHelper implements ResponseGenerator { tagResponses.add(tagResponse); } ipResponse.setTags(tagResponses); - + ipResponse.setObjectName("ipaddress"); return ipResponse; } @@ -862,14 +661,14 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public LoadBalancerResponse createLoadBalancerResponse(LoadBalancer loadBalancer) { LoadBalancerResponse lbResponse = new LoadBalancerResponse(); - lbResponse.setId(loadBalancer.getId()); + lbResponse.setId(loadBalancer.getUuid()); lbResponse.setName(loadBalancer.getName()); lbResponse.setDescription(loadBalancer.getDescription()); List cidrs = ApiDBUtils.findFirewallSourceCidrs(loadBalancer.getId()); lbResponse.setCidrList(StringUtils.join(cidrs, ",")); IPAddressVO publicIp = ApiDBUtils.findIpAddressById(loadBalancer.getSourceIpAddressId()); - lbResponse.setPublicIpId(publicIp.getId()); + lbResponse.setPublicIpId(publicIp.getUuid()); lbResponse.setPublicIp(publicIp.getAddress().addr()); lbResponse.setPublicPort(Integer.toString(loadBalancer.getSourcePortStart())); lbResponse.setPrivatePort(Integer.toString(loadBalancer.getDefaultPortStart())); @@ -881,7 +680,10 @@ public class ApiResponseHelper implements ResponseGenerator { } lbResponse.setState(stateToSet); populateOwner(lbResponse, loadBalancer); - lbResponse.setZoneId(publicIp.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(publicIp.getDataCenterId()); + if (zone != null) { + lbResponse.setZoneId(zone.getUuid()); + } //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, loadBalancer.getId()); @@ -906,10 +708,13 @@ public class ApiResponseHelper implements ResponseGenerator { } PodResponse podResponse = new PodResponse(); - podResponse.setId(pod.getId()); + podResponse.setId(pod.getUuid()); podResponse.setName(pod.getName()); - podResponse.setZoneId(pod.getDataCenterId()); - podResponse.setZoneName(PodZoneConfig.getZoneName(pod.getDataCenterId())); + DataCenter zone = ApiDBUtils.findZoneById(pod.getDataCenterId()); + if (zone != null) { + podResponse.setZoneId(zone.getUuid()); + podResponse.setZoneName(zone.getName()); + } podResponse.setNetmask(NetUtils.getCidrNetmask(pod.getCidrSize())); podResponse.setStartIp(ipRange[0]); podResponse.setEndIp(((ipRange.length > 1) && (ipRange[1] != null)) ? ipRange[1] : ""); @@ -952,7 +757,7 @@ public class ApiResponseHelper implements ResponseGenerator { public ZoneResponse createZoneResponse(DataCenter dataCenter, Boolean showCapacities) { Account account = UserContext.current().getCaller(); ZoneResponse zoneResponse = new ZoneResponse(); - zoneResponse.setId(dataCenter.getId()); + zoneResponse.setId(dataCenter.getUuid()); zoneResponse.setName(dataCenter.getName()); zoneResponse.setSecurityGroupsEnabled(ApiDBUtils.isSecurityGroupEnabledInZone(dataCenter.getId())); zoneResponse.setLocalStorageEnabled(dataCenter.isLocalStorageEnabled()); @@ -1046,167 +851,41 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VolumeResponse createVolumeResponse(Volume volume) { - VolumeResponse volResponse = new VolumeResponse(); - volResponse.setId(volume.getId()); - - if (volume.getName() != null) { - volResponse.setName(volume.getName()); - } else { - volResponse.setName(""); - } - - volResponse.setZoneId(volume.getDataCenterId()); - volResponse.setZoneName(ApiDBUtils.findZoneById(volume.getDataCenterId()).getName()); - - volResponse.setVolumeType(volume.getVolumeType().toString()); - volResponse.setDeviceId(volume.getDeviceId()); - - Long instanceId = volume.getInstanceId(); - if (instanceId != null && volume.getState() != Volume.State.Destroy) { - VMInstanceVO vm = ApiDBUtils.findVMInstanceById(instanceId); - if (vm != null) { - volResponse.setVirtualMachineId(vm.getId()); - volResponse.setVirtualMachineName(vm.getHostName()); - UserVm userVm = ApiDBUtils.findUserVmById(vm.getId()); - if (userVm != null) { - if (userVm.getDisplayName() != null) { - volResponse.setVirtualMachineDisplayName(userVm.getDisplayName()); - } else { - volResponse.setVirtualMachineDisplayName(userVm.getHostName()); - } - volResponse.setVirtualMachineState(vm.getState().toString()); - } else { - s_logger.error("User Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } else { - s_logger.error("Vm with Id: " + instanceId + " does not exist for volume " + volume.getId()); - } - } - - // Show the virtual size of the volume - volResponse.setSize(volume.getSize()); - - volResponse.setCreated(volume.getCreated()); - volResponse.setState(volume.getState().toString()); - if(volume.getState() == Volume.State.UploadOp){ - com.cloud.storage.VolumeHostVO volumeHostRef = ApiDBUtils.findVolumeHostRef(volume.getId(), volume.getDataCenterId()); - volResponse.setSize(volumeHostRef.getSize()); - volResponse.setCreated(volumeHostRef.getCreated()); - Account caller = UserContext.current().getCaller(); - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) - volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volumeHostRef.getFormat()).toString()); - if (volumeHostRef.getDownloadState() != Status.DOWNLOADED) { - String volumeStatus = "Processing"; - if (volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { - if (volumeHostRef.getDownloadPercent() == 100) { - volumeStatus = "Checking Volume"; - } else { - volumeStatus = volumeHostRef.getDownloadPercent() + "% Uploaded"; - } - volResponse.setState("Uploading"); - } else { - volumeStatus = volumeHostRef.getErrorString(); - if(volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.NOT_DOWNLOADED){ - volResponse.setState("UploadNotStarted"); - }else { - volResponse.setState("UploadError"); - } - } - volResponse.setStatus(volumeStatus); - } else if (volumeHostRef.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { - volResponse.setStatus("Upload Complete"); - volResponse.setState("Uploaded"); - } else { - volResponse.setStatus("Successfully Installed"); - } - } - - populateOwner(volResponse, volume); - - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingId(volume.getDiskOfferingId()); - } else { - volResponse.setDiskOfferingId(volume.getDiskOfferingId()); - } - - DiskOfferingVO diskOffering = ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); - if (volume.getVolumeType().equals(Volume.Type.ROOT)) { - volResponse.setServiceOfferingName(diskOffering.getName()); - volResponse.setServiceOfferingDisplayText(diskOffering.getDisplayText()); - } else { - volResponse.setDiskOfferingName(diskOffering.getName()); - volResponse.setDiskOfferingDisplayText(diskOffering.getDisplayText()); - } - volResponse.setStorageType(diskOffering.getUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared.toString()); - - Long poolId = volume.getPoolId(); - String poolName = (poolId == null) ? "none" : ApiDBUtils.findStoragePoolById(poolId).getName(); - volResponse.setStoragePoolName(poolName); - // volResponse.setSourceId(volume.getSourceId()); - // if (volume.getSourceType() != null) { - // volResponse.setSourceType(volume.getSourceType().toString()); - // } - - // return hypervisor for ROOT and Resource domain only - Account caller = UserContext.current().getCaller(); - if ((caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) && volume.getState() != Volume.State.UploadOp) { - volResponse.setHypervisor(ApiDBUtils.getVolumeHyperType(volume.getId()).toString()); - } - - volResponse.setAttached(volume.getAttached()); - volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); - boolean isExtractable = true; - if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence. - VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes - isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; - } - } - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Volume, volume.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - volResponse.setTags(tagResponses); - - volResponse.setExtractable(isExtractable); - volResponse.setObjectName("volume"); - return volResponse; + List viewVrs = ApiDBUtils.newVolumeView(volume); + List listVrs = ViewResponseHelper.createVolumeResponse(viewVrs.toArray(new VolumeJoinVO[viewVrs.size()])); + assert listVrs != null && listVrs.size() == 1 : "There should be one volume returned"; + return listVrs.get(0); } @Override public InstanceGroupResponse createInstanceGroupResponse(InstanceGroup group) { - InstanceGroupResponse groupResponse = new InstanceGroupResponse(); - groupResponse.setId(group.getId()); - groupResponse.setName(group.getName()); - groupResponse.setCreated(group.getCreated()); + InstanceGroupJoinVO vgroup = ApiDBUtils.newInstanceGroupView(group); + return ApiDBUtils.newInstanceGroupResponse(vgroup); - populateOwner(groupResponse, group); - - groupResponse.setObjectName("instancegroup"); - return groupResponse; } + + @Override public StoragePoolResponse createStoragePoolResponse(StoragePool pool) { StoragePoolResponse poolResponse = new StoragePoolResponse(); - poolResponse.setId(pool.getId()); + poolResponse.setId(pool.getUuid()); poolResponse.setName(pool.getName()); poolResponse.setState(pool.getStatus()); poolResponse.setPath(pool.getPath()); poolResponse.setIpAddress(pool.getHostAddress()); - poolResponse.setZoneId(pool.getDataCenterId()); - poolResponse.setZoneName(ApiDBUtils.findZoneById(pool.getDataCenterId()).getName()); + DataCenter zone = ApiDBUtils.findZoneById(pool.getDataCenterId()); + if ( zone != null ){ + poolResponse.setZoneId(zone.getUuid()); + poolResponse.setZoneName(zone.getName()); + } if (pool.getPoolType() != null) { poolResponse.setType(pool.getPoolType().toString()); } if (pool.getPodId() != null) { - poolResponse.setPodId(pool.getPodId()); HostPodVO pod = ApiDBUtils.findPodById(pool.getPodId()); if (pod != null) { + poolResponse.setPodId(pod.getUuid()); poolResponse.setPodName(pod.getName()); } } @@ -1226,7 +905,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (pool.getClusterId() != null) { ClusterVO cluster = ApiDBUtils.findClusterById(pool.getClusterId()); - poolResponse.setClusterId(cluster.getId()); + poolResponse.setClusterId(cluster.getUuid()); poolResponse.setClusterName(cluster.getName()); } poolResponse.setTags(ApiDBUtils.getStoragePoolTags(pool.getId())); @@ -1237,20 +916,24 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ClusterResponse createClusterResponse(Cluster cluster, Boolean showCapacities) { ClusterResponse clusterResponse = new ClusterResponse(); - clusterResponse.setId(cluster.getId()); + clusterResponse.setId(cluster.getUuid()); clusterResponse.setName(cluster.getName()); - clusterResponse.setPodId(cluster.getPodId()); - clusterResponse.setZoneId(cluster.getDataCenterId()); + HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); + if (pod != null) { + clusterResponse.setPodId(pod.getUuid()); + clusterResponse.setPodName(pod.getName()); + } + DataCenter dc = ApiDBUtils.findZoneById(cluster.getDataCenterId()); + if (dc != null) { + clusterResponse.setZoneId(dc.getUuid()); + clusterResponse.setZoneName(dc.getName()); + } clusterResponse.setHypervisorType(cluster.getHypervisorType().toString()); clusterResponse.setClusterType(cluster.getClusterType().toString()); clusterResponse.setAllocationState(cluster.getAllocationState().toString()); clusterResponse.setManagedState(cluster.getManagedState().toString()); - HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); - if (pod != null) { - clusterResponse.setPodName(pod.getName()); - } - DataCenterVO zone = ApiDBUtils.findZoneById(cluster.getDataCenterId()); - clusterResponse.setZoneName(zone.getName()); + + if (showCapacities != null && showCapacities) { List capacities = ApiDBUtils.getCapacityByClusterPodZone(null, null, cluster.getId()); Set capacityResponses = new HashSet(); @@ -1288,7 +971,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public FirewallRuleResponse createPortForwardingRuleResponse(PortForwardingRule fwRule) { FirewallRuleResponse response = new FirewallRuleResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setPrivateStartPort(Integer.toString(fwRule.getDestinationPortStart())); response.setPrivateEndPort(Integer.toString(fwRule.getDestinationPortEnd())); response.setProtocol(fwRule.getProtocol()); @@ -1298,15 +981,15 @@ public class ApiResponseHelper implements ResponseGenerator { response.setCidrList(StringUtils.join(cidrs, ",")); IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); - response.setPublicIpAddressId(ip.getId()); + response.setPublicIpAddressId(ip.getUuid()); response.setPublicIpAddress(ip.getAddress().addr()); if (ip != null && fwRule.getDestinationIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(fwRule.getVirtualMachineId()); if (vm != null) { - response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineId(vm.getUuid()); response.setVirtualMachineName(vm.getHostName()); - + if (vm.getDisplayName() != null) { response.setVirtualMachineDisplayName(vm.getDisplayName()); } else { @@ -1319,7 +1002,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (state.equals(FirewallRule.State.Revoke)) { stateToSet = "Deleting"; } - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.PortForwardingRule, fwRule.getId()); List tagResponses = new ArrayList(); @@ -1328,7 +1011,7 @@ public class ApiResponseHelper implements ResponseGenerator { tagResponses.add(tagResponse); } response.setTags(tagResponses); - + response.setState(stateToSet); response.setObjectName("portforwardingrule"); return response; @@ -1337,7 +1020,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public IpForwardingRuleResponse createIpForwardingRuleResponse(StaticNatRule fwRule) { IpForwardingRuleResponse response = new IpForwardingRuleResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setProtocol(fwRule.getProtocol()); IpAddress ip = ApiDBUtils.findIpAddressById(fwRule.getSourceIpAddressId()); @@ -1347,7 +1030,7 @@ public class ApiResponseHelper implements ResponseGenerator { if (ip != null && fwRule.getDestIpAddress() != null) { UserVm vm = ApiDBUtils.findUserVmById(ip.getAssociatedWithVmId()); if (vm != null) {// vm might be destroyed - response.setVirtualMachineId(vm.getId()); + response.setVirtualMachineId(vm.getUuid()); response.setVirtualMachineName(vm.getHostName()); if (vm.getDisplayName() != null) { response.setVirtualMachineDisplayName(vm.getDisplayName()); @@ -1372,420 +1055,56 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public List createUserVmResponse(String objectName, EnumSet details, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - Map dataCenters = new HashMap(); - Map hosts = new HashMap(); - Map templates = new HashMap(); - Map serviceOfferings = new HashMap(); - Map networks = new HashMap(); + List viewVms = ApiDBUtils.newUserVmView(userVms); + return ViewResponseHelper.createUserVmResponse(objectName, details, viewVms.toArray(new UserVmJoinVO[viewVms.size()])); - List vmResponses = new ArrayList(); - - for (UserVm userVm : userVms) { - UserVmResponse userVmResponse = new UserVmResponse(); - Account acct = ApiDBUtils.findAccountById(Long.valueOf(userVm.getAccountId())); - if (acct != null) { - userVmResponse.setAccountName(acct.getAccountName()); - userVmResponse.setDomainId(acct.getDomainId()); - userVmResponse.setDomainName(ApiDBUtils.findDomainById(acct.getDomainId()).getName()); - } - - userVmResponse.setId(userVm.getId()); - userVmResponse.setName(userVm.getHostName()); - userVmResponse.setCreated(userVm.getCreated()); - - userVmResponse.setHaEnable(userVm.isHaEnabled()); - - if (userVm.getDisplayName() != null) { - userVmResponse.setDisplayName(userVm.getDisplayName()); - } else { - userVmResponse.setDisplayName(userVm.getHostName()); - } - - if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - userVmResponse.setInstanceName(userVm.getInstanceName()); - } - - - if (userVm.getPassword() != null) { - userVmResponse.setPassword(userVm.getPassword()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { - InstanceGroupVO group = ApiDBUtils.findInstanceGroupForVM(userVm.getId()); - if (group != null) { - userVmResponse.setGroup(group.getName()); - userVmResponse.setGroupId(group.getId()); - } - - } - - // Data Center Info - DataCenter zone = dataCenters.get(userVm.getDataCenterIdToDeployIn()); - if (zone == null) { - zone = ApiDBUtils.findZoneById(userVm.getDataCenterIdToDeployIn()); - dataCenters.put(zone.getId(), zone); - } - - userVmResponse.setZoneId(zone.getId()); - userVmResponse.setZoneName(zone.getName()); - - // if user is an admin, display host id - if (((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) && (userVm.getHostId() != null)) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - - userVmResponse.setHostId(host.getId()); - userVmResponse.setHostName(host.getName()); - } - - if (userVm.getState() != null) { - if (userVm.getHostId() != null) { - Host host = hosts.get(userVm.getHostId()); - - if (host == null) { - host = ApiDBUtils.findHostById(userVm.getHostId()); - hosts.put(host.getId(), host); - } - if (host.getStatus() != com.cloud.host.Status.Up) { - userVmResponse.setState(VirtualMachine.State.Unknown.toString()); - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } else { - userVmResponse.setState(userVm.getState().toString()); - } - } - - if (userVm.getHypervisorType() != null) { - userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { - // Template Info - VMTemplateVO template = templates.get(userVm.getTemplateId()); - if (template == null) { - template = ApiDBUtils.findTemplateById(userVm.getTemplateId()); - if (template != null) { - templates.put(template.getId(), template); - } - } - - if (template != null) { - userVmResponse.setTemplateId(userVm.getTemplateId()); - userVmResponse.setTemplateName(template.getName()); - userVmResponse.setTemplateDisplayText(template.getDisplayText()); - userVmResponse.setPasswordEnabled(template.getEnablePassword()); - } else { - userVmResponse.setTemplateId(-1L); - userVmResponse.setTemplateName("ISO Boot"); - userVmResponse.setTemplateDisplayText("ISO Boot"); - userVmResponse.setPasswordEnabled(false); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { - // ISO Info - VMTemplateVO iso = templates.get(userVm.getIsoId()); - if (iso == null) { - iso = ApiDBUtils.findTemplateById(userVm.getIsoId()); - if (iso != null) { - templates.put(iso.getId(), iso); - } - } - - if (iso != null) { - userVmResponse.setIsoId(iso.getId()); - userVmResponse.setIsoName(iso.getName()); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(userVm.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(userVm.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - - userVmResponse.setServiceOfferingId(offering.getId()); - userVmResponse.setServiceOfferingName(offering.getName()); - userVmResponse.setCpuNumber(offering.getCpu()); - userVmResponse.setCpuSpeed(offering.getSpeed()); - userVmResponse.setMemory(offering.getRamSize()); - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { - VolumeVO rootVolume = ApiDBUtils.findRootVolume(userVm.getId()); - if (rootVolume != null) { - userVmResponse.setRootDeviceId(rootVolume.getDeviceId()); - String rootDeviceType = "Not created"; - if (rootVolume.getPoolId() != null) { - StoragePoolVO storagePool = ApiDBUtils.findStoragePoolById(rootVolume.getPoolId()); - rootDeviceType = storagePool.getPoolType().toString(); - } - userVmResponse.setRootDeviceType(rootDeviceType); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { - // stats calculation - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - String cpuUsed = null; - VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - } - - userVmResponse.setGuestOsId(userVm.getGuestOSId()); - - if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { - // security groups - list only when zone is security group enabled - if (zone.isSecurityGroupEnabled()) { - List securityGroups = ApiDBUtils.getSecurityGroupsForVm(userVm.getId()); - List securityGroupResponse = new ArrayList(); - for (SecurityGroupVO grp : securityGroups) { - SecurityGroupResponse resp = new SecurityGroupResponse(); - resp.setId(grp.getId()); - resp.setName(grp.getName()); - resp.setDescription(grp.getDescription()); - resp.setObjectName("securitygroup"); - securityGroupResponse.add(resp); - } - userVmResponse.setSecurityGroupList(securityGroupResponse); - } - } - - if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { - List nicProfiles = ApiDBUtils.getNics(userVm); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - nicResponse.setNetworkName(ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()).getName()); - if (acct.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - } - - // Long networkId = singleNicProfile.getNetworkId(); - Network network = networks.get(singleNicProfile.getNetworkId()); - if (network == null) { - network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - networks.put(singleNicProfile.getNetworkId(), network); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - nicResponse.setType(network.getGuestType().toString()); - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - userVmResponse.setNics(nicResponses); - } - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, userVm.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - userVmResponse.setTags(tagResponses); - - IpAddress ip = ApiDBUtils.findIpByAssociatedVmId(userVm.getId()); - if (ip != null) { - userVmResponse.setPublicIpId(ip.getId()); - userVmResponse.setPublicIp(ip.getAddress().addr()); - } - - userVmResponse.setObjectName(objectName); - vmResponses.add(userVmResponse); - } - - return vmResponses; } @Override public List createUserVmResponse(String objectName, UserVm... userVms) { - Account caller = UserContext.current().getCaller(); - boolean caller_is_admin = ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)); - - Hashtable vmDataList = new Hashtable(); - // Initialise the vmdatalist with the input data - for (UserVm userVm : userVms) { - UserVmData userVmData = newUserVmData(userVm); - vmDataList.put(userVm.getId(), userVmData); - } - - vmDataList = ApiDBUtils.listVmDetails(vmDataList); - - // initialize vmresponse from vmdatalist - List vmResponses = new ArrayList(); - DecimalFormat decimalFormat = new DecimalFormat("#.##"); - for (UserVmData uvd : vmDataList.values()) { - UserVmResponse userVmResponse = newUserVmResponse(uvd, caller_is_admin); - - // stats calculation - String cpuUsed = null; - // VmStats vmStats = ApiDBUtils.getVmStatistics(userVmResponse.getId()); - VmStats vmStats = ApiDBUtils.getVmStatistics(uvd.getId()); - if (vmStats != null) { - float cpuUtil = (float) vmStats.getCPUUtilization(); - cpuUsed = decimalFormat.format(cpuUtil) + "%"; - userVmResponse.setCpuUsed(cpuUsed); - - Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); - userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); - - Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); - userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); - } - userVmResponse.setObjectName(objectName); - - vmResponses.add(userVmResponse); - } - return vmResponses; + List viewVms = ApiDBUtils.newUserVmView(userVms); + return ViewResponseHelper.createUserVmResponse(objectName, viewVms.toArray(new UserVmJoinVO[viewVms.size()])); } + + @Override public DomainRouterResponse createDomainRouterResponse(VirtualRouter router) { - Account caller = UserContext.current().getCaller(); - Map serviceOfferings = new HashMap(); - - DomainRouterResponse routerResponse = new DomainRouterResponse(); - routerResponse.setId(router.getId()); - routerResponse.setZoneId(router.getDataCenterIdToDeployIn()); - routerResponse.setName(router.getHostName()); - routerResponse.setTemplateId(router.getTemplateId()); - routerResponse.setCreated(router.getCreated()); - routerResponse.setState(router.getState()); - routerResponse.setIsRedundantRouter(router.getIsRedundantRouter()); - routerResponse.setRedundantState(router.getRedundantState().toString()); - - if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { - if (router.getHostId() != null) { - routerResponse.setHostId(router.getHostId()); - routerResponse.setHostName(ApiDBUtils.findHostById(router.getHostId()).getName()); - } - routerResponse.setPodId(router.getPodIdToDeployIn()); - List nicProfiles = ApiDBUtils.getNics(router); - List nicResponses = new ArrayList(); - for (NicProfile singleNicProfile : nicProfiles) { - Network network = ApiDBUtils.findNetworkById(singleNicProfile.getNetworkId()); - //legacy code, public/control/guest nic info is kept in nics response object - if (network != null) { - if (network.getTrafficType() == TrafficType.Public) { - routerResponse.setPublicIp(singleNicProfile.getIp4Address()); - routerResponse.setPublicMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setPublicNetmask(singleNicProfile.getNetmask()); - routerResponse.setGateway(singleNicProfile.getGateway()); - routerResponse.setPublicNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Control) { - routerResponse.setLinkLocalIp(singleNicProfile.getIp4Address()); - routerResponse.setLinkLocalMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setLinkLocalNetmask(singleNicProfile.getNetmask()); - routerResponse.setLinkLocalNetworkId(singleNicProfile.getNetworkId()); - } else if (network.getTrafficType() == TrafficType.Guest) { - routerResponse.setGuestIpAddress(singleNicProfile.getIp4Address()); - routerResponse.setGuestMacAddress(singleNicProfile.getMacAddress()); - routerResponse.setGuestNetmask(singleNicProfile.getNetmask()); - routerResponse.setGuestNetworkId(singleNicProfile.getNetworkId()); - routerResponse.setNetworkDomain(network.getNetworkDomain()); - } - - NicResponse nicResponse = new NicResponse(); - nicResponse.setId(singleNicProfile.getId()); - nicResponse.setIpaddress(singleNicProfile.getIp4Address()); - nicResponse.setGateway(singleNicProfile.getGateway()); - nicResponse.setNetmask(singleNicProfile.getNetmask()); - nicResponse.setNetworkid(singleNicProfile.getNetworkId()); - nicResponse.setNetworkName(network.getName()); - - if (singleNicProfile.getBroadCastUri() != null) { - nicResponse.setBroadcastUri(singleNicProfile.getBroadCastUri().toString()); - } - if (singleNicProfile.getIsolationUri() != null) { - nicResponse.setIsolationUri(singleNicProfile.getIsolationUri().toString()); - } - - nicResponse.setTrafficType(network.getTrafficType().toString()); - if (network.getGuestType() != null) { - nicResponse.setType(network.getGuestType().toString()); - } - nicResponse.setIsDefault(singleNicProfile.isDefaultNic()); - nicResponse.setObjectName("nic"); - nicResponses.add(nicResponse); - } - } - routerResponse.setNics(nicResponses); - } - - // Service Offering Info - ServiceOffering offering = serviceOfferings.get(router.getServiceOfferingId()); - - if (offering == null) { - offering = ApiDBUtils.findServiceOfferingById(router.getServiceOfferingId()); - serviceOfferings.put(offering.getId(), offering); - } - routerResponse.setServiceOfferingId(offering.getId()); - routerResponse.setServiceOfferingName(offering.getName()); - - populateOwner(routerResponse, router); - - DataCenter zone = ApiDBUtils.findZoneById(router.getDataCenterIdToDeployIn()); - if (zone != null) { - routerResponse.setZoneName(zone.getName()); - routerResponse.setDns1(zone.getDns1()); - routerResponse.setDns2(zone.getDns2()); - } - - routerResponse.setVpcId(router.getVpcId()); - - routerResponse.setObjectName("domainrouter"); - return routerResponse; + List viewVrs = ApiDBUtils.newDomainRouterView(router); + List listVrs = ViewResponseHelper.createDomainRouterResponse(viewVrs.toArray(new DomainRouterJoinVO[viewVrs.size()])); + assert listVrs != null && listVrs.size() == 1 : "There should be one virtual router returned"; + return listVrs.get(0); } + @Override public SystemVmResponse createSystemVmResponse(VirtualMachine vm) { SystemVmResponse vmResponse = new SystemVmResponse(); if (vm.getType() == Type.SecondaryStorageVm || vm.getType() == Type.ConsoleProxy) { // SystemVm vm = (SystemVm) systemVM; - vmResponse.setId(vm.getId()); - vmResponse.setObjectId(vm.getId()); + vmResponse.setId(vm.getUuid()); + //vmResponse.setObjectId(vm.getId()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); - vmResponse.setZoneId(vm.getDataCenterIdToDeployIn()); vmResponse.setName(vm.getHostName()); - vmResponse.setPodId(vm.getPodIdToDeployIn()); - vmResponse.setTemplateId(vm.getTemplateId()); + if ( vm.getPodIdToDeployIn() != null ){ + HostPodVO pod = ApiDBUtils.findPodById(vm.getPodIdToDeployIn()); + if ( pod != null ){ + vmResponse.setPodId(pod.getUuid()); + } + } + VMTemplateVO template = ApiDBUtils.findTemplateById(vm.getTemplateId()); + if (template != null){ + vmResponse.setTemplateId(template.getUuid()); + } vmResponse.setCreated(vm.getCreated()); if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); - vmResponse.setHostName(ApiDBUtils.findHostById(vm.getHostId()).getName()); + Host host = ApiDBUtils.findHostById(vm.getHostId()); + if (host != null) { + vmResponse.setHostId(host.getUuid()); + vmResponse.setHostName(host.getName()); + } } if (vm.getState() != null) { @@ -1803,6 +1122,7 @@ public class ApiResponseHelper implements ResponseGenerator { DataCenter zone = ApiDBUtils.findZoneById(vm.getDataCenterIdToDeployIn()); if (zone != null) { + vmResponse.setZoneId(zone.getUuid()); vmResponse.setZoneName(zone.getName()); vmResponse.setDns1(zone.getDns1()); vmResponse.setDns2(zone.getDns2()); @@ -1868,7 +1188,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VpnUsersResponse createVpnUserResponse(VpnUser vpnUser) { VpnUsersResponse vpnResponse = new VpnUsersResponse(); - vpnResponse.setId(vpnUser.getId()); + vpnResponse.setId(vpnUser.getUuid()); vpnResponse.setUserName(vpnUser.getUsername()); populateOwner(vpnResponse, vpnUser); @@ -1880,11 +1200,13 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public RemoteAccessVpnResponse createRemoteAccessVpnResponse(RemoteAccessVpn vpn) { RemoteAccessVpnResponse vpnResponse = new RemoteAccessVpnResponse(); - vpnResponse.setPublicIpId(vpn.getServerAddressId()); - vpnResponse.setPublicIp(ApiDBUtils.findIpAddressById(vpn.getServerAddressId()).getAddress().addr()); + IpAddress ip = ApiDBUtils.findIpAddressById(vpn.getServerAddressId()); + if (ip != null) { + vpnResponse.setPublicIpId(ip.getUuid()); + vpnResponse.setPublicIp(ip.getAddress().addr()); + } vpnResponse.setIpRange(vpn.getIpRange()); vpnResponse.setPresharedKey(vpn.getIpsecPresharedKey()); - vpnResponse.setDomainId(vpn.getDomainId()); populateOwner(vpnResponse, vpn); @@ -1897,14 +1219,17 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public TemplateResponse createIsoResponse(VirtualMachineTemplate result) { TemplateResponse response = new TemplateResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setName(result.getName()); response.setDisplayText(result.getDisplayText()); response.setPublic(result.isPublicTemplate()); response.setCreated(result.getCreated()); response.setFormat(result.getFormat()); - response.setOsTypeId(result.getGuestOSId()); - response.setOsTypeName(ApiDBUtils.findGuestOSById(result.getGuestOSId()).getDisplayName()); + GuestOS os = ApiDBUtils.findGuestOSById(result.getGuestOSId()); + if (os != null) { + response.setOsTypeId(os.getUuid()); + response.setOsTypeName(os.getDisplayName()); + } response.setDetails(result.getDetails()); Account caller = UserContext.current().getCaller(); @@ -1926,7 +1251,7 @@ public class ApiResponseHelper implements ResponseGenerator { } else { tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Template, result.getId()); } - + List tagResponses = new ArrayList(); for (ResourceTag tag : tags) { ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); @@ -1966,7 +1291,7 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); + templateResponse.setId(template.getUuid()); templateResponse.setName(template.getName()); templateResponse.setDisplayText(template.getDisplayText()); templateResponse.setPublic(template.isPublicTemplate()); @@ -1987,10 +1312,10 @@ public class ApiResponseHelper implements ResponseGenerator { GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { - templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeId(os.getUuid()); templateResponse.setOsTypeName(os.getDisplayName()); } else { - templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeId("-1"); templateResponse.setOsTypeName(""); } @@ -2016,7 +1341,12 @@ public class ApiResponseHelper implements ResponseGenerator { } templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + if (template.getSourceTemplateId() != null) { + VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId()); + if (tmpl != null) { + templateResponse.setSourceTemplateId(tmpl.getUuid()); + } + } templateResponse.setChecksum(template.getChecksum()); @@ -2042,7 +1372,7 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplateResponse templateResponse = new TemplateResponse(); - templateResponse.setId(template.getId()); + templateResponse.setId(template.getUuid()); templateResponse.setName(template.getName()); templateResponse.setDisplayText(template.getDisplayText()); templateResponse.setPublic(template.isPublicTemplate()); @@ -2063,10 +1393,10 @@ public class ApiResponseHelper implements ResponseGenerator { GuestOS os = ApiDBUtils.findGuestOSById(template.getGuestOSId()); if (os != null) { - templateResponse.setOsTypeId(os.getId()); + templateResponse.setOsTypeId(os.getUuid()); templateResponse.setOsTypeName(os.getDisplayName()); } else { - templateResponse.setOsTypeId(-1L); + templateResponse.setOsTypeId("-1"); templateResponse.setOsTypeName(""); } @@ -2074,11 +1404,13 @@ public class ApiResponseHelper implements ResponseGenerator { populateAccount(templateResponse, account.getId()); populateDomain(templateResponse, account.getDomainId()); - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); + DataCenter datacenter = ApiDBUtils.findZoneById(zoneId); - // Add the zone ID - templateResponse.setZoneId(zoneId); - templateResponse.setZoneName(datacenter.getName()); + if (datacenter != null) { + // Add the zone ID + templateResponse.setZoneId(datacenter.getUuid()); + templateResponse.setZoneName(datacenter.getName()); + } boolean isAdmin = false; Account caller = UserContext.current().getCaller(); @@ -2114,7 +1446,12 @@ public class ApiResponseHelper implements ResponseGenerator { } templateResponse.setChecksum(template.getChecksum()); - templateResponse.setSourceTemplateId(template.getSourceTemplateId()); + if (template.getSourceTemplateId() != null) { + VirtualMachineTemplate tmpl = ApiDBUtils.findTemplateById(template.getSourceTemplateId()); + if (tmpl != null) { + templateResponse.setSourceTemplateId(tmpl.getUuid()); + } + } templateResponse.setChecksum(template.getChecksum()); @@ -2142,11 +1479,11 @@ 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(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2180,11 +1517,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)); @@ -2196,6 +1539,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(); @@ -2204,7 +1606,7 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2221,10 +1623,10 @@ public class ApiResponseHelper implements ResponseGenerator { // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { - isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeId(os.getUuid()); isoResponse.setOsTypeName(os.getDisplayName()); } else { - isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeId("-1"); isoResponse.setOsTypeName(""); } Account account = ApiDBUtils.findAccountByIdIncludingRemoved(iso.getAccountId()); @@ -2258,7 +1660,7 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } TemplateResponse isoResponse = new TemplateResponse(); - isoResponse.setId(iso.getId()); + isoResponse.setId(iso.getUuid()); isoResponse.setName(iso.getName()); isoResponse.setDisplayText(iso.getDisplayText()); isoResponse.setPublic(iso.isPublicTemplate()); @@ -2275,10 +1677,10 @@ public class ApiResponseHelper implements ResponseGenerator { // TODO: implement GuestOS os = ApiDBUtils.findGuestOSById(iso.getGuestOSId()); if (os != null) { - isoResponse.setOsTypeId(os.getId()); + isoResponse.setOsTypeId(os.getUuid()); isoResponse.setOsTypeName(os.getDisplayName()); } else { - isoResponse.setOsTypeId(-1L); + isoResponse.setOsTypeId("-1"); isoResponse.setOsTypeName(""); } @@ -2292,9 +1694,11 @@ public class ApiResponseHelper implements ResponseGenerator { isAdmin = true; } // Add the zone ID - DataCenterVO datacenter = ApiDBUtils.findZoneById(zoneId); - isoResponse.setZoneId(zoneId); - isoResponse.setZoneName(datacenter.getName()); + DataCenter datacenter = ApiDBUtils.findZoneById(zoneId); + if (datacenter != null) { + isoResponse.setZoneId(datacenter.getUuid()); + isoResponse.setZoneName(datacenter.getName()); + } // If the user is an admin, add the template download status if (isAdmin || caller.getId() == iso.getAccountId()) { @@ -2325,7 +1729,7 @@ public class ApiResponseHelper implements ResponseGenerator { //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.ISO, iso.getId()); - + List tagResponses = new ArrayList(); for (ResourceTag tag : tags) { ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); @@ -2338,92 +1742,14 @@ public class ApiResponseHelper implements ResponseGenerator { return isoResponses; } - @Override - public ListResponse createSecurityGroupResponses( - List networkGroups) { - List groupResultObjs = SecurityGroupResultObject - .transposeNetworkGroups(networkGroups); - ListResponse response = new ListResponse(); - List netGrpResponses = new ArrayList(); - for (SecurityGroupResultObject networkGroup : groupResultObjs) { - SecurityGroupResponse netGrpResponse = new SecurityGroupResponse(); - netGrpResponse.setId(networkGroup.getId()); - netGrpResponse.setName(networkGroup.getName()); - netGrpResponse.setDescription(networkGroup.getDescription()); - - populateOwner(netGrpResponse, networkGroup); - - List securityGroupRules = networkGroup - .getSecurityGroupRules(); - if ((securityGroupRules != null) && !securityGroupRules.isEmpty()) { - List ingressRulesResponse = new ArrayList(); - List egressRulesResponse = new ArrayList(); - for (SecurityGroupRuleResultObject securityGroupRule : securityGroupRules) { - SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); - ruleData.setRuleId(securityGroupRule.getId()); - ruleData.setProtocol(securityGroupRule.getProtocol()); - - if ("icmp".equalsIgnoreCase(securityGroupRule.getProtocol())) { - ruleData.setIcmpType(securityGroupRule.getStartPort()); - ruleData.setIcmpCode(securityGroupRule.getEndPort()); - } else { - ruleData.setStartPort(securityGroupRule.getStartPort()); - ruleData.setEndPort(securityGroupRule.getEndPort()); - } - - if (securityGroupRule.getAllowedSecurityGroup() != null) { - ruleData.setSecurityGroupName(securityGroupRule - .getAllowedSecurityGroup()); - ruleData.setAccountName(securityGroupRule - .getAllowedSecGroupAcct()); - } else { - ruleData.setCidr(securityGroupRule - .getAllowedSourceIpCidr()); - } - - if (securityGroupRule.getRuleType() == SecurityRuleType.IngressRule) { - ruleData.setObjectName("ingressrule"); - ingressRulesResponse.add(ruleData); - } else { - ruleData.setObjectName("egressrule"); - egressRulesResponse.add(ruleData); - } - } - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, networkGroup.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - netGrpResponse.setTags(tagResponses); - - netGrpResponse - .setSecurityGroupIngressRules(ingressRulesResponse); - netGrpResponse.setSecurityGroupEgressRules(egressRulesResponse); - } - netGrpResponse.setObjectName("securitygroup"); - netGrpResponses.add(netGrpResponse); - } - - response.setResponses(netGrpResponses); - return response; - } @Override public SecurityGroupResponse createSecurityGroupResponse(SecurityGroup group) { - SecurityGroupResponse response = new SecurityGroupResponse(); - - populateOwner(response, group); - - response.setDescription(group.getDescription()); - response.setId(group.getId()); - response.setName(group.getName()); - - response.setObjectName("securitygroup"); - return response; - + List viewSgs = ApiDBUtils.newSecurityGroupView(group); + List listSgs = ViewResponseHelper.createSecurityGroupResponses(viewSgs); + assert listSgs != null && listSgs.size() == 1 : "There should be one security group returned"; + return listSgs.get(0); } @Override @@ -2431,16 +1757,19 @@ public class ApiResponseHelper implements ResponseGenerator { UploadVO uploadInfo = ApiDBUtils.findUploadById(uploadId); ExtractResponse response = new ExtractResponse(); response.setObjectName("template"); - response.setId(id); - response.setName(ApiDBUtils.findTemplateById(id).getName()); + VMTemplateVO template = ApiDBUtils.findTemplateById(id); + response.setId(template.getUuid()); + response.setName(template.getName()); if (zoneId != null) { - response.setZoneId(zoneId); - response.setZoneName(ApiDBUtils.findZoneById(zoneId).getName()); + DataCenter zone = ApiDBUtils.findZoneById(zoneId); + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); } response.setMode(mode); - response.setUploadId(uploadId); + response.setUploadId(uploadInfo.getUuid()); response.setState(uploadInfo.getUploadState().toString()); - response.setAccountId(accountId); + Account account = ApiDBUtils.findAccountById(accountId); + response.setAccountId(account.getUuid()); response.setUrl(uploadInfo.getUploadUrl()); return response; @@ -2453,39 +1782,8 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public AsyncJobResponse createAsyncJobResponse(AsyncJob job) { - AsyncJobResponse jobResponse = new AsyncJobResponse(); - jobResponse.setAccountId(job.getAccountId()); - jobResponse.setUserId(job.getUserId()); - jobResponse.setCmd(job.getCmd()); - jobResponse.setCreated(job.getCreated()); - jobResponse.setJobId(job.getId()); - jobResponse.setJobStatus(job.getStatus()); - jobResponse.setJobProcStatus(job.getProcessStatus()); - - if (job.getInstanceType() != null && job.getInstanceId() != null) { - jobResponse.setJobInstanceType(job.getInstanceType().toString()); - jobResponse.setJobInstanceId(job.getInstanceId()); - } - jobResponse.setJobResultCode(job.getResultCode()); - - boolean savedValue = SerializationContext.current().getUuidTranslation(); - SerializationContext.current().setUuidTranslation(false); - - Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); - jobResponse.setJobResult((ResponseObject) resultObject); - SerializationContext.current().setUuidTranslation(savedValue); - - if (resultObject != null) { - Class clz = resultObject.getClass(); - if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { - jobResponse.setJobResultType("text"); - } else { - jobResponse.setJobResultType("object"); - } - } - - jobResponse.setObjectName("asyncjobs"); - return jobResponse; + AsyncJobJoinVO vJob = ApiDBUtils.newAsyncJobView(job); + return ApiDBUtils.newAsyncJobResponse(vJob); } @Override @@ -2508,26 +1806,12 @@ public class ApiResponseHelper implements ResponseGenerator { return createTemplateResponses(templateId, host.getDataCenterId(), true); } + + @Override public EventResponse createEventResponse(Event event) { - EventResponse responseEvent = new EventResponse(); - responseEvent.setCreated(event.getCreateDate()); - responseEvent.setDescription(event.getDescription()); - responseEvent.setEventType(event.getType()); - responseEvent.setId(event.getId()); - responseEvent.setLevel(event.getLevel()); - responseEvent.setParentId(event.getStartId()); - responseEvent.setState(event.getState()); - - populateOwner(responseEvent, event); - - User user = ApiDBUtils.findUserById(event.getUserId()); - if (user != null) { - responseEvent.setUsername(user.getUsername()); - } - - responseEvent.setObjectName("event"); - return responseEvent; + EventJoinVO vEvent = ApiDBUtils.newEventView(event); + return ApiDBUtils.newEventResponse(vEvent); } private List sumCapacities(List hostCapacities) { @@ -2595,17 +1879,17 @@ public class ApiResponseHelper implements ResponseGenerator { } if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved - // Capacity - // accounts -// for + // Capacity + // accounts + // for // stopped -// vms + // vms // that -// have been + // have been // stopped -// within + // within // an -// interval + // interval usedCapacity += capacity.getReservedCapacity(); } @@ -2634,17 +1918,17 @@ public class ApiResponseHelper implements ResponseGenerator { } if (capacityType == Capacity.CAPACITY_TYPE_CPU || capacityType == Capacity.CAPACITY_TYPE_MEMORY) { // Reserved - // Capacity - // accounts - // for - // stopped - // vms -// that + // Capacity + // accounts + // for + // stopped + // vms + // that // have -// been + // been // stopped // within -// an + // an // interval usedCapacity += capacity.getReservedCapacity(); } @@ -2676,33 +1960,37 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public List createCapacityResponse(List result, DecimalFormat format) { List capacityResponses = new ArrayList(); - + for (Capacity summedCapacity : result) { CapacityResponse capacityResponse = new CapacityResponse(); capacityResponse.setCapacityTotal(summedCapacity.getTotalCapacity()); capacityResponse.setCapacityType(summedCapacity.getCapacityType()); capacityResponse.setCapacityUsed(summedCapacity.getUsedCapacity()); if (summedCapacity.getPodId() != null) { - capacityResponse.setPodId(summedCapacity.getPodId()); + capacityResponse.setPodId(ApiDBUtils.findPodById(summedCapacity.getPodId()).getUuid()); HostPodVO pod = ApiDBUtils.findPodById(summedCapacity.getPodId()); if (pod != null) { + capacityResponse.setPodId(pod.getUuid()); capacityResponse.setPodName(pod.getName()); } } if (summedCapacity.getClusterId() != null) { - capacityResponse.setClusterId(summedCapacity.getClusterId()); ClusterVO cluster = ApiDBUtils.findClusterById(summedCapacity.getClusterId()); if (cluster != null) { + capacityResponse.setClusterId(cluster.getUuid()); capacityResponse.setClusterName(cluster.getName()); if (summedCapacity.getPodId() == null) { - long podId = cluster.getPodId(); - capacityResponse.setPodId(podId); - capacityResponse.setPodName(ApiDBUtils.findPodById(podId).getName()); + HostPodVO pod = ApiDBUtils.findPodById(cluster.getPodId()); + capacityResponse.setPodId(pod.getUuid()); + capacityResponse.setPodName(pod.getName()); } } } - capacityResponse.setZoneId(summedCapacity.getDataCenterId()); - capacityResponse.setZoneName(ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()).getName()); + DataCenter zone = ApiDBUtils.findZoneById(summedCapacity.getDataCenterId()); + if (zone != null) { + capacityResponse.setZoneId(zone.getUuid()); + capacityResponse.setZoneName(zone.getName()); + } if (summedCapacity.getUsedPercentage() != null){ capacityResponse.setPercentUsed(format.format(summedCapacity.getUsedPercentage() * 100f)); } else if (summedCapacity.getTotalCapacity() != 0) { @@ -2731,10 +2019,13 @@ public class ApiResponseHelper implements ResponseGenerator { } TemplatePermissionsResponse response = new TemplatePermissionsResponse(); - response.setId(template.getId()); + response.setId(template.getUuid()); response.setPublicTemplate(template.isPublicTemplate()); if (isAdmin && (templateOwnerDomain != null)) { - response.setDomainId(templateOwnerDomain); + Domain domain = ApiDBUtils.findDomainById(templateOwnerDomain); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } } // Set accounts @@ -2781,27 +2072,27 @@ public class ApiResponseHelper implements ResponseGenerator { Map allowedSecuriytGroupAccounts = new HashMap(); if ((securityRules != null) && !securityRules.isEmpty()) { - SecurityGroup securityGroup = ApiDBUtils.findSecurityGroupById(securityRules.get(0).getSecurityGroupId()); - response.setId(securityGroup.getId()); + SecurityGroupJoinVO securityGroup = ApiDBUtils.findSecurityGroupViewById(securityRules.get(0).getSecurityGroupId()).get(0); + response.setId(securityGroup.getUuid()); response.setName(securityGroup.getName()); response.setDescription(securityGroup.getDescription()); Account account = securiytGroupAccounts.get(securityGroup.getAccountId()); - if (account == null) { - account = ApiDBUtils.findAccountById(securityGroup.getAccountId()); - securiytGroupAccounts.put(securityGroup.getAccountId(), account); + if (securityGroup.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + response.setProjectId(securityGroup.getProjectUuid()); + response.setProjectName(securityGroup.getProjectName()); + } else { + response.setAccountName(securityGroup.getAccountName()); } - populateAccount(response, account.getId()); - populateDomain(response, account.getDomainId()); + response.setDomainId(securityGroup.getDomainUuid()); + response.setDomainName(securityGroup.getDomainName()); - List egressResponses = new ArrayList(); - List ingressResponses = new ArrayList(); for (SecurityRule securityRule : securityRules) { SecurityGroupRuleResponse securityGroupData = new SecurityGroupRuleResponse(); - securityGroupData.setRuleId(securityRule.getId()); + securityGroupData.setRuleId(securityRule.getUuid()); securityGroupData.setProtocol(securityRule.getProtocol()); if ("icmp".equalsIgnoreCase(securityRule.getProtocol())) { securityGroupData.setIcmpType(securityRule.getStartPort()); @@ -2813,35 +2104,24 @@ public class ApiResponseHelper implements ResponseGenerator { Long allowedSecurityGroupId = securityRule.getAllowedNetworkId(); if (allowedSecurityGroupId != null) { - SecurityGroup allowedSecurityGroup = allowedSecurityGroups.get(allowedSecurityGroupId); - if (allowedSecurityGroup == null) { - allowedSecurityGroup = ApiDBUtils.findSecurityGroupById(allowedSecurityGroupId); - allowedSecurityGroups.put(allowedSecurityGroupId, allowedSecurityGroup); + List sgs = ApiDBUtils.findSecurityGroupViewById(allowedSecurityGroupId); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + securityGroupData.setSecurityGroupName(sg.getName()); + securityGroupData.setAccountName(sg.getAccountName()); } - - securityGroupData.setSecurityGroupName(allowedSecurityGroup.getName()); - - Account allowedAccount = allowedSecuriytGroupAccounts.get(allowedSecurityGroup.getAccountId()); - if (allowedAccount == null) { - allowedAccount = ApiDBUtils.findAccountById(allowedSecurityGroup.getAccountId()); - allowedSecuriytGroupAccounts.put(allowedAccount.getId(), allowedAccount); - } - - securityGroupData.setAccountName(allowedAccount.getAccountName()); } else { securityGroupData.setCidr(securityRule.getAllowedSourceIpCidr()); } if (securityRule.getRuleType() == SecurityRuleType.IngressRule) { securityGroupData.setObjectName("ingressrule"); - ingressResponses.add(securityGroupData); + response.addSecurityGroupIngressRule(securityGroupData); } else { securityGroupData.setObjectName("egressrule"); - egressResponses.add(securityGroupData); + response.addSecurityGroupEgressRule(securityGroupData); } } - response.setSecurityGroupIngressRules(ingressResponses); - response.setSecurityGroupEgressRules(egressResponses); response.setObjectName("securitygroup"); } @@ -2851,7 +2131,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public NetworkOfferingResponse createNetworkOfferingResponse(NetworkOffering offering) { NetworkOfferingResponse response = new NetworkOfferingResponse(); - response.setId(offering.getId()); + response.setId(offering.getUuid()); response.setName(offering.getName()); response.setDisplayText(offering.getDisplayText()); response.setTags(offering.getTags()); @@ -2862,11 +2142,18 @@ public class ApiResponseHelper implements ResponseGenerator { response.setSpecifyIpRanges(offering.getSpecifyIpRanges()); response.setAvailability(offering.getAvailability().toString()); response.setNetworkRate(ApiDBUtils.getNetworkRate(offering.getId())); + Long so = null; if (offering.getServiceOfferingId() != null) { - response.setServiceOfferingId(offering.getServiceOfferingId()); + so = offering.getServiceOfferingId(); } else { - response.setServiceOfferingId(ApiDBUtils.findDefaultRouterServiceOffering()); + so = ApiDBUtils.findDefaultRouterServiceOffering(); } + if (so != null) { + ServiceOffering soffering = ApiDBUtils.findServiceOfferingById(so); + if (soffering != null) + response.setServiceOfferingId(soffering.getUuid()); + } + if (offering.getGuestType() != null) { response.setGuestIpType(offering.getGuestType().toString()); } @@ -2905,6 +2192,11 @@ public class ApiResponseHelper implements ResponseGenerator { eLb.setValue(offering.getElasticLb() ? "true" : "false"); lbCapResponse.add(eLb); + CapabilityResponse inline = new CapabilityResponse(); + inline.setName(Capability.InlineMode.getName()); + inline.setValue(offering.isInline() ? "true" : "false"); + lbCapResponse.add(inline); + svcRsp.setCapabilities(lbCapResponse); } else if (Service.SourceNat == service) { List capabilities = new ArrayList(); @@ -2933,7 +2225,7 @@ public class ApiResponseHelper implements ResponseGenerator { serviceResponses.add(svcRsp); } response.setForVpc(ApiDBUtils.isOfferingForVpc(offering)); - + response.setServices(serviceResponses); response.setObjectName("networkoffering"); return response; @@ -2944,7 +2236,7 @@ public class ApiResponseHelper implements ResponseGenerator { // need to get network profile in order to retrieve dns information from there NetworkProfile profile = ApiDBUtils.getNetworkProfile(network.getId()); NetworkResponse response = new NetworkResponse(); - response.setId(network.getId()); + response.setId(network.getUuid()); response.setName(network.getName()); response.setDisplaytext(network.getDisplayText()); if (network.getBroadcastDomainType() != null) { @@ -2967,25 +2259,33 @@ public class ApiResponseHelper implements ResponseGenerator { response.setNetmask(NetUtils.cidr2Netmask(network.getCidr())); } - if (network.getBroadcastUri() != null) { + //return vlan information only to Root admin + if (network.getBroadcastUri() != null && UserContext.current().getCaller().getType() == Account.ACCOUNT_TYPE_ADMIN) { String broadcastUri = network.getBroadcastUri().toString(); response.setBroadcastUri(broadcastUri); String vlan="N/A"; if (broadcastUri.startsWith("vlan")) { - vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); + vlan = broadcastUri.substring("vlan://".length(), broadcastUri.length()); } + //return vlan information only to Root admin response.setVlan(vlan); + } DataCenter zone = ApiDBUtils.findZoneById(network.getDataCenterId()); - response.setZoneId(network.getDataCenterId()); - response.setZoneName(zone.getName()); - response.setPhysicalNetworkId(network.getPhysicalNetworkId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } + if (network.getPhysicalNetworkId() != null) { + PhysicalNetworkVO pnet = ApiDBUtils.findPhysicalNetworkById(network.getPhysicalNetworkId()); + response.setPhysicalNetworkId(pnet.getUuid()); + } // populate network offering information - NetworkOffering networkOffering = ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); + NetworkOffering networkOffering = (NetworkOffering) ApiDBUtils.findNetworkOfferingById(network.getNetworkOfferingId()); if (networkOffering != null) { - response.setNetworkOfferingId(networkOffering.getId()); + response.setNetworkOfferingId(networkOffering.getUuid()); response.setNetworkOfferingName(networkOffering.getName()); response.setNetworkOfferingDisplayText(networkOffering.getDisplayText()); response.setIsSystem(networkOffering.isSystemOnly()); @@ -2997,7 +2297,10 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setState(network.getState().toString()); response.setRestartRequired(network.isRestartRequired()); - response.setRelated(network.getRelated()); + NetworkVO nw = ApiDBUtils.findNetworkById(network.getRelated()); + if (nw != null) { + response.setRelated(nw.getUuid()); + } response.setNetworkDomain(network.getNetworkDomain()); response.setDns1(profile.getDns1()); @@ -3040,19 +2343,31 @@ public class ApiResponseHelper implements ResponseGenerator { } else { // get domain from network_domain table Pair domainNetworkDetails = ApiDBUtils.getDomainNetworkDetails(network.getId()); - response.setDomainId(domainNetworkDetails.first()); + if (domainNetworkDetails.first() != null) { + Domain domain = ApiDBUtils.findDomainById(domainNetworkDetails.first()); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } + } response.setSubdomainAccess(domainNetworkDetails.second()); } Long dedicatedDomainId = ApiDBUtils.getDedicatedNetworkDomain(network.getId()); if (dedicatedDomainId != null) { Domain domain = ApiDBUtils.findDomainById(dedicatedDomainId); - response.setDomainId(dedicatedDomainId); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } response.setDomainName(domain.getName()); } response.setSpecifyIpRanges(network.getSpecifyIpRanges()); - response.setVpcId(network.getVpcId()); + if (network.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(network.getVpcId()); + if (vpc != null) { + response.setVpcId(vpc.getUuid()); + } + } response.setCanUseForDeploy(ApiDBUtils.canUseForDeploy(network)); //set tag information @@ -3080,36 +2395,20 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public ProjectResponse createProjectResponse(Project project) { - ProjectResponse response = new ProjectResponse(); - response.setId(project.getId()); - response.setName(project.getName()); - response.setDisplaytext(project.getDisplayText()); - response.setState(project.getState().toString()); - - Domain domain = ApiDBUtils.findDomainById(project.getDomainId()); - response.setDomainId(domain.getId()); - response.setDomain(domain.getName()); - - response.setOwner(ApiDBUtils.getProjectOwner(project.getId()).getAccountName()); - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Project, project.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - response.setTags(tagResponses); - - response.setObjectName("project"); - return response; + List viewPrjs = ApiDBUtils.newProjectView(project); + List listPrjs = ViewResponseHelper.createProjectResponse(viewPrjs.toArray(new ProjectJoinVO[viewPrjs.size()])); + assert listPrjs != null && listPrjs.size() == 1 : "There should be one project returned"; + return listPrjs.get(0); } + + + @Override public FirewallResponse createFirewallResponse(FirewallRule fwRule) { FirewallResponse response = new FirewallResponse(); - response.setId(fwRule.getId()); + response.setId(fwRule.getUuid()); response.setProtocol(fwRule.getProtocol()); if (fwRule.getSourcePortStart() != null) { response.setStartPort(Integer.toString(fwRule.getSourcePortStart())); @@ -3148,12 +2447,12 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("firewallrule"); return response; } - + @Override public NetworkACLResponse createNetworkACLResponse(FirewallRule networkACL) { NetworkACLResponse response = new NetworkACLResponse(); - response.setId(networkACL.getId()); + response.setId(networkACL.getUuid()); response.setProtocol(networkACL.getProtocol()); if (networkACL.getSourcePortStart() != null) { response.setStartPort(Integer.toString(networkACL.getSourcePortStart())); @@ -3178,7 +2477,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setIcmpType(networkACL.getIcmpType()); response.setState(stateToSet); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.NetworkACL, networkACL.getId()); List tagResponses = new ArrayList(); @@ -3187,150 +2486,15 @@ public class ApiResponseHelper implements ResponseGenerator { tagResponses.add(tagResponse); } response.setTags(tagResponses); - + response.setObjectName("networkacl"); return response; } - public UserVmData newUserVmData(UserVm userVm) { - UserVmData userVmData = new UserVmData(); - userVmData.setId(userVm.getId()); - userVmData.setName(userVm.getHostName()); - userVmData.setCreated(userVm.getCreated()); - userVmData.setGuestOsId(userVm.getGuestOSId()); - userVmData.setHaEnable(userVm.isHaEnabled()); - if (userVm.getState() != null) { - userVmData.setState(userVm.getState().toString()); - } - if (userVm.getDisplayName() != null) { - userVmData.setDisplayName(userVm.getDisplayName()); - } else { - userVmData.setDisplayName(userVm.getHostName()); - } - userVmData.setInstanceName(userVm.getInstanceName()); - - userVmData.setDomainId(userVm.getDomainId()); - - if (userVm.getHypervisorType() != null) { - userVmData.setHypervisor(userVm.getHypervisorType().toString()); - } - - if (userVm.getPassword() != null) { - userVmData.setPassword(userVm.getPassword()); - } - return userVmData; - } - - public UserVmResponse newUserVmResponse(UserVmData userVmData, boolean caller_is_admin) { - UserVmResponse userVmResponse = new UserVmResponse(); - - userVmResponse.setHypervisor(userVmData.getHypervisor()); - userVmResponse.setId(userVmData.getId()); - userVmResponse.setName(userVmData.getName()); - - userVmResponse.setDisplayName(userVmData.getDisplayName()); - - populateAccount(userVmResponse, userVmData.getAccountId()); - populateDomain(userVmResponse, userVmData.getDomainId()); - - userVmResponse.setCreated(userVmData.getCreated()); - userVmResponse.setState(userVmData.getState()); - userVmResponse.setHaEnable(userVmData.getHaEnable()); - userVmResponse.setGroupId(userVmData.getGroupId()); - userVmResponse.setGroup(userVmData.getGroup()); - userVmResponse.setZoneId(userVmData.getZoneId()); - userVmResponse.setZoneName(userVmData.getZoneName()); - if (caller_is_admin) { - userVmResponse.setInstanceName(userVmData.getInstanceName()); - userVmResponse.setHostId(userVmData.getHostId()); - userVmResponse.setHostName(userVmData.getHostName()); - } - userVmResponse.setTemplateId(userVmData.getTemplateId()); - userVmResponse.setTemplateName(userVmData.getTemplateName()); - userVmResponse.setTemplateDisplayText(userVmData.getTemplateDisplayText()); - userVmResponse.setPasswordEnabled(userVmData.getPasswordEnabled()); - userVmResponse.setIsoId(userVmData.getIsoId()); - userVmResponse.setIsoName(userVmData.getIsoName()); - userVmResponse.setIsoDisplayText(userVmData.getIsoDisplayText()); - userVmResponse.setServiceOfferingId(userVmData.getServiceOfferingId()); - userVmResponse.setServiceOfferingName(userVmData.getServiceOfferingName()); - userVmResponse.setCpuNumber(userVmData.getCpuNumber()); - userVmResponse.setCpuSpeed(userVmData.getCpuSpeed()); - userVmResponse.setMemory(userVmData.getMemory()); - userVmResponse.setCpuUsed(userVmData.getCpuUsed()); - userVmResponse.setNetworkKbsRead(userVmData.getNetworkKbsRead()); - userVmResponse.setNetworkKbsWrite(userVmData.getNetworkKbsWrite()); - userVmResponse.setGuestOsId(userVmData.getGuestOsId()); - userVmResponse.setRootDeviceId(userVmData.getRootDeviceId()); - userVmResponse.setRootDeviceType(userVmData.getRootDeviceType()); - userVmResponse.setPassword(userVmData.getPassword()); - userVmResponse.setJobId(userVmData.getJobId()); - userVmResponse.setJobStatus(userVmData.getJobStatus()); - userVmResponse.setForVirtualNetwork(userVmData.getForVirtualNetwork()); - - Set securityGroupResponse = new HashSet(); - for (SecurityGroupData sgd : userVmData.getSecurityGroupList()) { - if (sgd.getId() != null) { - SecurityGroupResponse sgr = new SecurityGroupResponse(); - sgr.setId(sgd.getId()); - sgr.setName(sgd.getName()); - sgr.setDescription(sgd.getDescription()); - - Account account = ApiDBUtils.findAccountByNameDomain(sgd.getAccountName(), sgd.getDomainId()); - if (account != null) { - populateAccount(sgr, account.getId()); - populateDomain(sgr, account.getDomainId()); - } - - sgr.setObjectName(sgd.getObjectName()); - securityGroupResponse.add(sgr); - } - } - userVmResponse.setSecurityGroupList(new ArrayList(securityGroupResponse)); - - Set nicResponses = new HashSet(); - for (NicData nd : userVmData.getNics()) { - NicResponse nr = new NicResponse(); - nr.setId(nd.getId()); - nr.setNetworkid(nd.getNetworkid()); - nr.setNetmask(nd.getNetmask()); - nr.setGateway(nd.getGateway()); - nr.setIpaddress(nd.getIpaddress()); - nr.setIsolationUri(nd.getIsolationUri()); - nr.setBroadcastUri(nd.getBroadcastUri()); - nr.setTrafficType(nd.getTrafficType()); - nr.setType(nd.getType()); - nr.setIsDefault(nd.getIsDefault()); - nr.setMacAddress(nd.getMacAddress()); - nr.setObjectName(nd.getObjectName()); - nicResponses.add(nr); - } - userVmResponse.setNics(new ArrayList(nicResponses)); - userVmResponse.setPublicIpId(userVmData.getPublicIpId()); - userVmResponse.setPublicIp(userVmData.getPublicIp()); - - //set tag information - List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.UserVm, userVmData.getId()); - List tagResponses = new ArrayList(); - for (ResourceTag tag : tags) { - ResourceTagResponse tagResponse = createResourceTagResponse(tag, true); - tagResponses.add(tagResponse); - } - userVmResponse.setTags(tagResponses); - - UserVmDetailVO userVmDetail = ApiDBUtils.findPublicKeyByVmId(userVmData.getId()); - if (userVmDetail != null && userVmDetail.getValue() != null) { - String keyPairName = ApiDBUtils.getKeyPairName(userVmDetail.getValue()); - userVmResponse.setKeyPairName(keyPairName); - } - - return userVmResponse; - } - @Override public HypervisorCapabilitiesResponse createHypervisorCapabilitiesResponse(HypervisorCapabilities hpvCapabilities) { HypervisorCapabilitiesResponse hpvCapabilitiesResponse = new HypervisorCapabilitiesResponse(); - hpvCapabilitiesResponse.setId(hpvCapabilities.getId()); + hpvCapabilitiesResponse.setId(hpvCapabilities.getUuid()); hpvCapabilitiesResponse.setHypervisor(hpvCapabilities.getHypervisorType()); hpvCapabilitiesResponse.setHypervisorVersion(hpvCapabilities.getHypervisorVersion()); hpvCapabilitiesResponse.setIsSecurityGroupEnabled(hpvCapabilities.isSecurityGroupEnabled()); @@ -3338,29 +2502,44 @@ public class ApiResponseHelper implements ResponseGenerator { return hpvCapabilitiesResponse; } + // TODO: we may need to refactor once ControlledEntityResponse and ControlledEntity id to uuid conversion are all done. + // currently code is scattered in private void populateOwner(ControlledEntityResponse response, ControlledEntity object) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(object.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { // find the project Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); + response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); } Domain domain = ApiDBUtils.findDomainById(object.getDomainId()); - response.setDomainId(domain.getId()); + response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); } + public static void populateOwner(ControlledViewEntityResponse response, ControlledViewEntity object) { + + if (object.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + response.setProjectId(object.getProjectUuid()); + response.setProjectName(object.getProjectName()); + } else { + response.setAccountName(object.getAccountName()); + } + + response.setDomainId(object.getDomainUuid()); + response.setDomainName(object.getDomainName()); + } + private void populateAccount(ControlledEntityResponse response, long accountId) { Account account = ApiDBUtils.findAccountByIdIncludingRemoved(accountId); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { // find the project Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); + response.setProjectId(project.getUuid()); response.setProjectName(project.getName()); } else { response.setAccountName(account.getAccountName()); @@ -3370,69 +2549,39 @@ public class ApiResponseHelper implements ResponseGenerator { private void populateDomain(ControlledEntityResponse response, long domainId) { Domain domain = ApiDBUtils.findDomainById(domainId); - response.setDomainId(domain.getId()); + response.setDomainId(domain.getUuid()); response.setDomainName(domain.getName()); } @Override public ProjectAccountResponse createProjectAccountResponse(ProjectAccount projectAccount) { - Account account = ApiDBUtils.findAccountById(projectAccount.getAccountId()); - ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); - - long projectId = projectAccount.getProjectId(); - projectAccountResponse.setProjectId(projectId); - projectAccountResponse.setProjectName(ApiDBUtils.findProjectById(projectId).getName()); - - projectAccountResponse.setId(account.getId()); - projectAccountResponse.setAccountName(account.getAccountName()); - projectAccountResponse.setAccountType(account.getType()); - projectAccountResponse.setRole(projectAccount.getAccountRole().toString()); - populateDomain(projectAccountResponse, account.getDomainId()); - - // add all the users for an account as part of the response obj - List usersForAccount = ApiDBUtils.listUsersByAccount(account.getAccountId()); - List userResponseList = new ArrayList(); - for (UserVO user : usersForAccount) { - UserResponse userResponse = createUserResponse(user); - userResponseList.add(userResponse); - } - - projectAccountResponse.setUsers(userResponseList); - projectAccountResponse.setObjectName("projectaccount"); - - return projectAccountResponse; + ProjectAccountJoinVO vProj = ApiDBUtils.newProjectAccountView(projectAccount); + List listProjs = ViewResponseHelper.createProjectAccountResponse(vProj); + assert listProjs != null && listProjs.size() == 1 : "There should be one project account returned"; + return listProjs.get(0); } + + + @Override public ProjectInvitationResponse createProjectInvitationResponse(ProjectInvitation invite) { - ProjectInvitationResponse response = new ProjectInvitationResponse(); - response.setId(invite.getId()); - response.setProjectId(invite.getProjectId()); - response.setProjectName(ApiDBUtils.findProjectById(invite.getProjectId()).getName()); - response.setInvitationState(invite.getState().toString()); - - if (invite.getForAccountId() != null) { - Account account = ApiDBUtils.findAccountById(invite.getForAccountId()); - response.setAccountName(account.getAccountName()); - - } else { - response.setEmail(invite.getEmail()); - } - - populateDomain(response, invite.getInDomainId()); - - response.setObjectName("projectinvitation"); - return response; + ProjectInvitationJoinVO vInvite = ApiDBUtils.newProjectInvitationView(invite); + return ApiDBUtils.newProjectInvitationResponse(vInvite); } + @Override public SystemVmInstanceResponse createSystemVmInstanceResponse(VirtualMachine vm) { SystemVmInstanceResponse vmResponse = new SystemVmInstanceResponse(); - vmResponse.setId(vm.getId()); + vmResponse.setId(vm.getUuid()); vmResponse.setSystemVmType(vm.getType().toString().toLowerCase()); vmResponse.setName(vm.getHostName()); if (vm.getHostId() != null) { - vmResponse.setHostId(vm.getHostId()); + Host host = ApiDBUtils.findHostById(vm.getHostId()); + if (host != null) { + vmResponse.setHostId(host.getUuid()); + } } if (vm.getState() != null) { vmResponse.setState(vm.getState().toString()); @@ -3451,10 +2600,18 @@ public class ApiResponseHelper implements ResponseGenerator { public PhysicalNetworkResponse createPhysicalNetworkResponse(PhysicalNetwork result) { PhysicalNetworkResponse response = new PhysicalNetworkResponse(); - response.setZoneId(result.getDataCenterId()); + DataCenter zone = ApiDBUtils.findZoneById(result.getDataCenterId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + } response.setNetworkSpeed(result.getSpeed()); response.setVlan(result.getVnet()); - response.setDomainId(result.getDomainId()); + if (result.getDomainId() != null) { + Domain domain = ApiDBUtils.findDomainById(result.getDomainId()); + if (domain != null) { + response.setDomainId(domain.getUuid()); + } + } response.setId(result.getUuid()); if (result.getBroadcastDomainRange() != null) { response.setBroadcastDomainRange(result.getBroadcastDomainRange().toString()); @@ -3526,8 +2683,14 @@ public class ApiResponseHelper implements ResponseGenerator { ProviderResponse response = new ProviderResponse(); response.setId(result.getUuid()); response.setName(result.getProviderName()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setDestinationPhysicalNetworkId(result.getDestinationPhysicalNetworkId()); + PhysicalNetwork pnw = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnw != null) { + response.setPhysicalNetworkId(pnw.getUuid()); + } + PhysicalNetwork dnw = ApiDBUtils.findPhysicalNetworkById(result.getDestinationPhysicalNetworkId()); + if (dnw != null) { + response.setDestinationPhysicalNetworkId(dnw.getUuid()); + } response.setState(result.getState().toString()); // set enabled services @@ -3545,8 +2708,14 @@ public class ApiResponseHelper implements ResponseGenerator { public TrafficTypeResponse createTrafficTypeResponse(PhysicalNetworkTrafficType result) { TrafficTypeResponse response = new TrafficTypeResponse(); response.setId(result.getUuid()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - response.setTrafficType(result.getTrafficType().toString()); + PhysicalNetwork pnet = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnet != null) { + response.setPhysicalNetworkId(pnet.getUuid()); + } + if (result.getTrafficType() != null) { + response.setTrafficType(result.getTrafficType().toString()); + } + response.setXenLabel(result.getXenNetworkLabel()); response.setKvmLabel(result.getKvmNetworkLabel()); response.setVmwareLabel(result.getVmwareNetworkLabel()); @@ -3558,8 +2727,11 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public VirtualRouterProviderResponse createVirtualRouterProviderResponse(VirtualRouterProvider result) { VirtualRouterProviderResponse response = new VirtualRouterProviderResponse(); - response.setId(result.getId()); - response.setNspId(result.getNspId()); + response.setId(result.getUuid()); + PhysicalNetworkServiceProvider nsp = ApiDBUtils.findPhysicalNetworkServiceProviderById(result.getNspId()); + if (nsp != null) { + response.setNspId(nsp.getUuid()); + } response.setEnabled(result.isEnabled()); response.setObjectName("virtualrouterelement"); @@ -3571,13 +2743,15 @@ public class ApiResponseHelper implements ResponseGenerator { StickinessPolicy stickinessPolicy, LoadBalancer lb) { LBStickinessResponse spResponse = new LBStickinessResponse(); - spResponse.setlbRuleId(lb.getId()); + spResponse.setlbRuleId(lb.getUuid()); Account accountTemp = ApiDBUtils.findAccountById(lb.getAccountId()); if (accountTemp != null) { spResponse.setAccountName(accountTemp.getAccountName()); - spResponse.setDomainId(accountTemp.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - accountTemp.getDomainId()).getName()); + Domain domain = ApiDBUtils.findDomainById(accountTemp.getDomainId()); + if (domain != null) { + spResponse.setDomainId(domain.getUuid()); + spResponse.setDomainName(domain.getName()); + } } List responses = new ArrayList(); @@ -3598,13 +2772,15 @@ public class ApiResponseHelper implements ResponseGenerator { if (lb == null) return spResponse; - spResponse.setlbRuleId(lb.getId()); + spResponse.setlbRuleId(lb.getUuid()); Account account = ApiDBUtils.findAccountById(lb.getAccountId()); if (account != null) { spResponse.setAccountName(account.getAccountName()); - spResponse.setDomainId(account.getDomainId()); - spResponse.setDomainName(ApiDBUtils.findDomainById( - account.getDomainId()).getName()); + Domain domain = ApiDBUtils.findDomainById(account.getDomainId()); + if (domain != null) { + spResponse.setDomainId(domain.getUuid()); + spResponse.setDomainName(domain.getName()); + } } List responses = new ArrayList(); @@ -3648,53 +2824,24 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("storagenetworkiprange"); return response; } - + @Override public Long getIdentiyId(String tableName, String token) { return ApiDispatcher.getIdentiyId(tableName, token); } - + @Override public ResourceTagResponse createResourceTagResponse(ResourceTag resourceTag, boolean keyValueOnly) { - ResourceTagResponse response = new ResourceTagResponse(); - response.setKey(resourceTag.getKey()); - response.setValue(resourceTag.getValue()); - - if (!keyValueOnly) { - response.setResourceType(resourceTag.getResourceType().toString()); - response.setId(ApiDBUtils.getUuid(String.valueOf(resourceTag.getResourceId()),resourceTag.getResourceType())); - Long accountId = resourceTag.getAccountId(); - Long domainId = resourceTag.getDomainId(); - if (accountId != null) { - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(resourceTag.getAccountId()); - - if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { - // find the project - Project project = ApiDBUtils.findProjectByProjectAccountIdIncludingRemoved(account.getId()); - response.setProjectId(project.getId()); - response.setProjectName(project.getName()); - } else { - response.setAccountName(account.getAccountName()); - } - } - - if (domainId != null) { - response.setDomainId(domainId); - response.setDomainName(ApiDBUtils.findDomainById(domainId).getName()); - } - - response.setCustomer(resourceTag.getCustomer()); - } - - response.setObjectName("tag"); - - return response; + ResourceTagJoinVO rto = ApiDBUtils.newResourceTagView(resourceTag); + return ApiDBUtils.newResourceTagResponse(rto, keyValueOnly); } - + + + @Override public VpcOfferingResponse createVpcOfferingResponse(VpcOffering offering) { VpcOfferingResponse response = new VpcOfferingResponse(); - response.setId(offering.getId()); + response.setId(offering.getUuid()); response.setName(offering.getName()); response.setDisplayText(offering.getDisplayText()); response.setIsDefault(offering.isDefault()); @@ -3725,16 +2872,19 @@ public class ApiResponseHelper implements ResponseGenerator { response.setObjectName("vpcoffering"); return response; } - - + + @Override public VpcResponse createVpcResponse(Vpc vpc) { VpcResponse response = new VpcResponse(); - response.setId(vpc.getId()); + response.setId(vpc.getUuid()); response.setName(vpc.getName()); response.setDisplayText(vpc.getDisplayText()); response.setState(vpc.getState().name()); - response.setVpcOfferingId(vpc.getVpcOfferingId()); + VpcOffering voff = ApiDBUtils.findVpcOfferingById(vpc.getVpcOfferingId()); + if (voff != null) { + response.setVpcOfferingId(voff.getUuid()); + } response.setCidr(vpc.getCidr()); response.setRestartRequired(vpc.isRestartRequired()); response.setNetworkDomain(vpc.getNetworkDomain()); @@ -3760,22 +2910,24 @@ public class ApiResponseHelper implements ResponseGenerator { serviceResponses.add(svcRsp); } - + List networkResponses = new ArrayList(); List networks = ApiDBUtils.listVpcNetworks(vpc.getId()); for (Network network : networks) { NetworkResponse ntwkRsp = createNetworkResponse(network); networkResponses.add(ntwkRsp); } - + DataCenter zone = ApiDBUtils.findZoneById(vpc.getZoneId()); - response.setZoneId(vpc.getZoneId()); - response.setZoneName(zone.getName()); - + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } + response.setNetworks(networkResponses); response.setServices(serviceResponses); populateOwner(response, vpc); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.Vpc, vpc.getId()); List tagResponses = new ArrayList(); @@ -3791,33 +2943,168 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public PrivateGatewayResponse createPrivateGatewayResponse(PrivateGateway result) { PrivateGatewayResponse response = new PrivateGatewayResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setVlan(result.getVlanTag()); response.setGateway(result.getGateway()); response.setNetmask(result.getNetmask()); - response.setVpcId(result.getVpcId()); - response.setZoneId(result.getZoneId()); + if (result.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + response.setVpcId(vpc.getUuid()); + } + DataCenter zone = ApiDBUtils.findZoneById(result.getZoneId()); - response.setZoneName(zone.getName()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + response.setZoneName(zone.getName()); + } response.setAddress(result.getIp4Address()); - response.setPhysicalNetworkId(result.getPhysicalNetworkId()); - + PhysicalNetwork pnet = ApiDBUtils.findPhysicalNetworkById(result.getPhysicalNetworkId()); + if (pnet != null) { + response.setPhysicalNetworkId(pnet.getUuid()); + } + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); response.setState(result.getState().toString()); - + response.setObjectName("privategateway"); - + + return response; } - + + @Override + public CounterResponse createCounterResponse(Counter counter) { + CounterResponse response = new CounterResponse(); + response.setId(counter.getUuid()); + response.setSource(counter.getSource().toString()); + response.setName(counter.getName()); + response.setValue(counter.getValue()); + response.setObjectName("counter"); + return response; + } + + @Override + public ConditionResponse createConditionResponse(Condition condition) { + ConditionResponse response = new ConditionResponse(); + response.setId(condition.getUuid()); + List counterResponseList = new ArrayList(); + counterResponseList.add(createCounterResponse(ApiDBUtils.getCounter(condition.getCounterid()))); + response.setCounterResponse(counterResponseList); + response.setRelationalOperator(condition.getRelationalOperator().toString()); + response.setThreshold(condition.getThreshold()); + response.setObjectName("condition"); + populateOwner(response, condition); + return response; + } + + @Override + public AutoScaleVmProfileResponse createAutoScaleVmProfileResponse(AutoScaleVmProfile profile) { + AutoScaleVmProfileResponse response = new AutoScaleVmProfileResponse(); + response.setId(profile.getUuid()); + if (profile.getZoneId() != null) { + DataCenter zone = ApiDBUtils.findZoneById(profile.getZoneId()); + if (zone != null) { + response.setZoneId(zone.getUuid()); + } + } + if (profile.getServiceOfferingId() != null) { + ServiceOffering so = ApiDBUtils.findServiceOfferingById(profile.getServiceOfferingId()); + if (so != null) { + response.setServiceOfferingId(so.getUuid()); + } + } + if (profile.getTemplateId() != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(profile.getTemplateId()); + if (template != null) { + response.setTemplateId(template.getUuid()); + } + } + response.setOtherDeployParams(profile.getOtherDeployParams()); + response.setCounterParams(profile.getCounterParams()); + response.setDestroyVmGraceperiod(profile.getDestroyVmGraceperiod()); + User user = ApiDBUtils.findUserById(profile.getAutoScaleUserId()); + if (user != null) { + response.setAutoscaleUserId(user.getUuid()); + } + response.setObjectName("autoscalevmprofile"); + + // Populates the account information in the response + populateOwner(response, profile); + return response; + } + + @Override + public AutoScalePolicyResponse createAutoScalePolicyResponse(AutoScalePolicy policy) { + AutoScalePolicyResponse response = new AutoScalePolicyResponse(); + response.setId(policy.getUuid()); + response.setDuration(policy.getDuration()); + response.setQuietTime(policy.getQuietTime()); + response.setAction(policy.getAction()); + List vos = ApiDBUtils.getAutoScalePolicyConditions(policy.getId()); + ArrayList conditions = new ArrayList(vos.size()); + for (ConditionVO vo : vos) { + conditions.add(createConditionResponse(vo)); + } + response.setConditions(conditions); + response.setObjectName("autoscalepolicy"); + + // Populates the account information in the response + populateOwner(response, policy); + + return response; + } + + @Override + public AutoScaleVmGroupResponse createAutoScaleVmGroupResponse(AutoScaleVmGroup vmGroup) { + AutoScaleVmGroupResponse response = new AutoScaleVmGroupResponse(); + response.setId(vmGroup.getUuid()); + response.setMinMembers(vmGroup.getMinMembers()); + response.setMaxMembers(vmGroup.getMaxMembers()); + response.setState(vmGroup.getState()); + response.setInterval(vmGroup.getInterval()); + AutoScaleVmProfileVO profile = ApiDBUtils.findAutoScaleVmProfileById(vmGroup.getProfileId()); + if (profile != null) { + response.setProfileId(profile.getUuid()); + } + FirewallRuleVO fw = ApiDBUtils.findFirewallRuleById(vmGroup.getProfileId()); + if (fw != null) { + response.setLoadBalancerId(fw.getUuid()); + } + + List scaleUpPoliciesResponse = new ArrayList(); + List scaleDownPoliciesResponse = new ArrayList(); + response.setScaleUpPolicies(scaleUpPoliciesResponse); + response.setScaleDownPolicies(scaleDownPoliciesResponse); + response.setObjectName("autoscalevmgroup"); + + // Fetch policies for vmgroup + List scaleUpPolicies = new ArrayList(); + List scaleDownPolicies = new ArrayList(); + ApiDBUtils.getAutoScaleVmGroupPolicies(vmGroup.getId(), scaleUpPolicies, scaleDownPolicies); + // populate policies + for (AutoScalePolicy autoScalePolicy : scaleUpPolicies) { + scaleUpPoliciesResponse.add(createAutoScalePolicyResponse(autoScalePolicy)); + } + for (AutoScalePolicy autoScalePolicy : scaleDownPolicies) { + scaleDownPoliciesResponse.add(createAutoScalePolicyResponse(autoScalePolicy)); + } + + return response; + } + @Override public StaticRouteResponse createStaticRouteResponse(StaticRoute result) { StaticRouteResponse response = new StaticRouteResponse(); - response.setId(result.getId()); - response.setVpcId(result.getVpcId()); + response.setId(result.getUuid()); + if (result.getVpcId() != null) { + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + if (vpc != null) { + response.setVpcId(vpc.getUuid()); + } + } response.setCidr(result.getCidr()); - + StaticRoute.State state = result.getState(); String stateToSet = state.toString(); if (state.equals(FirewallRule.State.Revoke)) { @@ -3826,7 +3113,7 @@ public class ApiResponseHelper implements ResponseGenerator { response.setState(stateToSet); populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + //set tag information List tags = ApiDBUtils.listByResourceTypeAndId(TaggedResourceType.StaticRoute, result.getId()); List tagResponses = new ArrayList(); @@ -3836,19 +3123,22 @@ public class ApiResponseHelper implements ResponseGenerator { } response.setTags(tagResponses); response.setObjectName("staticroute"); - + return response; } - + @Override public Site2SiteVpnGatewayResponse createSite2SiteVpnGatewayResponse(Site2SiteVpnGateway result) { - Site2SiteVpnGatewayResponse response = new Site2SiteVpnGatewayResponse(); - response.setId(result.getId()); + Site2SiteVpnGatewayResponse response = new Site2SiteVpnGatewayResponse(); + response.setId(result.getUuid()); response.setIp(ApiDBUtils.findIpAddressById(result.getAddrId()).getAddress().toString()); - response.setVpcId(result.getVpcId()); + Vpc vpc = ApiDBUtils.findVpcById(result.getVpcId()); + if (vpc != null) { + response.setVpcId(result.getUuid()); + } response.setRemoved(result.getRemoved()); response.setObjectName("vpngateway"); - + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); return response; @@ -3857,7 +3147,7 @@ public class ApiResponseHelper implements ResponseGenerator { @Override public Site2SiteCustomerGatewayResponse createSite2SiteCustomerGatewayResponse(Site2SiteCustomerGateway result) { Site2SiteCustomerGatewayResponse response = new Site2SiteCustomerGatewayResponse(); - response.setId(result.getId()); + response.setId(result.getUuid()); response.setName(result.getName()); response.setGatewayIp(result.getGatewayIp()); response.setGuestCidrList(result.getGuestCidrList()); @@ -3870,49 +3160,94 @@ public class ApiResponseHelper implements ResponseGenerator { response.setRemoved(result.getRemoved()); response.setObjectName("vpncustomergateway"); - + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + return response; } @Override public Site2SiteVpnConnectionResponse createSite2SiteVpnConnectionResponse(Site2SiteVpnConnection result) { Site2SiteVpnConnectionResponse response = new Site2SiteVpnConnectionResponse(); - response.setId(result.getId()); - - response.setVpnGatewayId(result.getVpnGatewayId()); + response.setId(result.getUuid()); + Long vpnGatewayId = result.getVpnGatewayId(); if(vpnGatewayId != null) { - Site2SiteVpnGatewayVO vpnGateway = ApiDBUtils.findVpnGatewayById(vpnGatewayId); - - long ipId = vpnGateway.getAddrId(); - IPAddressVO ipObj = ApiDBUtils.findIpAddressById(ipId); - response.setIp(ipObj.getAddress().addr()); + Site2SiteVpnGateway vpnGateway = ApiDBUtils.findVpnGatewayById(vpnGatewayId); + if (vpnGateway != null) { + response.setVpnGatewayId(vpnGateway.getUuid()); + long ipId = vpnGateway.getAddrId(); + IPAddressVO ipObj = ApiDBUtils.findIpAddressById(ipId); + response.setIp(ipObj.getAddress().addr()); + } } - - response.setCustomerGatewayId(result.getCustomerGatewayId()); + Long customerGatewayId = result.getCustomerGatewayId(); if(customerGatewayId != null) { - Site2SiteCustomerGatewayVO customerGateway = ApiDBUtils.findCustomerGatewayById(customerGatewayId); - response.setGatewayIp(customerGateway.getGatewayIp()); - response.setGuestCidrList(customerGateway.getGuestCidrList()); - response.setIpsecPsk(customerGateway.getIpsecPsk()); - response.setIkePolicy(customerGateway.getIkePolicy()); - response.setEspPolicy(customerGateway.getEspPolicy()); + Site2SiteCustomerGateway customerGateway = ApiDBUtils.findCustomerGatewayById(customerGatewayId); + if (customerGateway != null) { + response.setCustomerGatewayId(customerGateway.getUuid()); + response.setGatewayIp(customerGateway.getGatewayIp()); + response.setGuestCidrList(customerGateway.getGuestCidrList()); + response.setIpsecPsk(customerGateway.getIpsecPsk()); + response.setIkePolicy(customerGateway.getIkePolicy()); + response.setEspPolicy(customerGateway.getEspPolicy()); response.setIkeLifetime(customerGateway.getIkeLifetime()); response.setEspLifetime(customerGateway.getEspLifetime()); response.setDpd(customerGateway.getDpd()); - } - + } + } + populateAccount(response, result.getAccountId()); populateDomain(response, result.getDomainId()); - + response.setState(result.getState().toString()); response.setCreated(result.getCreated()); response.setRemoved(result.getRemoved()); response.setObjectName("vpnconnection"); return response; } + + + + @Override + public GuestOSResponse createGuestOSResponse(GuestOS guestOS) { + GuestOSResponse response = new GuestOSResponse(); + response.setDescription(guestOS.getDisplayName()); + response.setId(guestOS.getUuid()); + GuestOSCategoryVO category = ApiDBUtils.findGuestOsCategoryById(guestOS.getCategoryId()); + if ( category != null ){ + response.setOsCategoryId(category.getUuid()); + } + + response.setObjectName("ostype"); + return response; + } + + + + @Override + public SnapshotScheduleResponse createSnapshotScheduleResponse(SnapshotSchedule snapshotSchedule) { + SnapshotScheduleResponse response = new SnapshotScheduleResponse(); + response.setId(snapshotSchedule.getUuid()); + if (snapshotSchedule.getVolumeId() != null) { + Volume vol = ApiDBUtils.findVolumeById(snapshotSchedule.getVolumeId()); + if (vol != null) { + response.setVolumeId(vol.getUuid()); + } + } + if (snapshotSchedule.getPolicyId() != null) { + SnapshotPolicy policy = ApiDBUtils.findSnapshotPolicyById(snapshotSchedule.getPolicyId()); + if (policy != null) { + response.setSnapshotPolicyId(policy.getUuid()); + } + } + response.setScheduled(snapshotSchedule.getScheduledTimestamp()); + + response.setObjectName("snapshot"); + return response; + } + + } diff --git a/server/src/com/cloud/api/ApiSerializerHelper.java b/server/src/com/cloud/api/ApiSerializerHelper.java index e2e1547491d..735330d261c 100644 --- a/server/src/com/cloud/api/ApiSerializerHelper.java +++ b/server/src/com/cloud/api/ApiSerializerHelper.java @@ -16,6 +16,7 @@ // under the License. package com.cloud.api; +import org.apache.cloudstack.api.ResponseObject; import org.apache.log4j.Logger; import com.google.gson.Gson; diff --git a/server/src/com/cloud/api/ApiServer.java b/server/src/com/cloud/api/ApiServer.java index 457bba41f07..8a88cbba750 100755 --- a/server/src/com/cloud/api/ApiServer.java +++ b/server/src/com/cloud/api/ApiServer.java @@ -17,16 +17,14 @@ package com.cloud.api; import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.IOException; -import java.io.InputStream; import java.io.InterruptedIOException; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; +import java.net.URI; +import java.net.URISyntaxException; import java.net.URLDecoder; import java.net.URLEncoder; import java.security.SecureRandom; @@ -40,7 +38,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.Set; import java.util.TimeZone; import java.util.concurrent.ExecutorService; @@ -54,13 +51,24 @@ import javax.inject.Inject; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.cloudstack.acl.APIAccessChecker; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; import org.apache.commons.codec.binary.Base64; +import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpServerConnection; import org.apache.http.HttpStatus; +import org.apache.http.NameValuePair; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.DefaultHttpServerConnection; @@ -83,9 +91,16 @@ import org.apache.http.protocol.ResponseServer; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.ExceptionResponse; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.response.ExceptionResponse; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.async.AsyncJob; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -107,180 +122,77 @@ import com.cloud.user.User; import com.cloud.user.UserAccount; import com.cloud.user.UserContext; import com.cloud.user.UserVO; -import com.cloud.utils.IdentityProxy; import com.cloud.utils.Pair; -import com.cloud.utils.PropertiesUtil; -import com.cloud.utils.component.ComponentContext; +import com.cloud.utils.component.Adapters; +import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.PluggableService; +import com.cloud.utils.component.Inject; import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CSExceptionErrorCode; import com.cloud.uuididentity.dao.IdentityDao; +import org.reflections.Reflections; + public class ApiServer implements HttpRequestHandler { private static final Logger s_logger = Logger.getLogger(ApiServer.class.getName()); private static final Logger s_accessLogger = Logger.getLogger("apiserver." + ApiServer.class.getName()); - public static final short ADMIN_COMMAND = 1; - public static final short DOMAIN_ADMIN_COMMAND = 4; - public static final short RESOURCE_DOMAIN_ADMIN_COMMAND = 2; - public static final short USER_COMMAND = 8; public static boolean encodeApiResponse = false; public static String jsonContentType = "text/javascript"; - private Properties _apiCommands = null; private ApiDispatcher _dispatcher; - @Inject private AccountManager _accountMgr; - @Inject private DomainManager _domainMgr; - @Inject private AsyncJobManager _asyncMgr; - @Inject private ConfigurationDao _configDao; - private Account _systemAccount; - private User _systemUser; - - @Inject List _pluggableServices; + @Inject private AccountManager _accountMgr = null; + @Inject private DomainManager _domainMgr = null; + @Inject private AsyncJobManager _asyncMgr = null; + @Inject(adapter = APIAccessChecker.class) + protected Adapters _apiAccessCheckers; + + private Account _systemAccount = null; + private User _systemUser = null; private static int _workerCount = 0; - private static ApiServer s_instance = null; - private static List s_userCommands = null; - private static List s_resellerCommands = null; // AKA domain-admin - private static List s_adminCommands = null; - private static List s_resourceDomainAdminCommands = null; - private static List s_allCommands = null; - private static List s_pluggableServiceCommands = null; private static final DateFormat _dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); + private Map> _apiNameCmdClassMap = new HashMap>(); private static ExecutorService _executor = new ThreadPoolExecutor(10, 150, 60, TimeUnit.SECONDS, new LinkedBlockingQueue(), new NamedThreadFactory("ApiServer")); - static { - s_userCommands = new ArrayList(); - s_resellerCommands = new ArrayList(); - s_adminCommands = new ArrayList(); - s_resourceDomainAdminCommands = new ArrayList(); - s_allCommands = new ArrayList(); - s_pluggableServiceCommands = new ArrayList(); - } - - public ApiServer() { + protected ApiServer() { + super(); } public static void initApiServer(String[] apiConfig) { if (s_instance == null) { - s_instance = new ApiServer(); - s_instance = ComponentContext.inject(s_instance); + //Injecting will create ApiServer object with all its + //vars injected as well, no need to do the following: + //s_instance = new ApiServer(); + s_instance = ComponentLocator.inject(ApiServer.class); s_instance.init(apiConfig); } } public static ApiServer getInstance() { - // initApiServer(); + // Assumption: CloudStartupServlet would initialize ApiServer + // initApiServer(null); + if (s_instance == null) { + s_logger.fatal("ApiServer instance failed to initialize"); + } return s_instance; } - public Properties get_apiCommands() { - return _apiCommands; - } - - public static boolean isPluggableServiceCommand(String cmdClassName) { - if (s_pluggableServiceCommands != null) { - if (s_pluggableServiceCommands.contains(cmdClassName)) { - return true; - } - } - return false; - } - - private String[] getPluggableServicesApiConfigs() { - List pluggableServicesApiConfigs = new ArrayList(); - - for (PluggableService service : _pluggableServices) { - pluggableServicesApiConfigs.add(service.getPropertiesFile()); - } - return pluggableServicesApiConfigs.toArray(new String[0]); - } - - private void processConfigFiles(String[] apiConfig, boolean pluggableServicesConfig) { - try { - if (_apiCommands == null) { - _apiCommands = new Properties(); - } - Properties preProcessedCommands = new Properties(); - if (apiConfig != null) { - for (String configFile : apiConfig) { - File commandsFile = PropertiesUtil.findConfigFile(configFile); - if (commandsFile != null) { - try { - preProcessedCommands.load(new FileInputStream(commandsFile)); - } catch (FileNotFoundException fnfex) { - // in case of a file within a jar in classpath, try to open stream using url - InputStream stream = PropertiesUtil.openStreamFromURL(configFile); - if (stream != null) { - preProcessedCommands.load(stream); - } else { - s_logger.error("Unable to find properites file", fnfex); - } - } - } - } - for (Object key : preProcessedCommands.keySet()) { - String preProcessedCommand = preProcessedCommands.getProperty((String) key); - String[] commandParts = preProcessedCommand.split(";"); - _apiCommands.put(key, commandParts[0]); - - if (pluggableServicesConfig) { - s_pluggableServiceCommands.add(commandParts[0]); - } - - if (commandParts.length > 1) { - try { - short cmdPermissions = Short.parseShort(commandParts[1]); - if ((cmdPermissions & ADMIN_COMMAND) != 0) { - s_adminCommands.add((String) key); - } - if ((cmdPermissions & RESOURCE_DOMAIN_ADMIN_COMMAND) != 0) { - s_resourceDomainAdminCommands.add((String) key); - } - if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { - s_resellerCommands.add((String) key); - } - if ((cmdPermissions & USER_COMMAND) != 0) { - s_userCommands.add((String) key); - } - } catch (NumberFormatException nfe) { - s_logger.info("Malformed command.properties permissions value, key = " + key + ", value = " + preProcessedCommand); - } - } - } - - s_allCommands.addAll(s_adminCommands); - s_allCommands.addAll(s_resourceDomainAdminCommands); - s_allCommands.addAll(s_userCommands); - s_allCommands.addAll(s_resellerCommands); - } - } catch (FileNotFoundException fnfex) { - s_logger.error("Unable to find properites file", fnfex); - } catch (IOException ioex) { - s_logger.error("Exception loading properties file", ioex); - } - } - public void init(String[] apiConfig) { BaseCmd.setComponents(new ApiResponseHelper()); BaseListCmd.configure(); - processConfigFiles(apiConfig, false); - - // get commands for all pluggable services - String[] pluggableServicesApiConfigs = getPluggableServicesApiConfigs(); - processConfigFiles(pluggableServicesApiConfigs, true); _systemAccount = _accountMgr.getSystemAccount(); _systemUser = _accountMgr.getSystemUser(); _dispatcher = ApiDispatcher.getInstance(); Integer apiPort = null; // api port, null by default - - SearchCriteria sc = _configDao.createSearchCriteria(); + ComponentLocator locator = ComponentLocator.getLocator(ManagementServer.Name); + ConfigurationDao configDao = locator.getDao(ConfigurationDao.class); + SearchCriteria sc = configDao.createSearchCriteria(); sc.addAnd("name", SearchCriteria.Op.EQ, "integration.api.port"); List values = _configDao.search(sc, null); if ((values != null) && (values.size() > 0)) { @@ -290,9 +202,21 @@ public class ApiServer implements HttpRequestHandler { } } - encodeApiResponse = Boolean.valueOf(_configDao.getValue(Config.EncodeApiResponse.key())); + // Populate api name and cmd class mappings + Reflections reflections = new Reflections("org.apache.cloudstack.api"); + Set> cmdClasses = reflections.getTypesAnnotatedWith(APICommand.class); + reflections = new Reflections("com.cloud.api"); + cmdClasses.addAll(reflections.getTypesAnnotatedWith(APICommand.class)); + for(Class cmdClass: cmdClasses) { + String apiName = cmdClass.getAnnotation(APICommand.class).name(); + if (_apiNameCmdClassMap.containsKey(apiName)) { + s_logger.error("API Cmd class " + cmdClass.getName() + " has non-unique apiname" + apiName); + } + _apiNameCmdClassMap.put(apiName, cmdClass); + } - String jsonType = _configDao.getValue(Config.JavaScriptDefaultContentType.key()); + encodeApiResponse = Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())); + String jsonType = configDao.getValue(Config.JavaScriptDefaultContentType.key()); if (jsonType != null) { jsonContentType = jsonType; } @@ -303,49 +227,49 @@ public class ApiServer implements HttpRequestHandler { } } + // NOTE: handle() only handles over the wire (OTW) requests from integration.api.port 8096 + // If integration api port is not configured, actual OTW requests will be received by ApiServlet @SuppressWarnings({ "unchecked", "rawtypes" }) @Override - public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { - // get some information for the access log... + public void handle(HttpRequest request, HttpResponse response, HttpContext context) + throws HttpException, IOException { + + // Create StringBuffer to log information in access log StringBuffer sb = new StringBuffer(); HttpServerConnection connObj = (HttpServerConnection) context.getAttribute("http.connection"); if (connObj instanceof SocketHttpServerConnection) { InetAddress remoteAddr = ((SocketHttpServerConnection) connObj).getRemoteAddress(); sb.append(remoteAddr.toString() + " -- "); } - sb.append(request.getRequestLine()); + sb.append(StringUtils.cleanString(request.getRequestLine().toString())); try { - String uri = request.getRequestLine().getUri(); - int requestParamsStartIndex = uri.indexOf('?'); - if (requestParamsStartIndex >= 0) { - uri = uri.substring(requestParamsStartIndex + 1); - } - - String[] paramArray = uri.split("&"); - if (paramArray.length < 1) { - s_logger.info("no parameters received for request: " + uri + ", aborting..."); - return; + List paramList = null; + try { + paramList = URLEncodedUtils.parse(new URI(request.getRequestLine().getUri()), "UTF-8"); + } catch (URISyntaxException e) { + s_logger.error("Error parsing url request", e); } + // Use Multimap as the parameter map should be in the form (name=String, value=String[]) + // So parameter values are stored in a list for the same name key + // APITODO: Use Guava's (import com.google.common.collect.Multimap;) + // (Immutable)Multimap paramMultiMap = HashMultimap.create(); + // Map> parameterMap = paramMultiMap.asMap(); Map parameterMap = new HashMap(); - - String responseType = BaseCmd.RESPONSE_TYPE_XML; - for (String paramEntry : paramArray) { - String[] paramValue = paramEntry.split("="); - if (paramValue.length != 2) { - s_logger.info("malformed parameter: " + paramEntry + ", skipping"); + String responseType = BaseCmd.RESPONSE_TYPE_JSON; + for (NameValuePair param : paramList) { + if (param.getName().equalsIgnoreCase("response")) { + responseType = param.getValue(); continue; } - if ("response".equalsIgnoreCase(paramValue[0])) { - responseType = paramValue[1]; - } else { - // according to the servlet spec, the parameter map should be in the form (name=String, - // value=String[]), so - // parameter values will be stored in an array - parameterMap.put(/* name */paramValue[0], /* value */new String[] { paramValue[1] }); - } + parameterMap.put(param.getName(), new String[] { param.getValue() }); } + + // Check responseType, if not among valid types, fallback to JSON + if (!(responseType.equals(BaseCmd.RESPONSE_TYPE_JSON) || responseType.equals(BaseCmd.RESPONSE_TYPE_XML))) + responseType = BaseCmd.RESPONSE_TYPE_JSON; + try { // always trust commands from API port, user context will always be UID_SYSTEM/ACCOUNT_ID_SYSTEM UserContext.registerContext(_systemUser.getId(), _systemAccount, null, true); @@ -413,9 +337,9 @@ public class ApiServer implements HttpRequestHandler { } paramMap.put(key, decodedValue); } - String cmdClassName = _apiCommands.getProperty(command[0]); - if (cmdClassName != null) { - Class cmdClass = Class.forName(cmdClassName); + + Class cmdClass = getCmdClass(command[0]); + if (cmdClass != null) { BaseCmd cmdObj = (BaseCmd) cmdClass.newInstance(); cmdObj.setFullUrlParams(paramMap); cmdObj.setResponseType(responseType); @@ -436,12 +360,11 @@ public class ApiServer implements HttpRequestHandler { InvalidParameterValueException ref = (InvalidParameterValueException)ex; ServerApiException e = new ServerApiException(BaseCmd.PARAM_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy obj = idList.get(i); - e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName()); + e.addProxyObject(idList.get(i)); } } // Also copy over the cserror code and the function/layer in which it was thrown. @@ -451,12 +374,11 @@ public class ApiServer implements HttpRequestHandler { PermissionDeniedException ref = (PermissionDeniedException)ex; ServerApiException e = new ServerApiException(BaseCmd.ACCOUNT_ERROR, ex.getMessage()); // copy over the IdentityProxy information as well and throw the serverapiexception. - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { // Iterate through entire arraylist and copy over each proxy id. for (int i = 0 ; i < idList.size(); i++) { - IdentityProxy obj = idList.get(i); - e.addProxyObject(obj.getTableName(), obj.getValue(), obj.getidFieldName()); + e.addProxyObject(idList.get(i)); } } e.setCSErrorCode(ref.getCSErrorCode()); @@ -477,6 +399,11 @@ public class ApiServer implements HttpRequestHandler { UserContext ctx = UserContext.current(); Long callerUserId = ctx.getCallerUserId(); Account caller = ctx.getCaller(); + + // Queue command based on Cmd super class: + // BaseCmd: cmd is dispatched to ApiDispatcher, executed, serialized and returned. + // BaseAsyncCreateCmd: cmd params are processed and create() is called, then same workflow as BaseAsyncCmd. + // BaseAsyncCmd: cmd is processed and submitted as an AsyncJob, job related info is serialized and returned. if (cmdObj instanceof BaseAsyncCmd) { Long objectId = null; String objectEntityTable = null; @@ -487,8 +414,7 @@ public class ApiServer implements HttpRequestHandler { objectEntityTable = createCmd.getEntityTable(); params.put("id", objectId.toString()); } else { - ApiDispatcher.setupParameters(cmdObj, params); - ApiDispatcher.plugService(cmdObj); + ApiDispatcher.processParameters(cmdObj, params); } BaseAsyncCmd asyncCmd = (BaseAsyncCmd) cmdObj; @@ -516,14 +442,9 @@ public class ApiServer implements HttpRequestHandler { ctx.setAccountId(asyncCmd.getEntityOwnerId()); - AsyncJobVO job = new AsyncJobVO(); - job.setInstanceId((objectId == null) ? asyncCmd.getInstanceId() : objectId); - job.setInstanceType(asyncCmd.getInstanceType()); - job.setUserId(callerUserId); - job.setAccountId(caller.getId()); - - job.setCmd(cmdObj.getClass().getName()); - job.setCmdInfo(ApiGsonHelper.getBuilder().create().toJson(params)); + Long instanceId = (objectId == null) ? asyncCmd.getInstanceId() : objectId; + AsyncJobVO job = new AsyncJobVO(callerUserId, caller.getId(), cmdObj.getClass().getName(), + ApiGsonHelper.getBuilder().create().toJson(params), instanceId, asyncCmd.getInstanceType()); long jobId = _asyncMgr.submitAsyncJob(job); @@ -545,7 +466,19 @@ public class ApiServer implements HttpRequestHandler { // if the command is of the listXXXCommand, we will need to also return the // the job id and status if possible - if (cmdObj instanceof BaseListCmd) { + if (cmdObj instanceof BaseListCmd && !(cmdObj instanceof ListVMsCmd) && !(cmdObj instanceof ListRoutersCmd) + && !(cmdObj instanceof ListSecurityGroupsCmd) + && !(cmdObj instanceof ListTagsCmd) + && !(cmdObj instanceof ListEventsCmd) + && !(cmdObj instanceof ListVMGroupsCmd) + && !(cmdObj instanceof ListProjectsCmd) + && !(cmdObj instanceof ListProjectAccountsCmd) + && !(cmdObj instanceof ListProjectInvitationsCmd) + && !(cmdObj instanceof ListHostsCmd) + && !(cmdObj instanceof ListVolumesCmd) + && !(cmdObj instanceof ListUsersCmd) + && !(cmdObj instanceof ListAccountsCmd) + ) { buildAsyncListResponse((BaseListCmd) cmdObj, caller); } @@ -570,46 +503,37 @@ public class ApiServer implements HttpRequestHandler { return; } - // Using maps might possibly be more efficient if the set is large enough but for now, we'll just do a - // comparison of two lists. Either way, there shouldn't be too many async jobs active for the account. + Map objectJobMap = new HashMap(); for (AsyncJob job : jobs) { if (job.getInstanceId() == null) { continue; } + String instanceUuid = ApiDBUtils.findJobInstanceUuid(job); + if (instanceUuid != null) { + objectJobMap.put(instanceUuid, job); + } + } + for (ResponseObject response : responses) { - if (response.getObjectId() != null && job.getInstanceId().longValue() == response.getObjectId().longValue()) { - response.setJobId(job.getId()); + if (response.getObjectId() != null && objectJobMap.containsKey(response.getObjectId())) { + AsyncJob job = objectJobMap.get(response.getObjectId()); + response.setJobId(job.getUuid()); response.setJobStatus(job.getStatus()); } } } } - } private void buildAuditTrail(StringBuffer auditTrailSb, String command, String result) { if (result == null) { 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()); } } } - */ - } - - private static boolean isCommandAvailable(String commandName) { - boolean isCommandAvailable = false; - isCommandAvailable = s_allCommands.contains(commandName); - return isCommandAvailable; + 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 { @@ -629,20 +553,17 @@ public class ApiServer implements HttpRequestHandler { // if userId not null, that mean that user is logged in if (userId != null) { - Long accountId = ApiDBUtils.findUserById(userId).getAccountId(); - Account userAccount = _accountMgr.getAccount(accountId); - short accountType = userAccount.getType(); - - if (!isCommandAvailable(accountType, commandName)) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); + User user = ApiDBUtils.findUserById(userId); + if (!isCommandAvailable(user, commandName)) { + s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } return true; } else { // check against every available command to see if the command exists or not - if (!isCommandAvailable(commandName) && !commandName.equals("login") && !commandName.equals("logout")) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist"); + if (!isCommandAvailable(null, commandName) && !commandName.equals("login") && !commandName.equals("logout")) { + s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command does not exist or it is not available for user"); } } @@ -734,9 +655,9 @@ public class ApiServer implements HttpRequestHandler { UserContext.updateContext(user.getId(), account, null); - if (!isCommandAvailable(account.getType(), commandName)) { - s_logger.warn("The given command:" + commandName + " does not exist"); - throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist"); + if (!isCommandAvailable(user, commandName)) { + s_logger.warn("The given command:" + commandName + " does not exist or it is not available for user"); + throw new ServerApiException(BaseCmd.UNSUPPORTED_ACTION_ERROR, "The given command:" + commandName + " does not exist or it is not available for user"); } // verify secret key exists @@ -872,23 +793,17 @@ public class ApiServer implements HttpRequestHandler { return true; } - public static boolean isCommandAvailable(short accountType, String commandName) { - boolean isCommandAvailable = false; - switch (accountType) { - case Account.ACCOUNT_TYPE_ADMIN: - isCommandAvailable = s_adminCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_DOMAIN_ADMIN: - isCommandAvailable = s_resellerCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN: - isCommandAvailable = s_resourceDomainAdminCommands.contains(commandName); - break; - case Account.ACCOUNT_TYPE_NORMAL: - isCommandAvailable = s_userCommands.contains(commandName); - break; + private boolean isCommandAvailable(User user, String commandName) { + for (APIAccessChecker apiChecker : _apiAccessCheckers) { + // Fail the checking if any checker fails to verify + if (!apiChecker.canAccessAPI(user, commandName)) + return false; } - return isCommandAvailable; + return true; + } + + private Class getCmdClass(String cmdName) { + return _apiNameCmdClassMap.get(cmdName); } // FIXME: rather than isError, we might was to pass in the status code to give more flexibility @@ -1024,8 +939,7 @@ public class ApiServer implements HttpRequestHandler { public String getSerializedApiError(int errorCode, String errorText, Map apiCommandParams, String responseType, Exception ex) { String responseName = null; - String cmdClassName = null; - + Class cmdClass = null; String responseText = null; try { @@ -1036,10 +950,9 @@ public class ApiServer implements HttpRequestHandler { // cmd name can be null when "command" parameter is missing in the request if (cmdObj != null) { String cmdName = ((String[]) cmdObj)[0]; - cmdClassName = _apiCommands.getProperty(cmdName); - if (cmdClassName != null) { - Class claz = Class.forName(cmdClassName); - responseName = ((BaseCmd) claz.newInstance()).getCommandName(); + cmdClass = getCmdClass(cmdName); + if (cmdClass != null) { + responseName = ((BaseCmd) cmdClass.newInstance()).getCommandName(); } else { responseName = "errorresponse"; } @@ -1060,33 +973,30 @@ public class ApiServer implements HttpRequestHandler { // Cast the exception appropriately and retrieve the IdentityProxy if (ex instanceof ServerApiException) { ServerApiException ref = (ServerApiException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); + apiResponse.addProxyObject(idList.get(i)); } } // Also copy over the cserror code and the function/layer in which it was thrown. apiResponse.setCSErrorCode(ref.getCSErrorCode()); } else if (ex instanceof PermissionDeniedException) { PermissionDeniedException ref = (PermissionDeniedException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); + apiResponse.addProxyObject(idList.get(i)); } } // Also copy over the cserror code and the function/layer in which it was thrown. apiResponse.setCSErrorCode(ref.getCSErrorCode()); } else if (ex instanceof InvalidParameterValueException) { InvalidParameterValueException ref = (InvalidParameterValueException) ex; - ArrayList idList = ref.getIdProxyList(); + ArrayList idList = ref.getIdProxyList(); if (idList != null) { for (int i=0; i < idList.size(); i++) { - IdentityProxy id = idList.get(i); - apiResponse.addProxyObject(id.getTableName(), id.getValue(), id.getidFieldName()); + apiResponse.addProxyObject(idList.get(i)); } } // Also copy over the cserror code and the function/layer in which it was thrown. diff --git a/server/src/com/cloud/api/ApiServlet.java b/server/src/com/cloud/api/ApiServlet.java index 8a1d4de7525..19091f25ff2 100755 --- a/server/src/com/cloud/api/ApiServlet.java +++ b/server/src/com/cloud/api/ApiServlet.java @@ -28,6 +28,8 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ServerApiException; import org.apache.log4j.Logger; import com.cloud.cluster.StackMaid; @@ -36,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; @@ -84,8 +87,8 @@ public class ApiServlet extends HttpServlet { for (String param : paramsInQueryString) { String[] paramTokens = param.split("="); if (paramTokens != null && paramTokens.length == 2) { - String name = param.split("=")[0]; - String value = param.split("=")[1]; + String name = paramTokens[0]; + String value = paramTokens[1]; try { name = URLDecoder.decode(name, "UTF-8"); @@ -97,7 +100,7 @@ public class ApiServlet extends HttpServlet { } params.put(name, new String[] { value }); } else { - s_logger.debug("Invalid paramemter in URL found. param: " + param); + s_logger.debug("Invalid parameter in URL found. param: " + param); } } } @@ -113,15 +116,19 @@ public class ApiServlet extends HttpServlet { Map params = new HashMap(); params.putAll(req.getParameterMap()); - // // For HTTP GET requests, it seems that HttpServletRequest.getParameterMap() actually tries // to unwrap URL encoded content from ISO-9959-1. - // - // After failed in using setCharacterEncoding() to control it, end up with following hacking : for all GET requests, - // we will override it with our-own way of UTF-8 based URL decoding. - // + // After failed in using setCharacterEncoding() to control it, end up with following hacking: + // for all GET requests, we will override it with our-own way of UTF-8 based URL decoding. utf8Fixup(req, params); + // logging the request start and end in management log for easy debugging + String reqStr = ""; + if (s_logger.isDebugEnabled()) { + reqStr = auditTrailSb.toString() + " " + req.getQueryString(); + s_logger.debug("===START=== " + StringUtils.cleanString(reqStr)); + } + try { HttpSession session = req.getSession(false); Object[] responseTypeParam = params.get("response"); @@ -256,7 +263,8 @@ public class ApiServlet extends HttpServlet { } // Do a sanity check here to make sure the user hasn't already been deleted - if ((userId != null) && (account != null) && (accountObj != null) && _apiServer.verifyUser(userId)) { + if ((userId != null) && (account != null) + && (accountObj != null) && _apiServer.verifyUser(userId)) { String[] command = (String[]) params.get("command"); if (command == null) { s_logger.info("missing command, ignoring request..."); @@ -267,9 +275,8 @@ public class ApiServlet extends HttpServlet { } UserContext.updateContext(userId, (Account) accountObj, session.getId()); } else { - // Invalidate the session to ensure we won't allow a request across management server restarts if the userId - // was serialized to the - // stored session + // Invalidate the session to ensure we won't allow a request across management server + // restarts if the userId was serialized to the stored session try { session.invalidate(); } catch (IllegalStateException ise) { @@ -335,6 +342,9 @@ public class ApiServlet extends HttpServlet { } } finally { s_accessLogger.info(auditTrailSb.toString()); + if (s_logger.isDebugEnabled()) { + s_logger.debug("===END=== " + StringUtils.cleanString(reqStr)); + } // cleanup user context to prevent from being peeked in other request context UserContext.unregisterContext(); } @@ -377,12 +387,11 @@ public class ApiServlet extends HttpServlet { StringBuffer sb = new StringBuffer(); int inactiveInterval = session.getMaxInactiveInterval(); - String user_UUID = (String)session.getAttribute("user_UUID"); - session.removeAttribute("user_UUID"); + String user_UUID = (String)session.getAttribute("user_UUID"); + session.removeAttribute("user_UUID"); - String domain_UUID = (String)session.getAttribute("domain_UUID"); - session.removeAttribute("domain_UUID"); - + String domain_UUID = (String)session.getAttribute("domain_UUID"); + session.removeAttribute("domain_UUID"); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { sb.append("{ \"loginresponse\" : { "); @@ -403,10 +412,13 @@ public class ApiServlet extends HttpServlet { } } } - sb.append(" } }"); + sb.append(" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); } else { sb.append(""); - sb.append(""); + sb.append(""); sb.append("" + inactiveInterval + ""); Enumeration attrNames = session.getAttributeNames(); if (attrNames != null) { @@ -433,10 +445,13 @@ public class ApiServlet extends HttpServlet { private String getLogoutSuccessResponse(String responseType) { StringBuffer sb = new StringBuffer(); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { - sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" } }"); + sb.append("{ \"logoutresponse\" : { \"description\" : \"success\" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); } else { sb.append(""); - sb.append(""); + sb.append(""); sb.append("success"); sb.append(""); } diff --git a/server/src/com/cloud/api/IdentityTypeAdapter.java b/server/src/com/cloud/api/IdentityTypeAdapter.java index 0e91a4ee444..369c2020c24 100644 --- a/server/src/com/cloud/api/IdentityTypeAdapter.java +++ b/server/src/com/cloud/api/IdentityTypeAdapter.java @@ -17,7 +17,6 @@ package com.cloud.api; import java.lang.reflect.Type; -import java.util.ArrayList; import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDaoImpl; diff --git a/server/src/com/cloud/api/ResponseObjectTypeAdapter.java b/server/src/com/cloud/api/ResponseObjectTypeAdapter.java index 9c768dc9de6..b49792334f4 100644 --- a/server/src/com/cloud/api/ResponseObjectTypeAdapter.java +++ b/server/src/com/cloud/api/ResponseObjectTypeAdapter.java @@ -19,10 +19,11 @@ package com.cloud.api; import java.lang.reflect.Method; import java.lang.reflect.Type; +import org.apache.cloudstack.api.ResponseObject; import org.apache.log4j.Logger; -import com.cloud.api.response.ExceptionResponse; -import com.cloud.api.response.SuccessResponse; +import org.apache.cloudstack.api.response.ExceptionResponse; +import org.apache.cloudstack.api.response.SuccessResponse; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; diff --git a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java deleted file mode 100644 index 6edd2ab2aec..00000000000 --- a/server/src/com/cloud/api/commands/AddNetworkDeviceCmd.java +++ /dev/null @@ -1,95 +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.api.commands; - -import java.util.Map; - -import org.apache.log4j.Logger; - -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.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="Adds a network device of one of the following types: ExternalDhcp, ExternalFirewall, ExternalLoadBalancer, PxeServer", responseObject = NetworkDeviceResponse.class) -public class AddNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(AddNetworkDeviceCmd.class); - private static final String s_name = "addnetworkdeviceresponse"; - - // /////////////////////////////////////////////////// - // ////////////// API parameters ///////////////////// - // /////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") - private String type; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") - private Map paramList; - - - public String getDeviceType() { - return type; - } - - public Map getParamList() { - return paramList; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - Host device = nwDeviceMgr.addNetworkDevice(this); - NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(device); - response.setObjectName("networkdevice"); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } - -} diff --git a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java index 6bbdde7ecc3..fdbbbe4ca3c 100644 --- a/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/AddTrafficMonitorCmd.java @@ -16,25 +16,21 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.APICommand; import com.cloud.exception.InvalidParameterValueException; import com.cloud.host.Host; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; -import com.cloud.server.api.response.ExternalFirewallResponse; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.exception.CloudRuntimeException; -@Implementation(description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "addTrafficMonitor", description="Adds Traffic Monitor Host for Direct Network Usage", responseObject = TrafficMonitorResponse.class) public class AddTrafficMonitorCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(AddTrafficMonitorCmd.class.getName()); private static final String s_name = "addtrafficmonitorresponse"; @@ -43,18 +39,31 @@ public class AddTrafficMonitorCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="Zone in which to add the external firewall appliance.") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="Zone in which to add the external firewall appliance.") private Long zoneId; - @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; } @@ -82,8 +91,8 @@ public class AddTrafficMonitorCmd extends BaseCmd { try { ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); NetworkUsageManager networkUsageMgr = locator.getManager(NetworkUsageManager.class); - Host trafficMoinitor = networkUsageMgr.addTrafficMonitor(this); - TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMoinitor); + Host trafficMonitor = networkUsageMgr.addTrafficMonitor(this); + TrafficMonitorResponse response = networkUsageMgr.getApiResponse(trafficMonitor); response.setObjectName("trafficmonitor"); response.setResponseName(getCommandName()); this.setResponseObject(response); diff --git a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java deleted file mode 100644 index 7d07a3b0901..00000000000 --- a/server/src/com/cloud/api/commands/DeleteNetworkDeviceCmd.java +++ /dev/null @@ -1,90 +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.api.commands; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.SuccessResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="Deletes network device.", responseObject=SuccessResponse.class) -public class DeleteNetworkDeviceCmd extends BaseCmd { - public static final Logger s_logger = Logger.getLogger(DeleteNetworkDeviceCmd.class); - private static final String s_name = "deletenetworkdeviceresponse"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @IdentityMapper(entityTableName="host") - @Parameter(name = ApiConstants.ID, type = CommandType.LONG, required=true, description = "Id of network device to delete") - private Long id; - - - public Long getId() { - return id; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - boolean result = nwDeviceMgr.deleteNetworkDevice(this); - if (result) { - SuccessResponse response = new SuccessResponse(getCommandName()); - response.setResponseName(getCommandName()); - this.setResponseObject(response); - } else { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Failed to delete network device:" + getId()); - } - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - - } - - @Override - public String getCommandName() { - return s_name; - } - - @Override - public long getEntityOwnerId() { - // TODO Auto-generated method stub - return 0; - } - -} diff --git a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java index 1a4d1ab825d..4c7d3a70546 100644 --- a/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java +++ b/server/src/com/cloud/api/commands/DeleteTrafficMonitorCmd.java @@ -16,22 +16,22 @@ // under the License. package com.cloud.api.commands; +import org.apache.cloudstack.api.response.HostResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.exception.InvalidParameterValueException; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; import com.cloud.user.Account; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class) +@APICommand(name = "deleteTrafficMonitor", description="Deletes an traffic monitor host.", responseObject = SuccessResponse.class) public class DeleteTrafficMonitorCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(DeleteTrafficMonitorCmd.class.getName()); private static final String s_name = "deletetrafficmonitorresponse"; @@ -40,8 +40,8 @@ public class DeleteTrafficMonitorCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="host") - @Parameter(name=ApiConstants.ID, type=CommandType.LONG, required = true, description="Id of the Traffic Monitor Host.") + @Parameter(name=ApiConstants.ID, type=CommandType.UUID, entityType = HostResponse.class, + required = true, description="Id of the Traffic Monitor Host.") private Long id; /////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java index b285775313c..aa3c082ce81 100644 --- a/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GenerateUsageRecordsCmd.java @@ -18,19 +18,16 @@ package com.cloud.api.commands; import java.util.Date; +import org.apache.cloudstack.api.*; +import org.apache.cloudstack.api.response.DomainResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.IdentityMapper; -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.APICommand; +import org.apache.cloudstack.api.response.SuccessResponse; import com.cloud.server.ManagementServerExt; import com.cloud.user.Account; -@Implementation(description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) +@APICommand(name = "generateUsageRecords", description="Generates usage records. This will generate records only if there any records to be generated, i.e if the scheduled usage job was not run or failed", responseObject=SuccessResponse.class) public class GenerateUsageRecordsCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(GenerateUsageRecordsCmd.class.getName()); @@ -40,8 +37,8 @@ public class GenerateUsageRecordsCmd extends BaseCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List events for the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="List events for the specified domain.") private Long domainId; @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") diff --git a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java index 4edcb25760d..60afbd0a8f4 100644 --- a/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java +++ b/server/src/com/cloud/api/commands/GetUsageRecordsCmd.java @@ -23,25 +23,32 @@ import java.util.Date; import java.util.List; import java.util.TimeZone; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.DomainResponse; +import org.apache.cloudstack.api.response.ProjectResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; +import com.cloud.dc.DataCenter; +import com.cloud.domain.Domain; + +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.projects.Project; import com.cloud.server.ManagementServerExt; -import com.cloud.server.api.response.UsageRecordResponse; +import org.apache.cloudstack.api.response.UsageRecordResponse; +import com.cloud.storage.VMTemplateVO; import com.cloud.usage.UsageTypes; import com.cloud.usage.UsageVO; import com.cloud.user.Account; import com.cloud.uuididentity.dao.IdentityDao; import com.cloud.uuididentity.dao.IdentityDaoImpl; +import com.cloud.vm.VMInstanceVO; -@Implementation(description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) +@APICommand(name = "listUsageRecords", description="Lists usage records for accounts", responseObject=UsageRecordResponse.class) public class GetUsageRecordsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(GetUsageRecordsCmd.class.getName()); @@ -54,8 +61,8 @@ public class GetUsageRecordsCmd extends BaseListCmd { @Parameter(name=ApiConstants.ACCOUNT, type=CommandType.STRING, description="List usage records for the specified user.") private String accountName; - @IdentityMapper(entityTableName="domain") - @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.LONG, description="List usage records for the specified domain.") + @Parameter(name=ApiConstants.DOMAIN_ID, type=CommandType.UUID, entityType = DomainResponse.class, + description="List usage records for the specified domain.") private Long domainId; @Parameter(name=ApiConstants.END_DATE, type=CommandType.DATE, required=true, description="End date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-03.") @@ -63,15 +70,15 @@ public class GetUsageRecordsCmd extends BaseListCmd { @Parameter(name=ApiConstants.START_DATE, type=CommandType.DATE, required=true, description="Start date range for usage record query. Use yyyy-MM-dd as the date format, e.g. startDate=2009-06-01.") private Date startDate; - - @IdentityMapper(entityTableName="account") - @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.LONG, description="List usage records for the specified account") + + @Parameter(name=ApiConstants.ACCOUNT_ID, type=CommandType.UUID, entityType = AccountResponse.class, + description="List usage records for the specified account") private Long accountId; - - @IdentityMapper(entityTableName="projects") - @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.LONG, description="List usage records for specified project") + + @Parameter(name=ApiConstants.PROJECT_ID, type=CommandType.UUID, entityType = ProjectResponse.class, + description="List usage records for specified project") private Long projectId; - + @Parameter(name=ApiConstants.TYPE, type=CommandType.LONG, description="List usage records for the specified usage type") private Long usageType; @@ -94,7 +101,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { public Date getStartDate() { return startDate; } - + public Long getAccountId() { return accountId; } @@ -102,11 +109,11 @@ public class GetUsageRecordsCmd extends BaseListCmd { public Long getUsageType() { return usageType; } - + public Long getProjectId() { return projectId; } - + ///////////////////////////////////////////////////// /////////////// Misc parameters /////////////////// ///////////////////////////////////////////////////// @@ -162,7 +169,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { } else { sb.append(hour+":"); } - + int minute = cal.get(Calendar.MINUTE); if (minute < 10) { sb.append("0" + minute + ":"); @@ -213,7 +220,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { return sb.toString(); } - + @Override public void execute(){ ManagementServerExt _mgrExt = (ManagementServerExt)_mgr; @@ -225,28 +232,46 @@ public class GetUsageRecordsCmd extends BaseListCmd { UsageRecordResponse usageRecResponse = new UsageRecordResponse(); if (usageRecordGeneric instanceof UsageVO) { UsageVO usageRecord = (UsageVO)usageRecordGeneric; - - Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId()); + + Account account = ApiDBUtils.findAccountByIdIncludingRemoved(usageRecord.getAccountId()); if (account.getType() == Account.ACCOUNT_TYPE_PROJECT) { //find the project Project project = ApiDBUtils.findProjectByProjectAccountId(account.getId()); - usageRecResponse.setProjectId(project.getId()); + usageRecResponse.setProjectId(project.getUuid()); usageRecResponse.setProjectName(project.getName()); } else { - usageRecResponse.setAccountId(account.getId()); + usageRecResponse.setAccountId(account.getUuid()); usageRecResponse.setAccountName(account.getAccountName()); } - - usageRecResponse.setDomainId(usageRecord.getDomainId()); - - usageRecResponse.setZoneId(usageRecord.getZoneId()); + + Domain domain = ApiDBUtils.findDomainById(usageRecord.getDomainId()); + if (domain != null) { + usageRecResponse.setDomainId(domain.getUuid()); + } + + if (usageRecord.getZoneId() != null) { + DataCenter zone = ApiDBUtils.findZoneById(usageRecord.getZoneId()); + if (zone != null) { + usageRecResponse.setZoneId(zone.getUuid()); + } + } usageRecResponse.setDescription(usageRecord.getDescription()); usageRecResponse.setUsage(usageRecord.getUsageDisplay()); usageRecResponse.setUsageType(usageRecord.getUsageType()); - usageRecResponse.setVirtualMachineId(usageRecord.getVmInstanceId()); + if (usageRecord.getVmInstanceId() != null) { + VMInstanceVO vm = ApiDBUtils.findVMInstanceById(usageRecord.getVmInstanceId()); + if (vm != null) { + usageRecResponse.setVirtualMachineId(vm.getUuid()); + } + } usageRecResponse.setVmName(usageRecord.getVmName()); - usageRecResponse.setTemplateId(usageRecord.getTemplateId()); - + if (usageRecord.getTemplateId() != null) { + VMTemplateVO template = ApiDBUtils.findTemplateById(usageRecord.getTemplateId()); + if (template != null) { + usageRecResponse.setTemplateId(template.getUuid()); + } + } + if(usageRecord.getUsageType() == UsageTypes.RUNNING_VM || usageRecord.getUsageType() == UsageTypes.ALLOCATED_VM){ //Service Offering Id usageRecResponse.setOfferingId(identityDao.getIdentityUuid("disk_offering", usageRecord.getOfferingId().toString())); @@ -254,7 +279,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString())); //Hypervisor Type usageRecResponse.setType(usageRecord.getType()); - + } else if(usageRecord.getUsageType() == UsageTypes.IP_ADDRESS){ //isSourceNAT usageRecResponse.setSourceNat((usageRecord.getType().equals("SourceNat"))?true:false); @@ -262,7 +287,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setSystem((usageRecord.getSize() == 1)?true:false); //IP Address ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("user_ip_address", usageRecord.getUsageId().toString())); - + } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_SENT || usageRecord.getUsageType() == UsageTypes.NETWORK_BYTES_RECEIVED){ //Device Type usageRecResponse.setType(usageRecord.getType()); @@ -271,11 +296,11 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_instance", usageRecord.getUsageId().toString())); } else { //External Device Host Id - usageRecResponse.setUsageId(identityDao.getIdentityUuid("host", usageRecord.getUsageId().toString())); + usageRecResponse.setUsageId(identityDao.getIdentityUuid("host", usageRecord.getUsageId().toString())); } //Network ID usageRecResponse.setNetworkId(identityDao.getIdentityUuid("networks", usageRecord.getNetworkId().toString())); - + } else if(usageRecord.getUsageType() == UsageTypes.VOLUME){ //Volume ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("volumes", usageRecord.getUsageId().toString())); @@ -291,36 +316,36 @@ public class GetUsageRecordsCmd extends BaseListCmd { usageRecResponse.setUsageId(identityDao.getIdentityUuid("vm_template", usageRecord.getUsageId().toString())); //Template/ISO Size usageRecResponse.setSize(usageRecord.getSize()); - + } else if(usageRecord.getUsageType() == UsageTypes.SNAPSHOT){ //Snapshot ID usageRecResponse.setUsageId(identityDao.getIdentityUuid("snapshots", usageRecord.getUsageId().toString())); //Snapshot Size usageRecResponse.setSize(usageRecord.getSize()); - + } else if(usageRecord.getUsageType() == UsageTypes.LOAD_BALANCER_POLICY){ //Load Balancer Policy ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.PORT_FORWARDING_RULE){ //Port Forwarding Rule ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.NETWORK_OFFERING){ //Network Offering Id usageRecResponse.setOfferingId(identityDao.getIdentityUuid("network_offerings", usageRecord.getOfferingId().toString())); //is Default usageRecResponse.setDefault((usageRecord.getUsageId() == 1)? true:false); - + } else if(usageRecord.getUsageType() == UsageTypes.VPN_USERS){ //VPN User ID usageRecResponse.setUsageId(usageRecord.getUsageId().toString()); - + } else if(usageRecord.getUsageType() == UsageTypes.SECURITY_GROUP){ //Security Group Id usageRecResponse.setUsageId(identityDao.getIdentityUuid("security_group", usageRecord.getUsageId().toString())); } - + if (usageRecord.getRawUsage() != null) { DecimalFormat decimalFormat = new DecimalFormat("###########.######"); usageRecResponse.setRawUsage(decimalFormat.format(usageRecord.getRawUsage())); @@ -332,7 +357,7 @@ public class GetUsageRecordsCmd extends BaseListCmd { if (usageRecord.getEndDate() != null) { usageRecResponse.setEndDate(getDateStringInternal(usageRecord.getEndDate())); } - } + } usageRecResponse.setObjectName("usagerecord"); usageResponses.add(usageRecResponse); diff --git a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java b/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java deleted file mode 100644 index fc583c15f7b..00000000000 --- a/server/src/com/cloud/api/commands/ListNetworkDeviceCmd.java +++ /dev/null @@ -1,99 +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.api.commands; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; - -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseCmd; -import com.cloud.api.BaseListCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.ServerApiException; -import com.cloud.api.response.ListResponse; -import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.InsufficientCapacityException; -import com.cloud.exception.InvalidParameterValueException; -import com.cloud.exception.ResourceAllocationException; -import com.cloud.exception.ResourceUnavailableException; -import com.cloud.host.Host; -import com.cloud.network.ExternalNetworkDeviceManager; -import com.cloud.server.ManagementService; -import com.cloud.server.api.response.NetworkDeviceResponse; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.exception.CloudRuntimeException; - -@Implementation(description="List network devices", responseObject = NetworkDeviceResponse.class) -public class ListNetworkDeviceCmd extends BaseListCmd { - public static final Logger s_logger = Logger.getLogger(ListNetworkDeviceCmd.class); - private static final String s_name = "listnetworkdevice"; - - ///////////////////////////////////////////////////// - //////////////// API parameters ///////////////////// - ///////////////////////////////////////////////////// - - @Parameter(name = ApiConstants.NETWORK_DEVICE_TYPE, type = CommandType.STRING, description = "Network device type, now supports ExternalDhcp, PxeServer, NetscalerMPXLoadBalancer, NetscalerVPXLoadBalancer, NetscalerSDXLoadBalancer, F5BigIpLoadBalancer, JuniperSRXFirewall") - private String type; - - @Parameter(name = ApiConstants.NETWORK_DEVICE_PARAMETER_LIST, type = CommandType.MAP, description = "parameters for network device") - private Map paramList; - - public String getDeviceType() { - return type; - } - - public Map getParamList() { - return paramList; - } - - @Override - public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException, - ResourceAllocationException { - try { - ExternalNetworkDeviceManager nwDeviceMgr; - ComponentLocator locator = ComponentLocator.getLocator(ManagementService.Name); - nwDeviceMgr = locator.getManager(ExternalNetworkDeviceManager.class); - List devices = nwDeviceMgr.listNetworkDevice(this); - List nwdeviceResponses = new ArrayList(); - ListResponse listResponse = new ListResponse(); - for (Host d : devices) { - NetworkDeviceResponse response = nwDeviceMgr.getApiResponse(d); - response.setObjectName("networkdevice"); - response.setResponseName(getCommandName()); - nwdeviceResponses.add(response); - } - - listResponse.setResponses(nwdeviceResponses); - listResponse.setResponseName(getCommandName()); - this.setResponseObject(listResponse); - } catch (InvalidParameterValueException ipve) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, ipve.getMessage()); - } catch (CloudRuntimeException cre) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, cre.getMessage()); - } - } - - @Override - public String getCommandName() { - return s_name; - } - -} diff --git a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java index 78338d86710..21ad339137a 100644 --- a/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java +++ b/server/src/com/cloud/api/commands/ListTrafficMonitorsCmd.java @@ -19,22 +19,22 @@ package com.cloud.api.commands; import java.util.ArrayList; import java.util.List; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.response.ZoneResponse; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; -import com.cloud.api.BaseListCmd; -import com.cloud.api.IdentityMapper; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseListCmd; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.Parameter; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.host.Host; import com.cloud.network.NetworkUsageManager; import com.cloud.server.ManagementService; -import com.cloud.server.api.response.ExternalFirewallResponse; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.utils.component.ComponentLocator; -@Implementation(description="List traffic monitor Hosts.", responseObject = ExternalFirewallResponse.class) +@APICommand(name = "listTrafficMonitors", description="List traffic monitor Hosts.", responseObject = TrafficMonitorResponse.class) public class ListTrafficMonitorsCmd extends BaseListCmd { public static final Logger s_logger = Logger.getLogger(ListServiceOfferingsCmd.class.getName()); private static final String s_name = "listtrafficmonitorsresponse"; @@ -43,11 +43,10 @@ public class ListTrafficMonitorsCmd extends BaseListCmd { //////////////// API parameters ///////////////////// ///////////////////////////////////////////////////// - @IdentityMapper(entityTableName="data_center") - @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.LONG, required = true, description="zone Id") + @Parameter(name=ApiConstants.ZONE_ID, type=CommandType.UUID, entityType = ZoneResponse.class, + required = true, description="zone Id") private long zoneId; - ///////////////////////////////////////////////////// /////////////////// Accessors /////////////////////// ///////////////////////////////////////////////////// diff --git a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java b/server/src/com/cloud/api/commands/ListUsageTypesCmd.java index b60807c24a8..dfa5dc1bb20 100644 --- a/server/src/com/cloud/api/commands/ListUsageTypesCmd.java +++ b/server/src/com/cloud/api/commands/ListUsageTypesCmd.java @@ -18,16 +18,16 @@ package com.cloud.api.commands; import java.util.List; +import org.apache.cloudstack.api.APICommand; import org.apache.log4j.Logger; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.response.ListResponse; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.response.ListResponse; import com.cloud.server.ManagementServerExt; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.user.Account; -@Implementation(description = "List Usage Types", responseObject = UsageTypeResponse.class) +@APICommand(name = "listUsageTypes", description = "List Usage Types", responseObject = UsageTypeResponse.class) public class ListUsageTypesCmd extends BaseCmd { public static final Logger s_logger = Logger.getLogger(ListUsageTypesCmd.class.getName()); private static final String s_name = "listusagetypesresponse"; diff --git a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java index d31ef5a8a5f..b493ec4b29c 100644 --- a/server/src/com/cloud/api/doc/ApiXmlDocWriter.java +++ b/server/src/com/cloud/api/doc/ApiXmlDocWriter.java @@ -24,48 +24,35 @@ import java.io.FileWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Properties; -import java.util.TreeMap; +import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; +import org.apache.cloudstack.api.*; import org.apache.log4j.Logger; import com.cloud.alert.AlertManager; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseAsyncCreateCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.Implementation; -import com.cloud.api.Parameter; -import com.cloud.api.response.AsyncJobResponse; -import com.cloud.api.response.BaseResponse; -import com.cloud.api.response.HostResponse; -import com.cloud.api.response.IPAddressResponse; -import com.cloud.api.response.LoadBalancerResponse; -import com.cloud.api.response.SecurityGroupResponse; -import com.cloud.api.response.SnapshotResponse; -import com.cloud.api.response.StoragePoolResponse; -import com.cloud.api.response.TemplateResponse; -import com.cloud.api.response.UserVmResponse; -import com.cloud.api.response.VolumeResponse; +import org.apache.cloudstack.api.APICommand; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.IPAddressResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SnapshotResponse; +import org.apache.cloudstack.api.response.StoragePoolResponse; +import org.apache.cloudstack.api.response.TemplateResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; import com.cloud.serializer.Param; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; import com.google.gson.annotations.SerializedName; import com.thoughtworks.xstream.XStream; +import org.reflections.Reflections; public class ApiXmlDocWriter { public static final Logger s_logger = Logger.getLogger(ApiXmlDocWriter.class.getName()); private static final short DOMAIN_ADMIN_COMMAND = 4; private static final short USER_COMMAND = 8; + private static Map> _apiNameCmdClassMap = new HashMap>(); private static LinkedHashMap all_api_commands = new LinkedHashMap(); private static LinkedHashMap domain_admin_api_commands = new LinkedHashMap(); private static LinkedHashMap regular_user_api_commands = new LinkedHashMap(); @@ -92,6 +79,16 @@ public class ApiXmlDocWriter { } public static void main(String[] args) { + // Populate api name and cmd class mappings + Reflections reflections = new Reflections("org.apache.cloudstack.api"); + Set> cmdClasses = reflections.getTypesAnnotatedWith(APICommand.class); + reflections = new Reflections("com.cloud.api"); + cmdClasses.addAll(reflections.getTypesAnnotatedWith(APICommand.class)); + for(Class cmdClass: cmdClasses) { + String apiName = cmdClass.getAnnotation(APICommand.class).name(); + _apiNameCmdClassMap.put(apiName, cmdClass); + } + LinkedProperties preProcessedCommands = new LinkedProperties(); String[] fileNames = null; @@ -131,13 +128,19 @@ public class ApiXmlDocWriter { while (propertiesIterator.hasNext()) { String key = (String) propertiesIterator.next(); String preProcessedCommand = preProcessedCommands.getProperty(key); - String[] commandParts = preProcessedCommand.split(";"); - String commandName = commandParts[0]; + int splitIndex = preProcessedCommand.lastIndexOf(";"); + String commandRoleMask = preProcessedCommand.substring(splitIndex + 1); + Class cmdClass = _apiNameCmdClassMap.get(key); + if (cmdClass == null) { + System.out.println("Check, Null Value for key: " + key + " preProcessedCommand=" + preProcessedCommand); + continue; + } + String commandName = cmdClass.getName(); all_api_commands.put(key, commandName); short cmdPermissions = 1; - if (commandParts.length > 1 && commandParts[1] != null) { - cmdPermissions = Short.parseShort(commandParts[1]); + if (commandRoleMask != null) { + cmdPermissions = Short.parseShort(commandRoleMask); } if ((cmdPermissions & DOMAIN_ADMIN_COMMAND) != 0) { @@ -309,9 +312,14 @@ public class ApiXmlDocWriter { Command apiCommand = new Command(); apiCommand.setName(command); - Implementation impl = clas.getAnnotation(Implementation.class); + APICommand impl = clas.getAnnotation(APICommand.class); if (impl == null) { - impl = clas.getSuperclass().getAnnotation(Implementation.class); + impl = clas.getSuperclass().getAnnotation(APICommand.class); + } + + if (impl == null) { + throw new IllegalStateException(String.format("An %1$s annotation is required for class %2$s.", + APICommand.class.getCanonicalName(), clas.getCanonicalName())); } if (impl.includeInApiDoc()) { diff --git a/server/src/com/cloud/api/query/QueryManagerImpl.java b/server/src/com/cloud/api/query/QueryManagerImpl.java new file mode 100644 index 00000000000..ceec932f942 --- /dev/null +++ b/server/src/com/cloud/api/query/QueryManagerImpl.java @@ -0,0 +1,1792 @@ +// 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.query; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.api.command.admin.host.ListHostsCmd; +import org.apache.cloudstack.api.command.admin.router.ListRoutersCmd; +import org.apache.cloudstack.api.command.admin.user.ListUsersCmd; +import org.apache.cloudstack.api.command.user.account.ListAccountsCmd; +import org.apache.cloudstack.api.command.user.account.ListProjectAccountsCmd; +import org.apache.cloudstack.api.command.user.event.ListEventsCmd; +import org.apache.cloudstack.api.command.user.job.ListAsyncJobsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectInvitationsCmd; +import org.apache.cloudstack.api.command.user.project.ListProjectsCmd; +import org.apache.cloudstack.api.command.user.securitygroup.ListSecurityGroupsCmd; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vmgroup.ListVMGroupsCmd; +import org.apache.cloudstack.api.command.user.volume.ListVolumesCmd; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.cloudstack.query.QueryService; +import org.apache.log4j.Logger; + +import com.cloud.api.query.dao.AccountJoinDao; +import com.cloud.api.query.dao.AsyncJobJoinDao; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.HostJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.dao.VolumeJoinDao; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.domain.Domain; +import com.cloud.domain.DomainVO; +import com.cloud.domain.dao.DomainDao; +import com.cloud.event.dao.EventJoinDao; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.PermissionDeniedException; +import com.cloud.ha.HighAvailabilityManager; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.network.security.dao.SecurityGroupVMMapDao; +import com.cloud.projects.ProjectInvitation; +import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.projects.Project; +import com.cloud.projects.ProjectManager; +import com.cloud.projects.dao.ProjectAccountDao; +import com.cloud.projects.dao.ProjectDao; +import com.cloud.server.Criteria; +import com.cloud.storage.Volume; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.AccountVO; +import com.cloud.user.UserContext; +import com.cloud.user.dao.AccountDao; +import com.cloud.utils.DateUtil; +import com.cloud.utils.Pair; +import com.cloud.utils.Ternary; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; +import com.cloud.utils.db.SearchCriteria.Op; +import com.cloud.vm.UserVmVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.UserVmDao; + +/** + * @author minc + * + */ +@Local(value = {QueryService.class }) +public class QueryManagerImpl implements QueryService, Manager { + + public static final Logger s_logger = Logger.getLogger(QueryManagerImpl.class); + + private String _name; + + // public static ViewResponseHelper _responseGenerator; + + @Inject + private AccountManager _accountMgr; + + @Inject + private ProjectManager _projectMgr; + + @Inject + private DomainDao _domainDao; + + @Inject + private UserAccountJoinDao _userAccountJoinDao; + + @Inject + private EventJoinDao _eventJoinDao; + + @Inject + private ResourceTagJoinDao _resourceTagJoinDao; + + @Inject + private InstanceGroupJoinDao _vmGroupJoinDao; + + @Inject + private UserVmJoinDao _userVmJoinDao; + + @Inject + private UserVmDao _userVmDao; + + @Inject + private SecurityGroupJoinDao _securityGroupJoinDao; + + @Inject + private SecurityGroupVMMapDao _securityGroupVMMapDao; + + @Inject + private DomainRouterJoinDao _routerJoinDao; + + @Inject + private ProjectInvitationJoinDao _projectInvitationJoinDao; + + @Inject + private ProjectJoinDao _projectJoinDao; + + @Inject + private ProjectDao _projectDao; + + @Inject + private ProjectAccountDao _projectAccountDao; + + @Inject + private ProjectAccountJoinDao _projectAccountJoinDao; + + @Inject + private HostJoinDao _hostJoinDao; + + @Inject + private VolumeJoinDao _volumeJoinDao; + + @Inject + private AccountDao _accountDao; + + @Inject + private AccountJoinDao _accountJoinDao; + + @Inject + private AsyncJobJoinDao _jobJoinDao; + + @Inject + private HighAvailabilityManager _haMgr; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + // _responseGenerator = new ViewResponseHelper(); + return false; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + /* (non-Javadoc) + * @see com.cloud.api.query.QueryService#searchForUsers(org.apache.cloudstack.api.command.admin.user.ListUsersCmd) + */ + @Override + public ListResponse searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { + Pair, Integer> result = searchForUsersInternal(cmd); + ListResponse response = new ListResponse(); + List userResponses = ViewResponseHelper.createUserResponse(result.first().toArray(new UserAccountJoinVO[result.first().size()])); + response.setResponses(userResponses, result.second()); + return response; + } + + private Pair, Integer> searchForUsersInternal(ListUsersCmd cmd) throws PermissionDeniedException { + Account caller = UserContext.current().getCaller(); + + //TODO: Integrate with ACL checkAccess refactoring + Long domainId = cmd.getDomainId(); + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); + } + + _accountMgr.checkAccess(caller, domain); + } else { + // default domainId to the caller's domain + domainId = caller.getDomainId(); + } + + Filter searchFilter = new Filter(UserAccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + Long id = cmd.getId(); + Object username = cmd.getUsername(); + Object type = cmd.getAccountType(); + Object accountName = cmd.getAccountName(); + Object state = cmd.getState(); + Object keyword = cmd.getKeyword(); + + SearchBuilder sb = _userAccountJoinDao.createSearchBuilder(); + sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE); + if (id != null && id == 1) { + // system user should NOT be searchable + List emptyList = new ArrayList(); + return new Pair, Integer>(emptyList, 0); + } else if (id != null) { + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + } else { + // this condition is used to exclude system user from the search results + sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ); + } + + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + + if ((accountName == null) && (domainId != null)) { + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + SearchCriteria sc = sb.create(); + if (keyword != null) { + SearchCriteria ssc = _userAccountJoinDao.createSearchCriteria(); + ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("username", SearchCriteria.Op.SC, ssc); + } + + if (username != null) { + sc.setParameters("username", username); + } + + if (id != null) { + sc.setParameters("id", id); + } else { + // Don't return system user, search builder with NEQ + sc.setParameters("id", 1); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + if (domainId != null) { + sc.setParameters("domainId", domainId); + } + } else if (domainId != null) { + DomainVO domainVO = _domainDao.findById(domainId); + sc.setParameters("domainPath", domainVO.getPath() + "%"); + } + + if (state != null) { + sc.setParameters("state", state); + } + + return _userAccountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForEvents(ListEventsCmd cmd) { + Pair, Integer> result = searchForEventsInternal(cmd); + ListResponse response = new ListResponse(); + List eventResponses = ViewResponseHelper.createEventResponse(result.first().toArray(new EventJoinVO[result.first().size()])); + response.setResponses(eventResponses, result.second()); + return response; + } + + private Pair, Integer> searchForEventsInternal(ListEventsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Long id = cmd.getId(); + String type = cmd.getType(); + String level = cmd.getLevel(); + Date startDate = cmd.getStartDate(); + Date endDate = cmd.getEndDate(); + String keyword = cmd.getKeyword(); + Integer entryTime = cmd.getEntryTime(); + Integer duration = cmd.getDuration(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(EventJoinVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _eventJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); + sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); + sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ); + sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); + sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); + + SearchCriteria sc = sb.create(); + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (id != null) { + sc.setParameters("id", id); + } + + if (keyword != null) { + SearchCriteria ssc = _eventJoinDao.createSearchCriteria(); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("level", SearchCriteria.Op.SC, ssc); + } + + if (level != null) { + sc.setParameters("levelEQ", level); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (startDate != null && endDate != null) { + sc.setParameters("createDateB", startDate, endDate); + } else if (startDate != null) { + sc.setParameters("createDateG", startDate); + } else if (endDate != null) { + sc.setParameters("createDateL", endDate); + } + + Pair, Integer> eventPair = null; + // event_view will not have duplicate rows for each event, so searchAndCount should be good enough. + if ((entryTime != null) && (duration != null)) { + // TODO: waiting for response from dev list, logic is mystery to + // me!! + /* + * if (entryTime <= duration) { throw new + * InvalidParameterValueException + * ("Entry time must be greater than duration"); } Calendar calMin = + * Calendar.getInstance(); Calendar calMax = Calendar.getInstance(); + * calMin.add(Calendar.SECOND, -entryTime); + * calMax.add(Calendar.SECOND, -duration); Date minTime = + * calMin.getTime(); Date maxTime = calMax.getTime(); + * + * sc.setParameters("state", com.cloud.event.Event.State.Completed); + * sc.setParameters("startId", 0); sc.setParameters("createDate", + * minTime, maxTime); List startedEvents = + * _eventJoinDao.searchAllEvents(sc, searchFilter); + * List pendingEvents = new ArrayList(); + * for (EventVO event : startedEvents) { EventVO completedEvent = + * _eventDao.findCompletedEvent(event.getId()); if (completedEvent + * == null) { pendingEvents.add(event); } } return pendingEvents; + */ + } else { + eventPair = _eventJoinDao.searchAndCount(sc, searchFilter); + } + return eventPair; + + } + + @Override + public ListResponse listTags(ListTagsCmd cmd) { + Pair, Integer> tags = listTagsInternal(cmd); + ListResponse response = new ListResponse(); + List tagResponses = ViewResponseHelper.createResourceTagResponse(false, tags.first().toArray(new ResourceTagJoinVO[tags.first().size()])); + response.setResponses(tagResponses, tags.second()); + return response; + } + + private Pair, Integer> listTagsInternal(ListTagsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String key = cmd.getKey(); + String value = cmd.getValue(); + String resourceId = cmd.getResourceId(); + String resourceType = cmd.getResourceType(); + String customerName = cmd.getCustomer(); + boolean listAll = cmd.listAll(); + + Ternary domainIdRecursiveListProject = + new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), + cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(ResourceTagJoinVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + + SearchBuilder sb = _resourceTagJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); + sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); + + if (resourceId != null) { + sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); + sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); + sb.cp(); + } + + sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); + sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); + + // now set the SC criteria... + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (key != null) { + sc.setParameters("key", key); + } + + if (value != null) { + sc.setParameters("value", value); + } + + if (resourceId != null) { + sc.setParameters("resourceId", resourceId); + sc.setParameters("resourceUuid", resourceId); + } + + if (resourceType != null) { + sc.setParameters("resourceType", resourceType); + } + + if (customerName != null) { + sc.setParameters("customer", customerName); + } + + Pair, Integer> result = _resourceTagJoinDao.searchAndCount(sc, searchFilter); + return result; + } + + + + @Override + public ListResponse searchForVmGroups(ListVMGroupsCmd cmd) { + Pair, Integer> groups = searchForVmGroupsInternal(cmd); + ListResponse response = new ListResponse(); + List grpResponses = ViewResponseHelper.createInstanceGroupResponse(groups.first().toArray(new InstanceGroupJoinVO[groups.first().size()])); + response.setResponses(grpResponses, groups.second()); + return response; + } + + private Pair, Integer> searchForVmGroupsInternal(ListVMGroupsCmd cmd) { + Long id = cmd.getId(); + String name = cmd.getGroupName(); + String keyword = cmd.getKeyword(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(InstanceGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + SearchBuilder sb = _vmGroupJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _vmGroupJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + + if (id != null) { + sc.setParameters("id", id); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + return _vmGroupJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForUserVMs(ListVMsCmd cmd) { + Pair, Integer> result = searchForUserVMsInternal(cmd); + ListResponse response = new ListResponse(); + List vmResponses = ViewResponseHelper.createUserVmResponse("virtualmachine", cmd.getDetails(), result.first().toArray(new UserVmJoinVO[result.first().size()])); + response.setResponses(vmResponses, result.second()); + return response; + } + + private Pair, Integer> searchForUserVMsInternal(ListVMsCmd cmd) { + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + String hypervisor = cmd.getHypervisor(); + boolean listAll = cmd.listAll(); + Long id = cmd.getId(); + Map tags = cmd.getTags(); + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); + //Criteria c = new Criteria(null, Boolean.FALSE, cmd.getStartIndex(), cmd.getPageSizeVal()); //version without default sorting + c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); + c.addCriteria(Criteria.ID, cmd.getId()); + c.addCriteria(Criteria.NAME, cmd.getInstanceName()); + c.addCriteria(Criteria.STATE, cmd.getState()); + c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId()); + c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); + c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); + c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); + c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId()); + c.addCriteria(Criteria.ISO_ID, cmd.getIsoId()); + c.addCriteria(Criteria.VPC_ID, cmd.getVpcId()); + + if (domainId != null) { + c.addCriteria(Criteria.DOMAINID, domainId); + } + + if (HypervisorType.getType(hypervisor) != HypervisorType.None) { + c.addCriteria(Criteria.HYPERVISOR, hypervisor); + } else if (hypervisor != null) { + throw new InvalidParameterValueException("Invalid HypervisorType " + hypervisor); + } + + // ignore these search requests if it's not an admin + if (_accountMgr.isAdmin(caller.getType())) { + c.addCriteria(Criteria.PODID, cmd.getPodId()); + c.addCriteria(Criteria.HOSTID, cmd.getHostId()); + c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId()); + } + + if (!permittedAccounts.isEmpty()) { + c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray()); + } + c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType())); + + return searchForUserVMsByCriteria(c, caller, domainId, isRecursive, + permittedAccounts, listAll, listProjectResourcesCriteria, tags); + } + + + private Pair, Integer> searchForUserVMsByCriteria(Criteria c, Account caller, Long domainId, boolean isRecursive, + List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); + + //first search distinct vm id by using query criteria and pagination + SearchBuilder sb = _userVmJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + Object id = c.getCriteria(Criteria.ID); + Object name = c.getCriteria(Criteria.NAME); + Object state = c.getCriteria(Criteria.STATE); + Object notState = c.getCriteria(Criteria.NOTSTATE); + Object zone = c.getCriteria(Criteria.DATACENTERID); + Object pod = c.getCriteria(Criteria.PODID); + Object hostId = c.getCriteria(Criteria.HOSTID); + Object hostName = c.getCriteria(Criteria.HOSTNAME); + Object keyword = c.getCriteria(Criteria.KEYWORD); + Object isAdmin = c.getCriteria(Criteria.ISADMIN); + assert c.getCriteria(Criteria.IPADDRESS) == null : "We don't support search by ip address on VM any more. If you see this assert, it means we have to find a different way to search by the nic table."; + Object groupId = c.getCriteria(Criteria.GROUPID); + Object networkId = c.getCriteria(Criteria.NETWORKID); + Object hypervisor = c.getCriteria(Criteria.HYPERVISOR); + Object storageId = c.getCriteria(Criteria.STORAGE_ID); + Object templateId = c.getCriteria(Criteria.TEMPLATE_ID); + Object isoId = c.getCriteria(Criteria.ISO_ID); + Object vpcId = c.getCriteria(Criteria.VPC_ID); + + sb.and("displayName", sb.entity().getDisplayName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); + sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); + sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ); + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); + + if (groupId != null && (Long) groupId != -1) { + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); + } + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + if (networkId != null) { + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); + } + + if(vpcId != null && networkId == null){ + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + } + + if (storageId != null) { + sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ); + } + + // populate the search criteria with the values passed in + SearchCriteria sc = sb.create(); + + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (groupId != null && (Long)groupId != -1) { + sc.setParameters("instanceGroupId", groupId); + } + + if (keyword != null) { + SearchCriteria ssc = _userVmJoinDao.createSearchCriteria(); + ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.EQ, keyword); + + sc.addAnd("displayName", SearchCriteria.Op.SC, ssc); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (templateId != null) { + sc.setParameters("templateId", templateId); + } + + if (isoId != null) { + sc.setParameters("isoId", isoId); + } + + if (networkId != null) { + sc.setParameters("networkId", networkId); + } + + if(vpcId != null && networkId == null){ + sc.setParameters("vpcId", vpcId); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + if (state != null) { + if (notState != null && (Boolean) notState == true) { + sc.setParameters("stateNEQ", state); + } else { + sc.setParameters("stateEQ", state); + } + } + + if (hypervisor != null) { + sc.setParameters("hypervisorType", hypervisor); + } + + // Don't show Destroyed and Expunging vms to the end user + if ((isAdmin != null) && ((Boolean) isAdmin != true)) { + sc.setParameters("stateNIN", "Destroyed", "Expunging"); + } + + if (zone != null) { + sc.setParameters("dataCenterId", zone); + + if (state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } + } + if (pod != null) { + sc.setParameters("podId", pod); + + if (state == null) { + sc.setParameters("stateNEQ", "Destroyed"); + } + } + + if (hostId != null) { + sc.setParameters("hostIdEQ", hostId); + } else { + if (hostName != null) { + sc.setParameters("hostName", hostName); + } + } + + if (storageId != null) { + sc.setParameters("poolId", storageId); + } + + // search vm details by ids + Pair, Integer> uniqueVmPair = _userVmJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVmPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueVmPair; + } + List uniqueVms = uniqueVmPair.first(); + Long[] vmIds = new Long[uniqueVms.size()]; + int i = 0; + for (UserVmJoinVO v : uniqueVms ){ + vmIds[i++] = v.getId(); + } + List vms = _userVmJoinDao.searchByIds(vmIds); + return new Pair, Integer>(vms, count); + } + + + @Override + public ListResponse searchForSecurityGroups(ListSecurityGroupsCmd cmd) { + Pair, Integer> result = searchForSecurityGroupsInternal(cmd); + ListResponse response = new ListResponse(); + List routerResponses = ViewResponseHelper.createSecurityGroupResponses(result.first()); + response.setResponses(routerResponses, result.second()); + return response; + } + + private Pair, Integer> searchForSecurityGroupsInternal(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { + Account caller = UserContext.current().getCaller(); + Long instanceId = cmd.getVirtualMachineId(); + String securityGroup = cmd.getSecurityGroupName(); + Long id = cmd.getId(); + Object keyword = cmd.getKeyword(); + List permittedAccounts = new ArrayList(); + Map tags = cmd.getTags(); + + if (instanceId != null) { + UserVmVO userVM = _userVmDao.findById(instanceId); + if (userVM == null) { + throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); + } + _accountMgr.checkAccess(caller, null, true, userVM); + return listSecurityGroupRulesByVM(instanceId.longValue(), cmd.getStartIndex(), cmd.getPageSizeVal()); + } + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(SecurityGroupJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _securityGroupJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (id != null) { + sc.setParameters("id", id); + } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (securityGroup != null) { + sc.setParameters("name", securityGroup); + } + + if (keyword != null) { + SearchCriteria ssc = _securityGroupJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + // search security group together with rules + Pair, Integer> uniqueSgPair = _securityGroupJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueSgPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueSgPair; + } + + List uniqueSgs = uniqueSgPair.first(); + Long[] sgIds = new Long[uniqueSgs.size()]; + int i = 0; + for (SecurityGroupJoinVO v : uniqueSgs ){ + sgIds[i++] = v.getId(); + } + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); + } + + private Pair, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) { + Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize); + Pair, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf); + Integer count = sgVmMappingPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return new Pair, Integer>(new ArrayList(), count); + } + List sgVmMappings = sgVmMappingPair.first(); + Long[] sgIds = new Long[sgVmMappings.size()]; + int i = 0; + for (SecurityGroupVMMapVO sgVm : sgVmMappings) { + sgIds[i++] = sgVm.getSecurityGroupId(); + } + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); + } + + + @Override + public ListResponse searchForRouters(ListRoutersCmd cmd) { + Pair, Integer> result = searchForRoutersInternal(cmd); + ListResponse response = new ListResponse(); + + List routerResponses = ViewResponseHelper.createDomainRouterResponse(result.first().toArray(new DomainRouterJoinVO[result.first().size()])); + response.setResponses(routerResponses, result.second()); + return response; + } + + + private Pair, Integer> searchForRoutersInternal(ListRoutersCmd cmd) { + Long id = cmd.getId(); + String name = cmd.getRouterName(); + String state = cmd.getState(); + Long zone = cmd.getZoneId(); + Long pod = cmd.getPodId(); + Long hostId = cmd.getHostId(); + String keyword = cmd.getKeyword(); + Long networkId = cmd.getNetworkId(); + Long vpcId = cmd.getVpcId(); + Boolean forVpc = cmd.getForVpc(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(DomainRouterJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + //Filter searchFilter = new Filter(DomainRouterJoinVO.class, null, true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _routerJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids to get + // number of + // records with + // pagination + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + + if (forVpc != null) { + if (forVpc) { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); + } else { + sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); + } + } + + if (networkId != null) { + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); + } + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _routerJoinDao.createSearchCriteria(); + ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (zone != null) { + sc.setParameters("dataCenterId", zone); + } + + if (pod != null) { + sc.setParameters("podId", pod); + } + + if (hostId != null) { + sc.setParameters("hostId", hostId); + } + + if (networkId != null) { + sc.setJoinParameters("nicSearch", "networkId", networkId); + } + + if (vpcId != null) { + sc.setParameters("vpcId", vpcId); + } + + // search VR details by ids + Pair, Integer> uniqueVrPair = _routerJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVrPair.second(); + if (count.intValue() == 0) { + // empty result + return uniqueVrPair; + } + List uniqueVrs = uniqueVrPair.first(); + Long[] vrIds = new Long[uniqueVrs.size()]; + int i = 0; + for (DomainRouterJoinVO v : uniqueVrs) { + vrIds[i++] = v.getId(); + } + List vrs = _routerJoinDao.searchByIds(vrIds); + return new Pair, Integer>(vrs, count); + } + + + + @Override + public ListResponse listProjects(ListProjectsCmd cmd) { + Pair, Integer> projects = listProjectsInternal(cmd); + ListResponse response = new ListResponse(); + List projectResponses = ViewResponseHelper.createProjectResponse(projects.first().toArray(new ProjectJoinVO[projects.first().size()])); + response.setResponses(projectResponses, projects.second()); + return response; + } + + private Pair, Integer> listProjectsInternal(ListProjectsCmd cmd) { + + Long id = cmd.getId(); + String name = cmd.getName(); + String displayText = cmd.getDisplayText(); + String state = cmd.getState(); + String accountName = cmd.getAccountName(); + Long domainId = cmd.getDomainId(); + String keyword = cmd.getKeyword(); + Long startIndex = cmd.getStartIndex(); + Long pageSize = cmd.getPageSizeVal(); + boolean listAll = cmd.listAll(); + boolean isRecursive = cmd.isRecursive(); + Map tags = cmd.getTags(); + + Account caller = UserContext.current().getCaller(); + Long accountId = null; + String path = null; + + Filter searchFilter = new Filter(ProjectJoinVO.class, "id", false, startIndex, pageSize); + SearchBuilder sb = _projectJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids + + if (_accountMgr.isAdmin(caller.getType())) { + if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system"); + } + + _accountMgr.checkAccess(caller, domain); + + if (accountName != null) { + Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); + if (owner == null) { + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); + } + accountId = owner.getId(); + } + } else { // domainId == null + if (accountName != null) { + throw new InvalidParameterValueException("could not find account " + accountName + " because domain is not specified"); + } + + } + } else { + if (accountName != null && !accountName.equals(caller.getAccountName())) { + throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized"); + } + + if (domainId != null && domainId.equals(caller.getDomainId())) { + throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized"); + } + + accountId = caller.getId(); + } + + if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { + accountId = caller.getId(); + } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { + DomainVO domain = _domainDao.findById(caller.getDomainId()); + path = domain.getPath(); + } + + if (path != null) { + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + if (accountId != null) { + sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.EQ); + } + + if (tags != null && !tags.isEmpty()) { + for (int count = 0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + SearchCriteria sc = sb.create(); + + if (id != null) { + sc.addAnd("id", Op.EQ, id); + } + + if (domainId != null && !isRecursive) { + sc.addAnd("domainId", Op.EQ, domainId); + } + + if (name != null) { + sc.addAnd("name", Op.EQ, name); + } + + if (displayText != null) { + sc.addAnd("displayText", Op.EQ, displayText); + } + + if (accountId != null) { + sc.setParameters("accountId", accountId); + } + + if (state != null) { + sc.addAnd("state", Op.EQ, state); + } + + if (keyword != null) { + SearchCriteria ssc = _projectJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (path != null) { + sc.setParameters("domainPath", path); + } + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + // search distinct projects to get count + Pair, Integer> uniquePrjPair = _projectJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniquePrjPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return uniquePrjPair; + } + List uniquePrjs = uniquePrjPair.first(); + Long[] prjIds = new Long[uniquePrjs.size()]; + int i = 0; + for (ProjectJoinVO v : uniquePrjs) { + prjIds[i++] = v.getId(); + } + List prjs = _projectJoinDao.searchByIds(prjIds); + return new Pair, Integer>(prjs, count); + } + + + @Override + public ListResponse listProjectInvitations(ListProjectInvitationsCmd cmd) { + Pair, Integer> invites = listProjectInvitationsInternal(cmd); + ListResponse response = new ListResponse(); + List projectInvitationResponses = + ViewResponseHelper.createProjectInvitationResponse(invites.first().toArray(new ProjectInvitationJoinVO[invites.first().size()])); + + response.setResponses(projectInvitationResponses, invites.second()); + return response; + } + + public Pair, Integer> listProjectInvitationsInternal(ListProjectInvitationsCmd cmd){ + Long id = cmd.getId(); + Long projectId = cmd.getProjectId(); + String accountName = cmd.getAccountName(); + Long domainId = cmd.getDomainId(); + String state = cmd.getState(); + boolean activeOnly = cmd.isActiveOnly(); + Long startIndex = cmd.getStartIndex(); + Long pageSizeVal = cmd.getPageSizeVal(); + boolean isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(ProjectInvitationJoinVO.class, "id", true, startIndex, pageSizeVal); + SearchBuilder sb = _projectInvitationJoinDao.createSearchBuilder(); + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + + if (projectId != null){ + sc.setParameters("projectId", projectId); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (activeOnly) { + sc.setParameters("state", ProjectInvitation.State.Pending); + sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - _projectMgr.getInvitationTimeout())); + } + + return _projectInvitationJoinDao.searchAndCount(sc, searchFilter); + + } + + + @Override + public ListResponse listProjectAccounts(ListProjectAccountsCmd cmd) { + Pair, Integer> projectAccounts = listProjectAccountsInternal(cmd); + ListResponse response = new ListResponse(); + List projectResponses = ViewResponseHelper.createProjectAccountResponse(projectAccounts.first().toArray(new ProjectAccountJoinVO[projectAccounts.first().size()])); + response.setResponses(projectResponses, projectAccounts.second()); + return response; + } + + + public Pair, Integer> listProjectAccountsInternal(ListProjectAccountsCmd cmd) { + long projectId = cmd.getProjectId(); + String accountName = cmd.getAccountName(); + String role = cmd.getRole(); + Long startIndex = cmd.getStartIndex(); + Long pageSizeVal = cmd.getPageSizeVal(); + + //long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) { + Account caller = UserContext.current().getCaller(); + + //check that the project exists + Project project = _projectDao.findById(projectId); + + if (project == null) { + throw new InvalidParameterValueException("Unable to find the project id=" + projectId); + } + + //verify permissions - only accounts belonging to the project can list project's account + if (!_accountMgr.isAdmin(caller.getType()) && _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) { + throw new PermissionDeniedException("Account " + caller + " is not authorized to list users of the project id=" + projectId); + } + + Filter searchFilter = new Filter(ProjectAccountJoinVO.class, "id", false, startIndex, pageSizeVal); + SearchBuilder sb = _projectAccountJoinDao.createSearchBuilder(); + sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ); + sb.and("projectId", sb.entity().getProjectId(), Op.EQ); + + SearchBuilder accountSearch; + if (accountName != null) { + sb.and("accountName", sb.entity().getAccountName(), Op.EQ); + } + + SearchCriteria sc = sb.create(); + + sc.setParameters("projectId", projectId); + + if (role != null) { + sc.setParameters("accountRole", role); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + } + + return _projectAccountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForServers(ListHostsCmd cmd) { + //FIXME: do we need to support list hosts with VmId, maybe we should create another command just for this + // Right now it is handled separately outside this QueryService + s_logger.debug(">>>Searching for hosts>>>"); + Pair, Integer> hosts = searchForServersInternal(cmd); + ListResponse response = new ListResponse(); + s_logger.debug(">>>Generating Response>>>"); + List hostResponses = ViewResponseHelper.createHostResponse(cmd.getDetails(), hosts.first().toArray(new HostJoinVO[hosts.first().size()])); + response.setResponses(hostResponses, hosts.second()); + return response; + } + + public Pair, Integer> searchForServersInternal(ListHostsCmd cmd) { + + Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); + Object name = cmd.getHostName(); + Object type = cmd.getType(); + Object state = cmd.getState(); + Object pod = cmd.getPodId(); + Object cluster = cmd.getClusterId(); + Object id = cmd.getId(); + Object keyword = cmd.getKeyword(); + Object resourceState = cmd.getResourceState(); + Object haHosts = cmd.getHaHost(); + Long startIndex = cmd.getStartIndex(); + Long pageSize = cmd.getPageSizeVal(); + + Filter searchFilter = new Filter(HostJoinVO.class, "id", Boolean.TRUE, startIndex, pageSize); + + SearchBuilder sb = _hostJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.LIKE); + sb.and("status", sb.entity().getStatus(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("clusterId", sb.entity().getClusterId(), SearchCriteria.Op.EQ); + sb.and("resourceState", sb.entity().getResourceState(), SearchCriteria.Op.EQ); + + String haTag = _haMgr.getHaTag(); + if (haHosts != null && haTag != null && !haTag.isEmpty()) { + if ((Boolean) haHosts) { + sb.and("tag", sb.entity().getTag(), SearchCriteria.Op.EQ); + } else { + sb.and().op("tag", sb.entity().getTag(), SearchCriteria.Op.NEQ); + sb.or("tagNull", sb.entity().getTag(), SearchCriteria.Op.NULL); + sb.cp(); + } + + } + + + SearchCriteria sc = sb.create(); + + if (keyword != null) { + SearchCriteria ssc = _hostJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("status", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + if (type != null) { + sc.setParameters("type", "%" + type); + } + if (state != null) { + sc.setParameters("status", state); + } + if (zoneId != null) { + sc.setParameters("dataCenterId", zoneId); + } + if (pod != null) { + sc.setParameters("podId", pod); + } + if (cluster != null) { + sc.setParameters("clusterId", cluster); + } + + if (resourceState != null) { + sc.setParameters("resourceState", resourceState); + } + + if (haHosts != null && haTag != null && !haTag.isEmpty()) { + sc.setJoinParameters("hostTagSearch", "tag", haTag); + } + + // search host details by ids + Pair, Integer> uniqueHostPair = _hostJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueHostPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueHostPair; + } + List uniqueHosts = uniqueHostPair.first(); + Long[] hostIds = new Long[uniqueHosts.size()]; + int i = 0; + for (HostJoinVO v : uniqueHosts ){ + hostIds[i++] = v.getId(); + } + List hosts = _hostJoinDao.searchByIds(hostIds); + return new Pair, Integer>(hosts, count); + + } + + @Override + public ListResponse searchForVolumes(ListVolumesCmd cmd) { + Pair, Integer> result = searchForVolumesInternal(cmd); + ListResponse response = new ListResponse(); + + List volumeResponses = ViewResponseHelper.createVolumeResponse(result.first().toArray(new VolumeJoinVO[result.first().size()])); + response.setResponses(volumeResponses, result.second()); + return response; + } + + + private Pair, Integer> searchForVolumesInternal(ListVolumesCmd cmd) { + + Account caller = UserContext.current().getCaller(); + List permittedAccounts = new ArrayList(); + + Long id = cmd.getId(); + Long vmInstanceId = cmd.getVirtualMachineId(); + String name = cmd.getVolumeName(); + String keyword = cmd.getKeyword(); + String type = cmd.getType(); + Map tags = cmd.getTags(); + + Long zoneId = cmd.getZoneId(); + Long podId = null; + if (_accountMgr.isAdmin(caller.getType())) { + podId = cmd.getPodId(); + } + + Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + Filter searchFilter = new Filter(VolumeJoinVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + + // hack for now, this should be done better but due to needing a join I opted to + // do this quickly and worry about making it pretty later + SearchBuilder sb = _volumeJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct + // ids to get + // number of + // records with + // pagination + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE); + sb.and("instanceId", sb.entity().getVmId(), SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + // Only return volumes that are not destroyed + sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); + sb.and("systemUse", sb.entity().isSystemUse(), SearchCriteria.Op.NEQ); + // display UserVM volumes only + sb.and().op("type", sb.entity().getVmType(), SearchCriteria.Op.NIN); + sb.or("nulltype", sb.entity().getVmType(), SearchCriteria.Op.NULL); + sb.cp(); + + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } + + + + // now set the SC criteria... + SearchCriteria sc = sb.create(); + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + + if (keyword != null) { + SearchCriteria ssc = _volumeJoinDao.createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.setParameters("name", "%" + name + "%"); + } + + sc.setParameters("systemUse", 1); + + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); + count++; + } + } + + if (id != null) { + sc.setParameters("id", id); + } + + if (type != null) { + sc.setParameters("volumeType", "%" + type + "%"); + } + if (vmInstanceId != null) { + sc.setParameters("instanceId", vmInstanceId); + } + if (zoneId != null) { + sc.setParameters("dataCenterId", zoneId); + } + if (podId != null) { + sc.setParameters("podId", podId); + } + + // Don't return DomR and ConsoleProxy volumes + sc.setParameters("type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.DomainRouter); + + // Only return volumes that are not destroyed + sc.setParameters("state", Volume.State.Destroy); + + // search Volume details by ids + Pair, Integer> uniqueVolPair = _volumeJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVolPair.second(); + if (count.intValue() == 0) { + // empty result + return uniqueVolPair; + } + List uniqueVols = uniqueVolPair.first(); + Long[] vrIds = new Long[uniqueVols.size()]; + int i = 0; + for (VolumeJoinVO v : uniqueVols) { + vrIds[i++] = v.getId(); + } + List vrs = _volumeJoinDao.searchByIds(vrIds); + return new Pair, Integer>(vrs, count); + } + + @Override + public ListResponse searchForAccounts(ListAccountsCmd cmd) { + Pair, Integer> result = searchForAccountsInternal(cmd); + ListResponse response = new ListResponse(); + List accountResponses = ViewResponseHelper.createAccountResponse(result.first().toArray(new AccountJoinVO[result.first().size()])); + response.setResponses(accountResponses, result.second()); + return response; + } + + + public Pair, Integer> searchForAccountsInternal(ListAccountsCmd cmd) { + Account caller = UserContext.current().getCaller(); + Long domainId = cmd.getDomainId(); + Long accountId = cmd.getId(); + String accountName = cmd.getSearchName(); + boolean isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + Boolean listForDomain = false; + + if (accountId != null) { + Account account = _accountDao.findById(accountId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by id " + accountId); + } + + _accountMgr.checkAccess(caller, null, true, account); + } + + if (domainId != null) { + Domain domain = _domainDao.findById(domainId); + if (domain == null) { + throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); + } + + _accountMgr.checkAccess(caller, domain); + + if (accountName != null) { + Account account = _accountDao.findActiveAccount(accountName, domainId); + if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); + } + _accountMgr.checkAccess(caller, null, true, account); + } + } + + if (accountId == null) { + if (_accountMgr.isAdmin(caller.getType()) && listAll && domainId == null) { + listForDomain = true; + isRecursive = true; + if (domainId == null) { + domainId = caller.getDomainId(); + } + } else if (_accountMgr.isAdmin(caller.getType()) && domainId != null) { + listForDomain = true; + } else { + accountId = caller.getAccountId(); + } + } + + Filter searchFilter = new Filter(AccountJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + + Object type = cmd.getAccountType(); + Object state = cmd.getState(); + Object isCleanupRequired = cmd.isCleanupRequired(); + Object keyword = cmd.getKeyword(); + + SearchBuilder sb = _accountJoinDao.createSearchBuilder(); + sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); + sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); + sb.and("needsCleanup", sb.entity().isNeedsCleanup(), SearchCriteria.Op.EQ); + sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); + sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); + + if (listForDomain && isRecursive) { + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + SearchCriteria sc = sb.create(); + + sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); + + if (keyword != null) { + SearchCriteria ssc = _accountJoinDao.createSearchCriteria(); + ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("accountName", SearchCriteria.Op.SC, ssc); + } + + if (type != null) { + sc.setParameters("type", type); + } + + if (state != null) { + sc.setParameters("state", state); + } + + if (isCleanupRequired != null) { + sc.setParameters("needsCleanup", isCleanupRequired); + } + + if (accountName != null) { + sc.setParameters("accountName", accountName); + } + + // don't return account of type project to the end user + sc.setParameters("typeNEQ", 5); + + if (accountId != null) { + sc.setParameters("id", accountId); + } + + if (listForDomain) { + if (isRecursive) { + Domain domain = _domainDao.findById(domainId); + sc.setParameters("path", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + + return _accountJoinDao.searchAndCount(sc, searchFilter); + } + + @Override + public ListResponse searchForAsyncJobs(ListAsyncJobsCmd cmd) { + Pair, Integer> result = searchForAsyncJobsInternal(cmd); + ListResponse response = new ListResponse(); + List jobResponses = ViewResponseHelper.createAsyncJobResponse(result.first().toArray(new AsyncJobJoinVO[result.first().size()])); + response.setResponses(jobResponses, result.second()); + return response; + } + + + public Pair, Integer> searchForAsyncJobsInternal(ListAsyncJobsCmd cmd) { + + Account caller = UserContext.current().getCaller(); + + List permittedAccounts = new ArrayList(); + + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); + Long domainId = domainIdRecursiveListProject.first(); + Boolean isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + + Filter searchFilter = new Filter(AsyncJobJoinVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); + SearchBuilder sb = _jobJoinDao.createSearchBuilder(); + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + SearchBuilder accountSearch = null; + boolean accountJoinIsDone = false; + if (permittedAccounts.isEmpty() && domainId != null) { + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + accountJoinIsDone = true; + } + + if (listProjectResourcesCriteria != null) { + + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + sb.and("type", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); + } + + if (!accountJoinIsDone) { + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + sb.and("path", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + } + + Object keyword = cmd.getKeyword(); + Object startDate = cmd.getStartDate(); + + SearchCriteria sc = sb.create(); + if (listProjectResourcesCriteria != null) { + sc.setParameters("type", Account.ACCOUNT_TYPE_PROJECT); + } + + if (!permittedAccounts.isEmpty()) { + sc.setParameters("accountIdIN", permittedAccounts.toArray()); + } else if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (isRecursive) { + sc.setParameters("path", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + + if (keyword != null) { + sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + } + + if (startDate != null) { + sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); + } + + return _jobJoinDao.searchAndCount(sc, searchFilter); + } + +} diff --git a/server/src/com/cloud/api/query/ViewResponseHelper.java b/server/src/com/cloud/api/query/ViewResponseHelper.java new file mode 100644 index 00000000000..08495860b20 --- /dev/null +++ b/server/src/com/cloud/api/query/ViewResponseHelper.java @@ -0,0 +1,256 @@ +// 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.query; + +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.EventResponse; +import org.apache.cloudstack.api.response.HostResponse; +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.ProjectAccountResponse; +import org.apache.cloudstack.api.response.ProjectInvitationResponse; +import org.apache.cloudstack.api.response.ProjectResponse; +import org.apache.cloudstack.api.response.ResourceTagResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import org.apache.cloudstack.api.response.VolumeResponse; +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.user.Account; +import com.cloud.user.UserContext; + +/** + * Helper class to generate response from DB view VO objects. + * @author minc + * + */ +public class ViewResponseHelper { + + public static final Logger s_logger = Logger.getLogger(ViewResponseHelper.class); + + public static List createUserResponse(UserAccountJoinVO... users) { + List respList = new ArrayList(); + for (UserAccountJoinVO vt : users){ + respList.add(ApiDBUtils.newUserResponse(vt)); + } + return respList; + } + + public static List createEventResponse(EventJoinVO... events) { + List respList = new ArrayList(); + for (EventJoinVO vt : events){ + respList.add(ApiDBUtils.newEventResponse(vt)); + } + return respList; + } + + public static List createResourceTagResponse(boolean keyValueOnly, ResourceTagJoinVO... tags) { + List respList = new ArrayList(); + for (ResourceTagJoinVO vt : tags){ + respList.add(ApiDBUtils.newResourceTagResponse(vt, keyValueOnly)); + } + return respList; + } + + public static List createInstanceGroupResponse(InstanceGroupJoinVO... groups) { + List respList = new ArrayList(); + for (InstanceGroupJoinVO vt : groups){ + respList.add(ApiDBUtils.newInstanceGroupResponse(vt)); + } + return respList; + } + + + public static List createUserVmResponse(String objectName, UserVmJoinVO... userVms) { + return createUserVmResponse(objectName, EnumSet.of(VMDetails.all), userVms); + } + + public static List createUserVmResponse(String objectName, EnumSet details, UserVmJoinVO... userVms) { + Account caller = UserContext.current().getCaller(); + + Hashtable vmDataList = new Hashtable(); + // Initialise the vmdatalist with the input data + + + for (UserVmJoinVO userVm : userVms) { + UserVmResponse userVmData = vmDataList.get(userVm.getId()); + if ( userVmData == null ){ + // first time encountering this vm + userVmData = ApiDBUtils.newUserVmResponse(objectName, userVm, details, caller); + } else{ + // update nics, securitygroups, tags for 1 to many mapping fields + userVmData = ApiDBUtils.fillVmDetails(userVmData, userVm); + } + vmDataList.put(userVm.getId(), userVmData); + } + return new ArrayList(vmDataList.values()); + } + + public static List createDomainRouterResponse(DomainRouterJoinVO... routers) { + Account caller = UserContext.current().getCaller(); + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (DomainRouterJoinVO vr : routers) { + DomainRouterResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this vm + vrData = ApiDBUtils.newDomainRouterResponse(vr, caller); + } + else{ + // update nics for 1 to many mapping fields + vrData = ApiDBUtils.fillRouterDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + + public static List createSecurityGroupResponses(List securityGroups) { + Account caller = UserContext.current().getCaller(); + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (SecurityGroupJoinVO vr : securityGroups) { + SecurityGroupResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ) { + // first time encountering this sg + vrData = ApiDBUtils.newSecurityGroupResponse(vr, caller); + + } else { + // update rules for 1 to many mapping fields + vrData = ApiDBUtils.fillSecurityGroupDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + + public static List createProjectResponse(ProjectJoinVO... projects) { + Hashtable prjDataList = new Hashtable(); + // Initialise the prjdatalist with the input data + for (ProjectJoinVO p : projects) { + ProjectResponse pData = prjDataList.get(p.getId()); + if ( pData == null ){ + // first time encountering this vm + pData = ApiDBUtils.newProjectResponse(p); + } + else{ + // update those 1 to many mapping fields + pData = ApiDBUtils.fillProjectDetails(pData, p); + } + prjDataList.put(p.getId(), pData); + } + return new ArrayList(prjDataList.values()); + } + + + public static List createProjectAccountResponse(ProjectAccountJoinVO... projectAccounts) { + List responseList = new ArrayList(); + for (ProjectAccountJoinVO proj : projectAccounts){ + ProjectAccountResponse resp = ApiDBUtils.newProjectAccountResponse(proj); + // update user list + List users = ApiDBUtils.findUserViewByAccountId(proj.getAccountId()); + resp.setUsers(ViewResponseHelper.createUserResponse(users.toArray(new UserAccountJoinVO[users.size()]))); + responseList.add(resp); + } + return responseList; + } + + public static List createProjectInvitationResponse(ProjectInvitationJoinVO... invites) { + List respList = new ArrayList(); + for (ProjectInvitationJoinVO v : invites){ + respList.add(ApiDBUtils.newProjectInvitationResponse(v)); + } + return respList; + } + + public static List createHostResponse(EnumSet details, HostJoinVO... hosts) { + Hashtable vrDataList = new Hashtable(); + // Initialise the vrdatalist with the input data + for (HostJoinVO vr : hosts) { + HostResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this vm + vrData = ApiDBUtils.newHostResponse(vr, details); + } + else{ + // update tags + vrData = ApiDBUtils.fillHostDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + public static List createVolumeResponse(VolumeJoinVO... volumes) { + Hashtable vrDataList = new Hashtable(); + for (VolumeJoinVO vr : volumes) { + VolumeResponse vrData = vrDataList.get(vr.getId()); + if ( vrData == null ){ + // first time encountering this volume + vrData = ApiDBUtils.newVolumeResponse(vr); + } + else{ + // update tags + vrData = ApiDBUtils.fillVolumeDetails(vrData, vr); + } + vrDataList.put(vr.getId(), vrData); + } + return new ArrayList(vrDataList.values()); + } + + public static List createAccountResponse(AccountJoinVO... accounts) { + List respList = new ArrayList(); + for (AccountJoinVO vt : accounts){ + respList.add(ApiDBUtils.newAccountResponse(vt)); + } + return respList; + } + + public static List createAsyncJobResponse(AsyncJobJoinVO... jobs) { + List respList = new ArrayList(); + for (AsyncJobJoinVO vt : jobs){ + respList.add(ApiDBUtils.newAsyncJobResponse(vt)); + } + return respList; + } +} diff --git a/server/src/com/cloud/api/query/dao/AccountJoinDao.java b/server/src/com/cloud/api/query/dao/AccountJoinDao.java new file mode 100644 index 00000000000..5485f093d87 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AccountJoinDao.java @@ -0,0 +1,32 @@ +// 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.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.AccountResponse; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface AccountJoinDao extends GenericDao { + + AccountResponse newAccountResponse(AccountJoinVO vol); + + AccountJoinVO newAccountView(Account vol); + +} diff --git a/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java new file mode 100644 index 00000000000..626872447e7 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AccountJoinDaoImpl.java @@ -0,0 +1,185 @@ +// 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.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.ViewResponseHelper; +import com.cloud.api.query.vo.AccountJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.configuration.Resource.ResourceType; +import org.apache.cloudstack.api.response.AccountResponse; +import org.apache.cloudstack.api.response.UserResponse; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={AccountJoinDao.class}) +public class AccountJoinDaoImpl extends GenericDaoBase implements AccountJoinDao { + public static final Logger s_logger = Logger.getLogger(AccountJoinDaoImpl.class); + + private SearchBuilder acctIdSearch; + + protected AccountJoinDaoImpl() { + + acctIdSearch = createSearchBuilder(); + acctIdSearch.and("id", acctIdSearch.entity().getId(), SearchCriteria.Op.EQ); + acctIdSearch.done(); + + this._count = "select count(distinct id) from account_view WHERE "; + } + + + + @Override + public AccountResponse newAccountResponse(AccountJoinVO account) { + boolean accountIsAdmin = (account.getType() == Account.ACCOUNT_TYPE_ADMIN); + AccountResponse accountResponse = new AccountResponse(); + accountResponse.setId(account.getUuid()); + accountResponse.setName(account.getAccountName()); + accountResponse.setAccountType(account.getType()); + accountResponse.setDomainId(account.getDomainUuid()); + accountResponse.setDomainName(account.getDomainName()); + accountResponse.setState(account.getState().toString()); + accountResponse.setNetworkDomain(account.getNetworkDomain()); + accountResponse.setDefaultZone(account.getDataCenterUuid()); + + // get network stat + accountResponse.setBytesReceived(account.getBytesReceived()); + accountResponse.setBytesSent(account.getBytesSent()); + + // Get resource limits and counts + + long vmLimit = ApiDBUtils.findCorrectResourceLimit(account.getVmLimit(), account.getType(), ResourceType.user_vm); + String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); + long vmTotal = (account.getVmTotal() == null) ? 0 : account.getVmTotal(); + String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); + accountResponse.setVmLimit(vmLimitDisplay); + accountResponse.setVmTotal(vmTotal); + accountResponse.setVmAvailable(vmAvail); + + long ipLimit = ApiDBUtils.findCorrectResourceLimit(account.getIpLimit(), account.getType(), ResourceType.public_ip); + String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); + long ipTotal = (account.getIpTotal() == null) ? 0 : account.getIpTotal(); + + Long ips = ipLimit - ipTotal; + // check how many free ips are left, and if it's less than max allowed number of ips from account - use this + // value + Long ipsLeft = account.getIpFree(); + boolean unlimited = true; + if (ips.longValue() > ipsLeft.longValue()) { + ips = ipsLeft; + unlimited = false; + } + + String ipAvail = ((accountIsAdmin || ipLimit == -1) && unlimited) ? "Unlimited" : String.valueOf(ips); + + accountResponse.setIpLimit(ipLimitDisplay); + accountResponse.setIpTotal(ipTotal); + accountResponse.setIpAvailable(ipAvail); + + long volumeLimit = ApiDBUtils.findCorrectResourceLimit(account.getVolumeLimit(), account.getType(), ResourceType.volume); + String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); + long volumeTotal = (account.getVolumeTotal() == 0) ? 0 : account.getVolumeTotal(); + String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); + accountResponse.setVolumeLimit(volumeLimitDisplay); + accountResponse.setVolumeTotal(volumeTotal); + accountResponse.setVolumeAvailable(volumeAvail); + + long snapshotLimit = ApiDBUtils.findCorrectResourceLimit(account.getSnapshotLimit(), account.getType(), ResourceType.snapshot); + String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); + long snapshotTotal = (account.getSnapshotTotal() == null) ? 0 : account.getSnapshotTotal(); + String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); + accountResponse.setSnapshotLimit(snapshotLimitDisplay); + accountResponse.setSnapshotTotal(snapshotTotal); + accountResponse.setSnapshotAvailable(snapshotAvail); + + Long templateLimit = ApiDBUtils.findCorrectResourceLimit(account.getTemplateLimit(), account.getType(), ResourceType.template); + String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); + Long templateTotal = (account.getTemplateTotal() == null) ? 0 : account.getTemplateTotal(); + String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); + accountResponse.setTemplateLimit(templateLimitDisplay); + accountResponse.setTemplateTotal(templateTotal); + accountResponse.setTemplateAvailable(templateAvail); + + // Get stopped and running VMs + accountResponse.setVmStopped(account.getVmStopped()); + accountResponse.setVmRunning(account.getVmRunning()); + + + //get resource limits for projects + long projectLimit = ApiDBUtils.findCorrectResourceLimit(account.getProjectLimit(), account.getType(), ResourceType.project); + String projectLimitDisplay = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit); + long projectTotal = (account.getProjectTotal() == null) ? 0 : account.getProjectTotal(); + String projectAvail = (accountIsAdmin || projectLimit == -1) ? "Unlimited" : String.valueOf(projectLimit - projectTotal); + accountResponse.setProjectLimit(projectLimitDisplay); + accountResponse.setProjectTotal(projectTotal); + accountResponse.setProjectAvailable(projectAvail); + + //get resource limits for networks + long networkLimit = ApiDBUtils.findCorrectResourceLimit(account.getNetworkLimit(), account.getType(), ResourceType.network); + String networkLimitDisplay = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit); + long networkTotal = (account.getNetworkTotal() == null) ? 0 : account.getNetworkTotal(); + String networkAvail = (accountIsAdmin || networkLimit == -1) ? "Unlimited" : String.valueOf(networkLimit - networkTotal); + accountResponse.setNetworkLimit(networkLimitDisplay); + accountResponse.setNetworkTotal(networkTotal); + accountResponse.setNetworkAvailable(networkAvail); + + //get resource limits for vpcs + long vpcLimit = ApiDBUtils.findCorrectResourceLimit(account.getVpcLimit(), account.getType(), ResourceType.vpc); + String vpcLimitDisplay = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit); + long vpcTotal = (account.getVpcTotal() == null) ? 0 : account.getVpcTotal(); + String vpcAvail = (accountIsAdmin || vpcLimit == -1) ? "Unlimited" : String.valueOf(vpcLimit - vpcTotal); + accountResponse.setNetworkLimit(vpcLimitDisplay); + accountResponse.setNetworkTotal(vpcTotal); + accountResponse.setNetworkAvailable(vpcAvail); + + // adding all the users for an account as part of the response obj + List usersForAccount = ApiDBUtils.findUserViewByAccountId(account.getId()); + List userResponses = ViewResponseHelper.createUserResponse(usersForAccount.toArray(new UserAccountJoinVO[usersForAccount.size()])); + accountResponse.setUsers(userResponses); + + // set details + accountResponse.setDetails(ApiDBUtils.getAccountDetails(account.getId())); + accountResponse.setObjectName("account"); + + // set async job + accountResponse.setJobId(account.getJobUuid()); + accountResponse.setJobStatus(account.getJobStatus()); + return accountResponse; + } + + + @Override + public AccountJoinVO newAccountView(Account acct) { + SearchCriteria sc = acctIdSearch.create(); + sc.setParameters("id", acct.getId()); + List accounts = searchIncludingRemoved(sc, null, null, false); + assert accounts != null && accounts.size() == 1 : "No account found for account id " + acct.getId(); + return accounts.get(0); + + } + + +} diff --git a/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java b/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java new file mode 100644 index 00000000000..f7a2c8c0f69 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AsyncJobJoinDao.java @@ -0,0 +1,33 @@ +// 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.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.AsyncJobResponse; + +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.async.AsyncJob; +import com.cloud.utils.db.GenericDao; + +public interface AsyncJobJoinDao extends GenericDao { + + AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO vol); + + AsyncJobJoinVO newAsyncJobView(AsyncJob vol); + +} diff --git a/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java new file mode 100644 index 00000000000..bf1d15c4205 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/AsyncJobJoinDaoImpl.java @@ -0,0 +1,114 @@ +// 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.query.dao; + +import java.util.Date; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiSerializerHelper; +import com.cloud.api.SerializationContext; +import com.cloud.api.query.vo.AsyncJobJoinVO; +import com.cloud.async.AsyncJob; +import org.apache.cloudstack.api.ResponseObject; +import org.apache.cloudstack.api.response.AsyncJobResponse; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={AsyncJobJoinDao.class}) +public class AsyncJobJoinDaoImpl extends GenericDaoBase implements AsyncJobJoinDao { + public static final Logger s_logger = Logger.getLogger(AsyncJobJoinDaoImpl.class); + + private SearchBuilder jobIdSearch; + + protected AsyncJobJoinDaoImpl() { + + + jobIdSearch = createSearchBuilder(); + jobIdSearch.and("id", jobIdSearch.entity().getId(), SearchCriteria.Op.EQ); + jobIdSearch.done(); + + this._count = "select count(distinct id) from async_job_view WHERE "; + } + + + + + + @Override + public AsyncJobResponse newAsyncJobResponse(AsyncJobJoinVO job) { + AsyncJobResponse jobResponse = new AsyncJobResponse(); + jobResponse.setAccountId(job.getAccountUuid()); + jobResponse.setUserId(job.getUserUuid()); + jobResponse.setCmd(job.getCmd()); + jobResponse.setCreated(job.getCreated()); + jobResponse.setJobId(job.getUuid()); + jobResponse.setJobStatus(job.getStatus()); + jobResponse.setJobProcStatus(job.getProcessStatus()); + + if (job.getInstanceType() != null && job.getInstanceId() != null) { + jobResponse.setJobInstanceType(job.getInstanceType().toString()); + + jobResponse.setJobInstanceId(job.getInstanceUuid()); + + } + jobResponse.setJobResultCode(job.getResultCode()); + + boolean savedValue = SerializationContext.current().getUuidTranslation(); + SerializationContext.current().setUuidTranslation(false); + + Object resultObject = ApiSerializerHelper.fromSerializedString(job.getResult()); + jobResponse.setJobResult((ResponseObject) resultObject); + SerializationContext.current().setUuidTranslation(savedValue); + + if (resultObject != null) { + Class clz = resultObject.getClass(); + if (clz.isPrimitive() || clz.getSuperclass() == Number.class || clz == String.class || clz == Date.class) { + jobResponse.setJobResultType("text"); + } else { + jobResponse.setJobResultType("object"); + } + } + + jobResponse.setObjectName("asyncjobs"); + return jobResponse; + } + + + + + + @Override + public AsyncJobJoinVO newAsyncJobView(AsyncJob job) { + SearchCriteria sc = jobIdSearch.create(); + sc.setParameters("id", job.getId()); + List accounts = searchIncludingRemoved(sc, null, null, false); + assert accounts != null && accounts.size() == 1 : "No async job found for job id " + job.getId(); + return accounts.get(0); + + } + + + + + +} diff --git a/server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java new file mode 100644 index 00000000000..961ab40a88d --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDao.java @@ -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 permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.DomainRouterResponse; + +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface DomainRouterJoinDao extends GenericDao { + + DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO uvo, Account caller); + + DomainRouterResponse setDomainRouterResponse(DomainRouterResponse userVmData, DomainRouterJoinVO uvo); + + List newDomainRouterView(VirtualRouter vr); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java new file mode 100644 index 00000000000..94736cd7f90 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/DomainRouterJoinDaoImpl.java @@ -0,0 +1,249 @@ +// 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.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.DomainRouterJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.DomainRouterResponse; +import org.apache.cloudstack.api.response.NicResponse; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.router.VirtualRouter; +import com.cloud.user.Account; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={DomainRouterJoinDao.class}) +public class DomainRouterJoinDaoImpl extends GenericDaoBase implements DomainRouterJoinDao { + public static final Logger s_logger = Logger.getLogger(DomainRouterJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder vrSearch; + + private SearchBuilder vrIdSearch; + + protected DomainRouterJoinDaoImpl() { + + vrSearch = createSearchBuilder(); + vrSearch.and("idIN", vrSearch.entity().getId(), SearchCriteria.Op.IN); + vrSearch.done(); + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + this._count = "select count(distinct id) from domain_router_view WHERE "; + } + + + @Override + public DomainRouterResponse newDomainRouterResponse(DomainRouterJoinVO router, Account caller) { + DomainRouterResponse routerResponse = new DomainRouterResponse(); + routerResponse.setId(router.getUuid()); + routerResponse.setZoneId(router.getDataCenterUuid()); + routerResponse.setName(router.getHostName()); + routerResponse.setTemplateId(router.getTemplateUuid()); + routerResponse.setCreated(router.getCreated()); + routerResponse.setState(router.getState()); + routerResponse.setIsRedundantRouter(router.isRedundantRouter()); + routerResponse.setRedundantState(router.getRedundantState().toString()); + + if (caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN + || caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { + if (router.getHostId() != null) { + routerResponse.setHostId(router.getHostUuid()); + routerResponse.setHostName(router.getHostName()); + } + routerResponse.setPodId(router.getPodUuid()); + long nic_id = router.getNicId(); + if (nic_id > 0) { + TrafficType ty = router.getTrafficType(); + if (ty != null) { + // legacy code, public/control/guest nic info is kept in + // nics response object + if (ty == TrafficType.Public) { + routerResponse.setPublicIp(router.getIpAddress()); + routerResponse.setPublicMacAddress(router.getMacAddress()); + routerResponse.setPublicNetmask(router.getNetmask()); + routerResponse.setGateway(router.getGateway()); + routerResponse.setPublicNetworkId(router.getNetworkUuid()); + } else if (ty == TrafficType.Control) { + routerResponse.setLinkLocalIp(router.getIpAddress()); + routerResponse.setLinkLocalMacAddress(router.getMacAddress()); + routerResponse.setLinkLocalNetmask(router.getNetmask()); + routerResponse.setLinkLocalNetworkId(router.getNetworkUuid()); + } else if (ty == TrafficType.Guest) { + routerResponse.setGuestIpAddress(router.getIpAddress()); + routerResponse.setGuestMacAddress(router.getMacAddress()); + routerResponse.setGuestNetmask(router.getNetmask()); + routerResponse.setGuestNetworkId(router.getNetworkUuid()); + routerResponse.setNetworkDomain(router.getNetworkDomain()); + } + } + + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(router.getNicUuid()); + nicResponse.setIpaddress(router.getIpAddress()); + nicResponse.setGateway(router.getGateway()); + nicResponse.setNetmask(router.getNetmask()); + nicResponse.setNetworkid(router.getNetworkUuid()); + nicResponse.setNetworkName(router.getNetworkName()); + nicResponse.setMacAddress(router.getMacAddress()); + if (router.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(router.getBroadcastUri().toString()); + } + if (router.getIsolationUri() != null) { + nicResponse.setIsolationUri(router.getIsolationUri().toString()); + } + if (router.getTrafficType() != null) { + nicResponse.setTrafficType(router.getTrafficType().toString()); + } + if (router.getGuestType() != null) { + nicResponse.setType(router.getGuestType().toString()); + } + nicResponse.setIsDefault(router.isDefaultNic()); + nicResponse.setObjectName("nic"); + routerResponse.addNic(nicResponse); + } + } + + routerResponse.setServiceOfferingId(router.getServiceOfferingUuid()); + routerResponse.setServiceOfferingName(router.getServiceOfferingName()); + + // populate owner. + ApiResponseHelper.populateOwner(routerResponse, router); + + + routerResponse.setDomainId(router.getDomainUuid()); + routerResponse.setDomainName(router.getDomainName()); + + routerResponse.setZoneName(router.getDataCenterName()); + routerResponse.setDns1(router.getDns1()); + routerResponse.setDns2(router.getDns2()); + + routerResponse.setVpcId(router.getVpcUuid()); + + // set async job + routerResponse.setJobId(router.getJobUuid()); + routerResponse.setJobStatus(router.getJobStatus()); + + routerResponse.setObjectName("router"); + + return routerResponse; + } + + + @Override + public DomainRouterResponse setDomainRouterResponse(DomainRouterResponse vrData, DomainRouterJoinVO vr) { + long nic_id = vr.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(vr.getNicUuid()); + nicResponse.setIpaddress(vr.getIpAddress()); + nicResponse.setGateway(vr.getGateway()); + nicResponse.setNetmask(vr.getNetmask()); + nicResponse.setNetworkid(vr.getNetworkUuid()); + nicResponse.setMacAddress(vr.getMacAddress()); + if (vr.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(vr.getBroadcastUri().toString()); + } + if (vr.getIsolationUri() != null) { + nicResponse.setIsolationUri(vr.getIsolationUri().toString()); + } + if (vr.getTrafficType() != null) { + nicResponse.setTrafficType(vr.getTrafficType().toString()); + } + if (vr.getGuestType() != null) { + nicResponse.setType(vr.getGuestType().toString()); + } + nicResponse.setIsDefault(vr.isDefaultNic()); + nicResponse.setObjectName("nic"); + vrData.addNic(nicResponse); + } + return vrData; + } + + + + + @Override + public List searchByIds(Long... vrIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( vrIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= vrIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = vrIds[j]; + } + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < vrIds.length) { + int batch_size = (vrIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = vrIds[j]; + } + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + @Override + public List newDomainRouterView(VirtualRouter vr) { + + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", vr.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + +} diff --git a/server/src/com/cloud/api/query/dao/HostJoinDao.java b/server/src/com/cloud/api/query/dao/HostJoinDao.java new file mode 100644 index 00000000000..1a2129998ed --- /dev/null +++ b/server/src/com/cloud/api/query/dao/HostJoinDao.java @@ -0,0 +1,38 @@ +// 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.query.dao; + +import java.util.EnumSet; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.response.HostResponse; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.host.Host; +import com.cloud.utils.db.GenericDao; + +public interface HostJoinDao extends GenericDao { + + HostResponse newHostResponse(HostJoinVO host, EnumSet details); + + HostResponse setHostResponse(HostResponse response, HostJoinVO host); + + List newHostView(Host group); + + List searchByIds(Long... ids); + +} diff --git a/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java new file mode 100644 index 00000000000..e8423836004 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/HostJoinDaoImpl.java @@ -0,0 +1,270 @@ +// 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.query.dao; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.HostJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.host.Host; +import com.cloud.host.HostStats; + +import org.apache.cloudstack.api.ApiConstants.HostDetails; +import org.apache.cloudstack.api.response.HostResponse; +import com.cloud.storage.StorageStats; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={HostJoinDao.class}) +public class HostJoinDaoImpl extends GenericDaoBase implements HostJoinDao { + public static final Logger s_logger = Logger.getLogger(HostJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder hostSearch; + + private SearchBuilder hostIdSearch; + + + protected HostJoinDaoImpl() { + + hostSearch = createSearchBuilder(); + hostSearch.and("idIN", hostSearch.entity().getId(), SearchCriteria.Op.IN); + hostSearch.done(); + + hostIdSearch = createSearchBuilder(); + hostIdSearch.and("id", hostIdSearch.entity().getId(), SearchCriteria.Op.EQ); + hostIdSearch.done(); + + this._count = "select count(distinct id) from host_view WHERE "; + } + + + + @Override + public HostResponse newHostResponse(HostJoinVO host, EnumSet details) { + HostResponse hostResponse = new HostResponse(); + hostResponse.setId(host.getUuid()); + hostResponse.setCapabilities(host.getCapabilities()); + hostResponse.setClusterId(host.getClusterUuid()); + hostResponse.setCpuNumber(host.getCpus()); + hostResponse.setZoneId(host.getUuid()); + hostResponse.setDisconnectedOn(host.getDisconnectedOn()); + hostResponse.setHypervisor(host.getHypervisorType()); + hostResponse.setHostType(host.getType()); + hostResponse.setLastPinged(new Date(host.getLastPinged())); + hostResponse.setManagementServerId(host.getManagementServerId()); + hostResponse.setName(host.getName()); + hostResponse.setPodId(host.getPodUuid()); + hostResponse.setRemoved(host.getRemoved()); + hostResponse.setCpuSpeed(host.getSpeed()); + hostResponse.setState(host.getStatus()); + hostResponse.setIpAddress(host.getPrivateIpAddress()); + hostResponse.setVersion(host.getVersion()); + hostResponse.setCreated(host.getCreated()); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity) + || details.contains(HostDetails.stats) || details.contains(HostDetails.events)) { + + hostResponse.setOsCategoryId(host.getOsCategoryUuid()); + hostResponse.setOsCategoryName(host.getOsCategoryName()); + hostResponse.setZoneName(host.getZoneName()); + hostResponse.setPodName(host.getPodName()); + if ( host.getClusterId() > 0) { + hostResponse.setClusterName(host.getClusterName()); + hostResponse.setClusterType(host.getClusterType().toString()); + } + } + + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + if (host.getType() == Host.Type.Routing) { + if (details.contains(HostDetails.all) || details.contains(HostDetails.capacity)) { + // set allocated capacities + Long mem = host.getMemReservedCapacity() + host.getMemUsedCapacity(); + Long cpu = host.getCpuReservedCapacity() + host.getCpuReservedCapacity(); + + hostResponse.setMemoryAllocated(mem); + hostResponse.setMemoryTotal(host.getTotalMemory()); + + String hostTags = host.getTag(); + hostResponse.setHostTags(host.getTag()); + + String haTag = ApiDBUtils.getHaTag(); + if (haTag != null && !haTag.isEmpty() && hostTags != null && !hostTags.isEmpty()) { + if (haTag.equalsIgnoreCase(hostTags)) { + hostResponse.setHaHost(true); + } else { + hostResponse.setHaHost(false); + } + } else { + hostResponse.setHaHost(false); + } + + hostResponse.setHypervisorVersion(host.getHypervisorVersion()); + + String cpuAlloc = decimalFormat.format(((float) cpu / (float) (host.getCpus() * host.getSpeed())) * 100f) + "%"; + hostResponse.setCpuAllocated(cpuAlloc); + String cpuWithOverprovisioning = new Float(host.getCpus() * host.getSpeed() * ApiDBUtils.getCpuOverprovisioningFactor()).toString(); + hostResponse.setCpuWithOverprovisioning(cpuWithOverprovisioning); + } + + if (details.contains(HostDetails.all) || details.contains(HostDetails.stats)) { + // set CPU/RAM/Network stats + String cpuUsed = null; + HostStats hostStats = ApiDBUtils.getHostStatistics(host.getId()); + if (hostStats != null) { + float cpuUtil = (float) hostStats.getCpuUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + hostResponse.setCpuUsed(cpuUsed); + hostResponse.setMemoryUsed((new Double(hostStats.getUsedMemory())).longValue()); + hostResponse.setNetworkKbsRead((new Double(hostStats.getNetworkReadKBs())).longValue()); + hostResponse.setNetworkKbsWrite((new Double(hostStats.getNetworkWriteKBs())).longValue()); + + } + } + + } else if (host.getType() == Host.Type.SecondaryStorage) { + StorageStats secStorageStats = ApiDBUtils.getSecondaryStorageStatistics(host.getId()); + if (secStorageStats != null) { + hostResponse.setDiskSizeTotal(secStorageStats.getCapacityBytes()); + hostResponse.setDiskSizeAllocated(secStorageStats.getByteUsed()); + } + } + + hostResponse.setLocalStorageActive(ApiDBUtils.isLocalStorageActiveOnHost(host.getId())); + + if (details.contains(HostDetails.all) || details.contains(HostDetails.events)) { + Set possibleEvents = host.getStatus().getPossibleEvents(); + if ((possibleEvents != null) && !possibleEvents.isEmpty()) { + String events = ""; + Iterator iter = possibleEvents.iterator(); + while (iter.hasNext()) { + com.cloud.host.Status.Event event = iter.next(); + events += event.toString(); + if (iter.hasNext()) { + events += "; "; + } + } + hostResponse.setEvents(events); + } + } + + hostResponse.setResourceState(host.getResourceState().toString()); + + // set async job + hostResponse.setJobId(host.getJobUuid()); + hostResponse.setJobStatus(host.getJobStatus()); + + hostResponse.setObjectName("host"); + + return hostResponse; + } + + + + + + + @Override + public HostResponse setHostResponse(HostResponse response, HostJoinVO host) { + String tag = host.getTag(); + if (tag != null) { + if ( response.getHostTags() != null && response.getHostTags().length() > 0){ + response.setHostTags(response.getHostTags() + "," + tag); + } + else{ + response.setHostTags(tag); + } + } + return response; + } + + + + @Override + public List newHostView(Host host) { + SearchCriteria sc = hostIdSearch.create(); + sc.setParameters("id", host.getId()); + return searchIncludingRemoved(sc, null, null, false); + + } + + + + @Override + public List searchByIds(Long... hostIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( hostIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= hostIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = hostIds[j]; + } + SearchCriteria sc = hostSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < hostIds.length) { + int batch_size = (hostIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = hostIds[j]; + } + SearchCriteria sc = hostSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java new file mode 100644 index 00000000000..78ceab16c42 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDao.java @@ -0,0 +1,32 @@ +// 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.query.dao; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; + +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.InstanceGroup; + +public interface InstanceGroupJoinDao extends GenericDao { + + InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO group); + + InstanceGroupJoinVO newInstanceGroupView(InstanceGroup group); + + +} diff --git a/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java new file mode 100644 index 00000000000..f83ef6cd8fd --- /dev/null +++ b/server/src/com/cloud/api/query/dao/InstanceGroupJoinDaoImpl.java @@ -0,0 +1,82 @@ +// 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.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.InstanceGroupJoinVO; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; + +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.InstanceGroup; + + +@Local(value={InstanceGroupJoinDao.class}) +public class InstanceGroupJoinDaoImpl extends GenericDaoBase implements InstanceGroupJoinDao { + public static final Logger s_logger = Logger.getLogger(InstanceGroupJoinDaoImpl.class); + + private SearchBuilder vrIdSearch; + + + protected InstanceGroupJoinDaoImpl() { + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + this._count = "select count(distinct id) from instance_group_view WHERE "; + } + + + + @Override + public InstanceGroupResponse newInstanceGroupResponse(InstanceGroupJoinVO group) { + InstanceGroupResponse groupResponse = new InstanceGroupResponse(); + groupResponse.setId(group.getUuid()); + groupResponse.setName(group.getName()); + groupResponse.setCreated(group.getCreated()); + + ApiResponseHelper.populateOwner(groupResponse, group); + + groupResponse.setObjectName("instancegroup"); + return groupResponse; + } + + + + @Override + public InstanceGroupJoinVO newInstanceGroupView(InstanceGroup group) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", group.getId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No vm group found for group id " + group.getId(); + return grps.get(0); + + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java new file mode 100644 index 00000000000..d8fa0f8acb1 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDao.java @@ -0,0 +1,32 @@ +// 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.query.dao; + +import org.apache.cloudstack.api.response.ProjectAccountResponse; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.projects.ProjectAccount; +import com.cloud.utils.db.GenericDao; + +public interface ProjectAccountJoinDao extends GenericDao { + + ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj); + + ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj); + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java new file mode 100644 index 00000000000..f808da0c5f1 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectAccountJoinDaoImpl.java @@ -0,0 +1,86 @@ +// 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.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.response.ProjectAccountResponse; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.projects.ProjectAccount; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectAccountJoinDao.class}) +public class ProjectAccountJoinDaoImpl extends GenericDaoBase implements ProjectAccountJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectAccountJoinDaoImpl.class); + + + private SearchBuilder paIdSearch; + + protected ProjectAccountJoinDaoImpl() { + + paIdSearch = createSearchBuilder(); + paIdSearch.and("accountId", paIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + paIdSearch.and("projectId", paIdSearch.entity().getProjectId(), SearchCriteria.Op.EQ); + paIdSearch.done(); + + this._count = "select count(distinct id) from project_account_view WHERE "; + } + + + + + @Override + public ProjectAccountResponse newProjectAccountResponse(ProjectAccountJoinVO proj) { + ProjectAccountResponse projectAccountResponse = new ProjectAccountResponse(); + + projectAccountResponse.setProjectId(proj.getProjectUuid()); + projectAccountResponse.setProjectName(proj.getProjectName()); + + projectAccountResponse.setAccountId(proj.getAccountUuid()); + projectAccountResponse.setAccountName(proj.getAccountName()); + projectAccountResponse.setAccountType(proj.getAccountType()); + projectAccountResponse.setRole(proj.getAccountRole().toString()); + projectAccountResponse.setDomainId(proj.getDomainUuid()); + projectAccountResponse.setDomainName(proj.getDomainName()); + + projectAccountResponse.setObjectName("projectaccount"); + + return projectAccountResponse; + } + + + + + @Override + public ProjectAccountJoinVO newProjectAccountView(ProjectAccount proj) { + SearchCriteria sc = paIdSearch.create(); + sc.setParameters("accountId", proj.getAccountId()); + sc.setParameters("projectId", proj.getProjectId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No project account found for account id = " + proj.getAccountId() + " and project id = " + proj.getProjectId(); + return grps.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java new file mode 100644 index 00000000000..ae81f0eae3b --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDao.java @@ -0,0 +1,30 @@ +// 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.query.dao; + +import org.apache.cloudstack.api.response.ProjectInvitationResponse; + +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.projects.ProjectInvitation; +import com.cloud.utils.db.GenericDao; + +public interface ProjectInvitationJoinDao extends GenericDao { + + ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO proj); + + ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj); +} diff --git a/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java new file mode 100644 index 00000000000..ebf64d1ce55 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectInvitationJoinDaoImpl.java @@ -0,0 +1,84 @@ +// 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.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.response.ProjectInvitationResponse; + +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.projects.ProjectInvitation; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectInvitationJoinDao.class}) +public class ProjectInvitationJoinDaoImpl extends GenericDaoBase implements ProjectInvitationJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectInvitationJoinDaoImpl.class); + + + private SearchBuilder piIdSearch; + + protected ProjectInvitationJoinDaoImpl() { + + piIdSearch = createSearchBuilder(); + piIdSearch.and("id", piIdSearch.entity().getId(), SearchCriteria.Op.EQ); + piIdSearch.done(); + + this._count = "select count(distinct id) from project_invitation_view WHERE "; + } + + + + @Override + public ProjectInvitationResponse newProjectInvitationResponse(ProjectInvitationJoinVO invite) { + ProjectInvitationResponse response = new ProjectInvitationResponse(); + response.setId(invite.getUuid()); + response.setProjectId(invite.getProjectUuid()); + response.setProjectName(invite.getProjectName()); + response.setInvitationState(invite.getState().toString()); + + if (invite.getAccountName() != null) { + response.setAccountName(invite.getAccountName()); + } else { + response.setEmail(invite.getEmail()); + } + + response.setDomainId(invite.getDomainUuid()); + response.setDomainName(invite.getDomainName()); + + response.setObjectName("projectinvitation"); + return response; + } + + + + @Override + public ProjectInvitationJoinVO newProjectInvitationView(ProjectInvitation proj) { + SearchCriteria sc = piIdSearch.create(); + sc.setParameters("id", proj.getId()); + List grps = searchIncludingRemoved(sc, null, null, false); + assert grps != null && grps.size() == 1 : "No project invitation found for id " + proj.getId(); + return grps.get(0); + } + + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectJoinDao.java b/server/src/com/cloud/api/query/dao/ProjectJoinDao.java new file mode 100644 index 00000000000..9eeb8aa65f2 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectJoinDao.java @@ -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 permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.ProjectResponse; + +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.projects.Project; +import com.cloud.utils.db.GenericDao; + +public interface ProjectJoinDao extends GenericDao { + + ProjectResponse newProjectResponse(ProjectJoinVO proj); + + ProjectResponse setProjectResponse(ProjectResponse rsp, ProjectJoinVO proj); + + List newProjectView(Project proj); + + List searchByIds(Long... ids); + +} diff --git a/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java new file mode 100644 index 00000000000..15bff3677fe --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ProjectJoinDaoImpl.java @@ -0,0 +1,153 @@ +// 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.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.ProjectJoinVO; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.ProjectResponse; +import com.cloud.projects.Project; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={ProjectJoinDao.class}) +public class ProjectJoinDaoImpl extends GenericDaoBase implements ProjectJoinDao { + public static final Logger s_logger = Logger.getLogger(ProjectJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder prjSearch; + + private SearchBuilder prjIdSearch; + + protected ProjectJoinDaoImpl() { + + prjSearch = createSearchBuilder(); + prjSearch.and("idIN", prjSearch.entity().getId(), SearchCriteria.Op.IN); + prjSearch.done(); + + prjIdSearch = createSearchBuilder(); + prjIdSearch.and("id", prjIdSearch.entity().getId(), SearchCriteria.Op.EQ); + prjIdSearch.done(); + + this._count = "select count(distinct id) from project_view WHERE "; + } + + @Override + public ProjectResponse newProjectResponse(ProjectJoinVO proj) { + ProjectResponse response = new ProjectResponse(); + response.setId(proj.getUuid()); + response.setName(proj.getName()); + response.setDisplaytext(proj.getDisplayText()); + if (proj.getState() != null) { + response.setState(proj.getState().toString()); + } + response.setDomainId(proj.getDomainUuid()); + response.setDomain(proj.getDomainName()); + + response.setOwner(proj.getOwner()); + + // update tag information + Long tag_id = proj.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + response.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + response.setObjectName("project"); + return response; + } + + @Override + public ProjectResponse setProjectResponse(ProjectResponse rsp, ProjectJoinVO proj) { + // update tag information + Long tag_id = proj.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + rsp.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return rsp; + } + + @Override + public List newProjectView(Project proj) { + SearchCriteria sc = prjIdSearch.create(); + sc.setParameters("id", proj.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + @Override + public List searchByIds(Long... prjIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( prjIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= prjIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = prjIds[j]; + } + SearchCriteria sc = prjSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < prjIds.length) { + int batch_size = (prjIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = prjIds[j]; + } + SearchCriteria sc = prjSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + +} diff --git a/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java b/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java new file mode 100644 index 00000000000..57fc130de55 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ResourceTagJoinDao.java @@ -0,0 +1,34 @@ +// 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.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.ResourceTagResponse; + +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.server.ResourceTag; +import com.cloud.utils.db.GenericDao; + +public interface ResourceTagJoinDao extends GenericDao { + + ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO uvo, boolean keyValueOnly ); + + ResourceTagJoinVO newResourceTagView(ResourceTag vr); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java new file mode 100644 index 00000000000..5adee9ee170 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/ResourceTagJoinDaoImpl.java @@ -0,0 +1,146 @@ +// 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.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.ResourceTagResponse; +import com.cloud.server.ResourceTag; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={ResourceTagJoinDao.class}) +public class ResourceTagJoinDaoImpl extends GenericDaoBase implements ResourceTagJoinDao { + public static final Logger s_logger = Logger.getLogger(ResourceTagJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder tagSearch; + + private SearchBuilder tagIdSearch; + + protected ResourceTagJoinDaoImpl() { + + tagSearch = createSearchBuilder(); + tagSearch.and("idIN", tagSearch.entity().getId(), SearchCriteria.Op.IN); + tagSearch.done(); + + tagIdSearch = createSearchBuilder(); + tagIdSearch.and("id", tagIdSearch.entity().getId(), SearchCriteria.Op.EQ); + tagIdSearch.done(); + + this._count = "select count(distinct id) from resource_tag_view WHERE "; + } + + + + + + @Override + public ResourceTagResponse newResourceTagResponse(ResourceTagJoinVO resourceTag, boolean keyValueOnly) { + ResourceTagResponse response = new ResourceTagResponse(); + response.setKey(resourceTag.getKey()); + response.setValue(resourceTag.getValue()); + + if (!keyValueOnly) { + response.setResourceType(resourceTag.getResourceType().toString()); + response.setResourceId(resourceTag.getResourceUuid()); + + ApiResponseHelper.populateOwner(response, resourceTag); + + response.setDomainId(resourceTag.getDomainUuid()); + response.setDomainName(resourceTag.getDomainName()); + + response.setCustomer(resourceTag.getCustomer()); + } + + response.setObjectName("tag"); + + return response; + } + + + @Override + public List searchByIds(Long... tagIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( tagIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= tagIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = tagIds[j]; + } + SearchCriteria sc = tagSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < tagIds.length) { + int batch_size = (tagIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = tagIds[j]; + } + SearchCriteria sc = tagSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + @Override + public ResourceTagJoinVO newResourceTagView(ResourceTag vr) { + + SearchCriteria sc = tagIdSearch.create(); + sc.setParameters("id", vr.getId()); + List vms = searchIncludingRemoved(sc, null, null, false); + assert vms != null && vms.size() == 1 : "No tag found for tag id " + vr.getId(); + return vms.get(0); + + } + +} diff --git a/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java new file mode 100644 index 00000000000..de1b72ae487 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDao.java @@ -0,0 +1,38 @@ +// 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.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.SecurityGroupResponse; + +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.network.security.SecurityGroup; +import com.cloud.user.Account; +import com.cloud.utils.db.GenericDao; + +public interface SecurityGroupJoinDao extends GenericDao { + + SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller); + + SecurityGroupResponse setSecurityGroupResponse(SecurityGroupResponse vsgData, SecurityGroupJoinVO vsg); + + List newSecurityGroupView(SecurityGroup sg); + + List searchByIds(Long... ids); +} + diff --git a/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java new file mode 100644 index 00000000000..c35c4aae297 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/SecurityGroupJoinDaoImpl.java @@ -0,0 +1,225 @@ +// 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.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.SecurityGroupJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; +import com.cloud.network.security.SecurityGroup; +import com.cloud.network.security.SecurityRule.SecurityRuleType; +import com.cloud.user.Account; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={SecurityGroupJoinDao.class}) +public class SecurityGroupJoinDaoImpl extends GenericDaoBase implements SecurityGroupJoinDao { + public static final Logger s_logger = Logger.getLogger(SecurityGroupJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder sgSearch; + + private SearchBuilder sgIdSearch; + + protected SecurityGroupJoinDaoImpl() { + + sgSearch = createSearchBuilder(); + sgSearch.and("idIN", sgSearch.entity().getId(), SearchCriteria.Op.IN); + sgSearch.done(); + + sgIdSearch = createSearchBuilder(); + sgIdSearch.and("id", sgIdSearch.entity().getId(), SearchCriteria.Op.EQ); + sgIdSearch.done(); + + this._count = "select count(distinct id) from security_group_view WHERE "; + } + + @Override + public SecurityGroupResponse newSecurityGroupResponse(SecurityGroupJoinVO vsg, Account caller) { + SecurityGroupResponse sgResponse = new SecurityGroupResponse(); + sgResponse.setId(vsg.getUuid()); + sgResponse.setName(vsg.getName()); + sgResponse.setDescription(vsg.getDescription()); + + ApiResponseHelper.populateOwner(sgResponse, vsg); + + Long rule_id = vsg.getRuleId(); + if (rule_id != null && rule_id.longValue() > 0) { + SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); + ruleData.setRuleId(vsg.getRuleUuid()); + ruleData.setProtocol(vsg.getRuleProtocol()); + + if ("icmp".equalsIgnoreCase(vsg.getRuleProtocol())) { + ruleData.setIcmpType(vsg.getRuleStartPort()); + ruleData.setIcmpCode(vsg.getRuleEndPort()); + } else { + ruleData.setStartPort(vsg.getRuleStartPort()); + ruleData.setEndPort(vsg.getRuleEndPort()); + } + + if (vsg.getRuleAllowedNetworkId() != null) { + List sgs = this.searchByIds(vsg.getRuleAllowedNetworkId()); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + ruleData.setSecurityGroupName(sg.getName()); + ruleData.setAccountName(sg.getAccountName()); + } + } else { + ruleData.setCidr(vsg.getRuleAllowedSourceIpCidr()); + } + + if (vsg.getRuleType() == SecurityRuleType.IngressRule) { + ruleData.setObjectName("ingressrule"); + sgResponse.addSecurityGroupIngressRule(ruleData); + } else { + ruleData.setObjectName("egressrule"); + sgResponse.addSecurityGroupEgressRule(ruleData); + } + } + + // update tag information + Long tag_id = vsg.getTagId(); + if (tag_id != null && tag_id.longValue() > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + sgResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + // set async job + sgResponse.setJobId(vsg.getJobUuid()); + sgResponse.setJobStatus(vsg.getJobStatus()); + + sgResponse.setObjectName("securitygroup"); + + return sgResponse; + } + + @Override + public SecurityGroupResponse setSecurityGroupResponse(SecurityGroupResponse vsgData, SecurityGroupJoinVO vsg) { + Long rule_id = vsg.getRuleId(); + if (rule_id != null && rule_id.longValue() > 0) { + SecurityGroupRuleResponse ruleData = new SecurityGroupRuleResponse(); + ruleData.setRuleId(vsg.getRuleUuid()); + ruleData.setProtocol(vsg.getRuleProtocol()); + + if ("icmp".equalsIgnoreCase(vsg.getRuleProtocol())) { + ruleData.setIcmpType(vsg.getRuleStartPort()); + ruleData.setIcmpCode(vsg.getRuleEndPort()); + } else { + ruleData.setStartPort(vsg.getRuleStartPort()); + ruleData.setEndPort(vsg.getRuleEndPort()); + } + + if (vsg.getRuleAllowedNetworkId() != null) { + List sgs = this.searchByIds(vsg.getRuleAllowedNetworkId()); + if (sgs != null && sgs.size() > 0) { + SecurityGroupJoinVO sg = sgs.get(0); + ruleData.setSecurityGroupName(sg.getName()); + ruleData.setAccountName(sg.getAccountName()); + } + } else { + ruleData.setCidr(vsg.getRuleAllowedSourceIpCidr()); + } + + if (vsg.getRuleType() == SecurityRuleType.IngressRule) { + ruleData.setObjectName("ingressrule"); + vsgData.addSecurityGroupIngressRule(ruleData); + } else { + ruleData.setObjectName("egressrule"); + vsgData.addSecurityGroupEgressRule(ruleData); + } + } + + // update tag information + Long tag_id = vsg.getTagId(); + if (tag_id != null && tag_id.longValue() > 0 ) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + vsgData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return vsgData; + } + + @Override + public List newSecurityGroupView(SecurityGroup sg) { + + SearchCriteria sc = sgIdSearch.create(); + sc.setParameters("id", sg.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + @Override + public List searchByIds(Long... sgIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( sgIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= sgIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = sgIds[j]; + } + SearchCriteria sc = sgSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < sgIds.length) { + int batch_size = (sgIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = sgIds[j]; + } + SearchCriteria sc = sgSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } +} diff --git a/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java b/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java new file mode 100644 index 00000000000..b48f19272bc --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserAccountJoinDao.java @@ -0,0 +1,38 @@ +// 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.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.UserResponse; + +import com.cloud.api.query.vo.UserAccountJoinVO; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.utils.db.GenericDao; + +public interface UserAccountJoinDao extends GenericDao { + + UserResponse newUserResponse(UserAccountJoinVO usr); + + UserAccountJoinVO newUserView(User usr); + + UserAccountJoinVO newUserView(UserAccount usr); + + List searchByAccountId(Long accountId); + +} diff --git a/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java new file mode 100644 index 00000000000..b1f5dcafeb3 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserAccountJoinDaoImpl.java @@ -0,0 +1,129 @@ +// 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.query.dao; + +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.InstanceGroupJoinVO; +import com.cloud.api.query.vo.UserAccountJoinVO; + +import org.apache.cloudstack.api.response.InstanceGroupResponse; +import org.apache.cloudstack.api.response.UserResponse; + +import com.cloud.user.Account; +import com.cloud.user.User; +import com.cloud.user.UserAccount; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.InstanceGroup; + + +@Local(value={UserAccountJoinDao.class}) +public class UserAccountJoinDaoImpl extends GenericDaoBase implements UserAccountJoinDao { + public static final Logger s_logger = Logger.getLogger(UserAccountJoinDaoImpl.class); + + + private SearchBuilder vrIdSearch; + + private SearchBuilder vrAcctIdSearch; + + + protected UserAccountJoinDaoImpl() { + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + vrAcctIdSearch = createSearchBuilder(); + vrAcctIdSearch.and("accountid", vrAcctIdSearch.entity().getAccountId(), SearchCriteria.Op.EQ); + vrAcctIdSearch.done(); + + + this._count = "select count(distinct id) from user_view WHERE "; + } + + + + @Override + public UserResponse newUserResponse(UserAccountJoinVO usr) { + UserResponse userResponse = new UserResponse(); + userResponse.setAccountId(usr.getAccountUuid()); + userResponse.setAccountName(usr.getAccountName()); + userResponse.setAccountType(usr.getAccountType()); + userResponse.setCreated(usr.getCreated()); + userResponse.setDomainId(usr.getDomainUuid()); + userResponse.setDomainName(usr.getDomainName()); + userResponse.setEmail(usr.getEmail()); + userResponse.setFirstname(usr.getFirstname()); + userResponse.setId(usr.getUuid()); + userResponse.setLastname(usr.getLastname()); + userResponse.setState(usr.getState().toString()); + userResponse.setTimezone(usr.getTimezone()); + userResponse.setUsername(usr.getUsername()); + userResponse.setApiKey(usr.getApiKey()); + userResponse.setSecretKey(usr.getSecretKey()); + + // set async job + userResponse.setJobId(usr.getJobUuid()); + userResponse.setJobStatus(usr.getJobStatus()); + + userResponse.setObjectName("user"); + + return userResponse; + } + + + @Override + public UserAccountJoinVO newUserView(User usr) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", usr.getId()); + List users = searchIncludingRemoved(sc, null, null, false); + assert users != null && users.size() == 1 : "No user found for user id " + usr.getId(); + return users.get(0); + } + + + + + @Override + public UserAccountJoinVO newUserView(UserAccount usr) { + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", usr.getId()); + List users = searchIncludingRemoved(sc, null, null, false); + assert users != null && users.size() == 1 : "No user found for user id " + usr.getId(); + return users.get(0); + } + + + @Override + public List searchByAccountId(Long accountId) { + SearchCriteria sc = vrAcctIdSearch.create(); + sc.setParameters("accountId", accountId); + return searchIncludingRemoved(sc, null, null, false); + } + + + + +} diff --git a/server/src/com/cloud/api/query/dao/UserVmJoinDao.java b/server/src/com/cloud/api/query/dao/UserVmJoinDao.java new file mode 100644 index 00000000000..2617a7475ef --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserVmJoinDao.java @@ -0,0 +1,39 @@ +// 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.query.dao; + +import java.util.EnumSet; +import java.util.List; + +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.UserVmResponse; + +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; +import com.cloud.utils.db.GenericDao; + +public interface UserVmJoinDao extends GenericDao { + + UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller); + + UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo); + + List newUserVmView(UserVm... userVms); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java new file mode 100644 index 00000000000..3310518ee79 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/UserVmJoinDaoImpl.java @@ -0,0 +1,331 @@ +// 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.query.dao; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Set; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.UserVmJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.ApiConstants.VMDetails; +import org.apache.cloudstack.api.response.NicResponse; +import org.apache.cloudstack.api.response.SecurityGroupResponse; +import org.apache.cloudstack.api.response.UserVmResponse; +import com.cloud.user.Account; +import com.cloud.uservm.UserVm; +import com.cloud.utils.component.ComponentLocator; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.vm.VmStats; + + +@Local(value={UserVmJoinDao.class}) +public class UserVmJoinDaoImpl extends GenericDaoBase implements UserVmJoinDao { + public static final Logger s_logger = Logger.getLogger(UserVmJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder VmDetailSearch; + + protected UserVmJoinDaoImpl() { + + VmDetailSearch = createSearchBuilder(); + VmDetailSearch.and("idIN", VmDetailSearch.entity().getId(), SearchCriteria.Op.IN); + VmDetailSearch.done(); + + this._count = "select count(distinct id) from user_vm_view WHERE "; + + + } + + public UserVmResponse newUserVmResponse(String objectName, UserVmJoinVO userVm, EnumSet details, Account caller) { + UserVmResponse userVmResponse = new UserVmResponse(); + + if (userVm.getHypervisorType() != null){ + userVmResponse.setHypervisor(userVm.getHypervisorType().toString()); + } + userVmResponse.setId(userVm.getUuid()); + userVmResponse.setName(userVm.getName()); + + userVmResponse.setDisplayName(userVm.getDisplayName()); + + if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + userVmResponse.setProjectId(userVm.getProjectUuid()); + userVmResponse.setProjectName(userVm.getProjectName()); + } else { + userVmResponse.setAccountName(userVm.getAccountName()); + } + + userVmResponse.setDomainId(userVm.getDomainUuid()); + userVmResponse.setDomainName(userVm.getDomainName()); + + userVmResponse.setCreated(userVm.getCreated()); + + if (userVm.getState() != null) { + userVmResponse.setState(userVm.getState().toString()); + } + userVmResponse.setHaEnable(userVm.isHaEnabled()); + if (details.contains(VMDetails.all) || details.contains(VMDetails.group)) { + userVmResponse.setGroupId(userVm.getInstanceGroupUuid()); + userVmResponse.setGroup(userVm.getInstanceGroupName()); + } + userVmResponse.setZoneId(userVm.getDataCenterUuid()); + userVmResponse.setZoneName(userVm.getDataCenterName()); + if ((caller == null) || (caller.getType() == Account.ACCOUNT_TYPE_ADMIN)) { + userVmResponse.setInstanceName(userVm.getInstanceName()); + userVmResponse.setHostId(userVm.getHostUuid()); + userVmResponse.setHostName(userVm.getHostName()); + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.tmpl)) { + userVmResponse.setTemplateId(userVm.getTemplateUuid()); + userVmResponse.setTemplateName(userVm.getTemplateName()); + userVmResponse.setTemplateDisplayText(userVm.getTemplateDisplayText()); + userVmResponse.setPasswordEnabled(userVm.isPasswordEnabled()); + } + if (details.contains(VMDetails.all) || details.contains(VMDetails.iso)) { + userVmResponse.setIsoId(userVm.getIsoUuid()); + userVmResponse.setIsoName(userVm.getIsoName()); + userVmResponse.setIsoDisplayText(userVm.getIsoDisplayText()); + } + if (details.contains(VMDetails.all) || details.contains(VMDetails.servoff)) { + userVmResponse.setServiceOfferingId(userVm.getServiceOfferingUuid()); + userVmResponse.setServiceOfferingName(userVm.getServiceOfferingName()); + userVmResponse.setCpuNumber(userVm.getCpu()); + userVmResponse.setCpuSpeed(userVm.getSpeed()); + userVmResponse.setMemory(userVm.getRamSize()); + } + userVmResponse.setGuestOsId(userVm.getGuestOsUuid()); + if (details.contains(VMDetails.all) || details.contains(VMDetails.volume)) { + userVmResponse.setRootDeviceId(userVm.getVolumeDeviceId()); + if (userVm.getVolumeType() != null) { + userVmResponse.setRootDeviceType(userVm.getVolumeType().toString()); + } + } + userVmResponse.setPassword(userVm.getPassword()); + userVmResponse.setJobId(userVm.getJobUuid()); + userVmResponse.setJobStatus(userVm.getJobStatus()); + //userVmResponse.setForVirtualNetwork(userVm.getForVirtualNetwork()); + + userVmResponse.setPublicIpId(userVm.getPublicIpUuid()); + userVmResponse.setPublicIp(userVm.getPublicIpAddress()); + userVmResponse.setKeyPairName(userVm.getKeypairName()); + + if (details.contains(VMDetails.all) || details.contains(VMDetails.stats)) { + DecimalFormat decimalFormat = new DecimalFormat("#.##"); + // stats calculation + String cpuUsed = null; + VmStats vmStats = ApiDBUtils.getVmStatistics(userVm.getId()); + if (vmStats != null) { + float cpuUtil = (float) vmStats.getCPUUtilization(); + cpuUsed = decimalFormat.format(cpuUtil) + "%"; + userVmResponse.setCpuUsed(cpuUsed); + + Double networkKbRead = Double.valueOf(vmStats.getNetworkReadKBs()); + userVmResponse.setNetworkKbsRead(networkKbRead.longValue()); + + Double networkKbWrite = Double.valueOf(vmStats.getNetworkWriteKBs()); + userVmResponse.setNetworkKbsWrite(networkKbWrite.longValue()); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.secgrp)) { + Long securityGroupId = userVm.getSecurityGroupId(); + if (securityGroupId != null && securityGroupId.longValue() != 0) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(userVm.getSecurityGroupUuid()); + resp.setName(userVm.getSecurityGroupName()); + resp.setDescription(userVm.getSecurityGroupDescription()); + resp.setObjectName("securitygroup"); + if (userVm.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + resp.setProjectId(userVm.getProjectUuid()); + resp.setProjectName(userVm.getProjectName()); + } else { + resp.setAccountName(userVm.getAccountName()); + } + userVmResponse.addSecurityGroup(resp); + } + } + + if (details.contains(VMDetails.all) || details.contains(VMDetails.nics)) { + long nic_id = userVm.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(userVm.getNicUuid()); + nicResponse.setIpaddress(userVm.getIpAddress()); + nicResponse.setGateway(userVm.getGateway()); + nicResponse.setNetmask(userVm.getNetmask()); + nicResponse.setNetworkid(userVm.getNetworkUuid()); + nicResponse.setMacAddress(userVm.getMacAddress()); + if (userVm.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(userVm.getBroadcastUri().toString()); + } + if (userVm.getIsolationUri() != null) { + nicResponse.setIsolationUri(userVm.getIsolationUri().toString()); + } + if (userVm.getTrafficType() != null) { + nicResponse.setTrafficType(userVm.getTrafficType().toString()); + } + if (userVm.getGuestType() != null) { + nicResponse.setType(userVm.getGuestType().toString()); + } + nicResponse.setIsDefault(userVm.isDefaultNic()); + nicResponse.setObjectName("nic"); + userVmResponse.addNic(nicResponse); + } + } + + // update tag information + long tag_id = userVm.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + userVmResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + userVmResponse.setObjectName(objectName); + + return userVmResponse; + } + + public UserVmResponse setUserVmResponse(UserVmResponse userVmData, UserVmJoinVO uvo) { + Long securityGroupId = uvo.getSecurityGroupId(); + if (securityGroupId != null && securityGroupId.longValue() != 0) { + SecurityGroupResponse resp = new SecurityGroupResponse(); + resp.setId(uvo.getSecurityGroupUuid()); + resp.setName(uvo.getSecurityGroupName()); + resp.setDescription(uvo.getSecurityGroupDescription()); + resp.setObjectName("securitygroup"); + if (uvo.getAccountType() == Account.ACCOUNT_TYPE_PROJECT) { + resp.setProjectId(uvo.getProjectUuid()); + resp.setProjectName(uvo.getProjectName()); + } else { + resp.setAccountName(uvo.getAccountName()); + } + userVmData.addSecurityGroup(resp); + } + + long nic_id = uvo.getNicId(); + if (nic_id > 0) { + NicResponse nicResponse = new NicResponse(); + nicResponse.setId(uvo.getNicUuid()); + nicResponse.setIpaddress(uvo.getIpAddress()); + nicResponse.setGateway(uvo.getGateway()); + nicResponse.setNetmask(uvo.getNetmask()); + nicResponse.setNetworkid(uvo.getNetworkUuid()); + nicResponse.setMacAddress(uvo.getMacAddress()); + if (uvo.getBroadcastUri() != null) { + nicResponse.setBroadcastUri(uvo.getBroadcastUri().toString()); + } + if (uvo.getIsolationUri() != null) { + nicResponse.setIsolationUri(uvo.getIsolationUri().toString()); + } + if (uvo.getTrafficType() != null) { + nicResponse.setTrafficType(uvo.getTrafficType().toString()); + } + if (uvo.getGuestType() != null) { + nicResponse.setType(uvo.getGuestType().toString()); + } + nicResponse.setIsDefault(uvo.isDefaultNic()); + nicResponse.setObjectName("nic"); + userVmData.addNic(nicResponse); + } + + long tag_id = uvo.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + userVmData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return userVmData; + } + + + @Override + public List searchByIds(Long... vmIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( vmIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= vmIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = vmIds[j]; + } + SearchCriteria sc = VmDetailSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < vmIds.length) { + int batch_size = (vmIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = vmIds[j]; + } + SearchCriteria sc = VmDetailSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + @Override + public List newUserVmView(UserVm... userVms) { + + Hashtable userVmDataHash = new Hashtable(); + for (UserVm vm : userVms){ + if ( !userVmDataHash.containsKey(vm.getId())){ + userVmDataHash.put(vm.getId(), vm); + } + } + + Set vmIdSet = userVmDataHash.keySet(); + return searchByIds(vmIdSet.toArray(new Long[vmIdSet.size()])); + } + +} diff --git a/server/src/com/cloud/api/query/dao/VolumeJoinDao.java b/server/src/com/cloud/api/query/dao/VolumeJoinDao.java new file mode 100644 index 00000000000..67509cf5b29 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/VolumeJoinDao.java @@ -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 permissions and limitations +// under the License. +package com.cloud.api.query.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.VolumeResponse; + + +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.storage.Volume; +import com.cloud.utils.db.GenericDao; + +public interface VolumeJoinDao extends GenericDao { + + VolumeResponse newVolumeResponse(VolumeJoinVO vol); + + VolumeResponse setVolumeResponse(VolumeResponse volData, VolumeJoinVO vol); + + List newVolumeView(Volume vol); + + List searchByIds(Long... ids); +} diff --git a/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java new file mode 100644 index 00000000000..35ba2eb4537 --- /dev/null +++ b/server/src/com/cloud/api/query/dao/VolumeJoinDaoImpl.java @@ -0,0 +1,279 @@ +// 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.query.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.ResourceTagJoinVO; +import com.cloud.api.query.vo.VolumeJoinVO; +import com.cloud.configuration.dao.ConfigurationDao; + +import org.apache.cloudstack.api.response.VolumeResponse; + +import com.cloud.offering.ServiceOffering; +import com.cloud.storage.Storage; +import com.cloud.storage.VMTemplateHostVO; +import com.cloud.storage.Volume; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.user.Account; +import com.cloud.user.UserContext; +import com.cloud.utils.component.Inject; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={VolumeJoinDao.class}) +public class VolumeJoinDaoImpl extends GenericDaoBase implements VolumeJoinDao { + public static final Logger s_logger = Logger.getLogger(VolumeJoinDaoImpl.class); + + @Inject + private ConfigurationDao _configDao; + + private SearchBuilder volSearch; + + private SearchBuilder volIdSearch; + + protected VolumeJoinDaoImpl() { + + volSearch = createSearchBuilder(); + volSearch.and("idIN", volSearch.entity().getId(), SearchCriteria.Op.IN); + volSearch.done(); + + volIdSearch = createSearchBuilder(); + volIdSearch.and("id", volIdSearch.entity().getId(), SearchCriteria.Op.EQ); + volIdSearch.done(); + + this._count = "select count(distinct id) from volume_view WHERE "; + } + + + + + @Override + public VolumeResponse newVolumeResponse(VolumeJoinVO volume) { + Account caller = UserContext.current().getCaller(); + + VolumeResponse volResponse = new VolumeResponse(); + volResponse.setId(volume.getUuid()); + + if (volume.getName() != null) { + volResponse.setName(volume.getName()); + } else { + volResponse.setName(""); + } + + volResponse.setZoneId(volume.getDataCenterUuid()); + volResponse.setZoneName(volume.getDataCenterName()); + + volResponse.setVolumeType(volume.getVolumeType().toString()); + volResponse.setDeviceId(volume.getDeviceId()); + + long instanceId = volume.getVmId(); + if (instanceId > 0 && volume.getState() != Volume.State.Destroy) { + volResponse.setVirtualMachineId(volume.getVmUuid()); + volResponse.setVirtualMachineName(volume.getVmName()); + volResponse.setVirtualMachineState(volume.getVmState().toString()); + volResponse.setVirtualMachineDisplayName(volume.getVmDisplayName()); + } + + // Show the virtual size of the volume + volResponse.setSize(volume.getSize()); + + volResponse.setCreated(volume.getCreated()); + volResponse.setState(volume.getState().toString()); + if (volume.getState() == Volume.State.UploadOp) { + // com.cloud.storage.VolumeHostVO volumeHostRef = + // ApiDBUtils.findVolumeHostRef(volume.getId(), + // volume.getDataCenterId()); + volResponse.setSize(volume.getVolumeHostSize()); + volResponse.setCreated(volume.getVolumeHostCreated()); + + if (caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + volResponse.setHypervisor(ApiDBUtils.getHypervisorTypeFromFormat(volume.getFormat()).toString()); + if (volume.getDownloadState() != Status.DOWNLOADED) { + String volumeStatus = "Processing"; + if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOAD_IN_PROGRESS) { + if (volume.getDownloadPercent() == 100) { + volumeStatus = "Checking Volume"; + } else { + volumeStatus = volume.getDownloadPercent() + "% Uploaded"; + } + volResponse.setState("Uploading"); + } else { + volumeStatus = volume.getErrorString(); + if (volume.getDownloadState() == VMTemplateHostVO.Status.NOT_DOWNLOADED) { + volResponse.setState("UploadNotStarted"); + } else { + volResponse.setState("UploadError"); + } + } + volResponse.setStatus(volumeStatus); + } else if (volume.getDownloadState() == VMTemplateHostVO.Status.DOWNLOADED) { + volResponse.setStatus("Upload Complete"); + volResponse.setState("Uploaded"); + } else { + volResponse.setStatus("Successfully Installed"); + } + } + + // populate owner. + ApiResponseHelper.populateOwner(volResponse, volume); + + // DiskOfferingVO diskOffering = + // ApiDBUtils.findDiskOfferingById(volume.getDiskOfferingId()); + if (volume.getDiskOfferingId() > 0) { + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingId(volume.getDiskOfferingUuid()); + } else { + volResponse.setDiskOfferingId(volume.getDiskOfferingUuid()); + } + + if (volume.getVolumeType().equals(Volume.Type.ROOT)) { + volResponse.setServiceOfferingName(volume.getDiskOfferingName()); + volResponse.setServiceOfferingDisplayText(volume.getDiskOfferingDisplayText()); + } else { + volResponse.setDiskOfferingName(volume.getDiskOfferingName()); + volResponse.setDiskOfferingDisplayText(volume.getDiskOfferingDisplayText()); + } + volResponse.setStorageType(volume.isUseLocalStorage() ? ServiceOffering.StorageType.local.toString() : ServiceOffering.StorageType.shared + .toString()); + } + Long poolId = volume.getPoolId(); + String poolName = (poolId == null) ? "none" : volume.getPoolName(); + volResponse.setStoragePoolName(poolName); + + // return hypervisor for ROOT and Resource domain only + if ((caller.getType() == Account.ACCOUNT_TYPE_ADMIN || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + && volume.getState() != Volume.State.UploadOp && volume.getHypervisorType() != null) { + volResponse.setHypervisor(volume.getHypervisorType().toString()); + } + + volResponse.setAttached(volume.getAttached()); + volResponse.setDestroyed(volume.getState() == Volume.State.Destroy); + boolean isExtractable = true; + if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont + // have any + // template + // dependence. + if (volume.getTemplateId() > 0) { // For ISO based volumes template + // = null and we allow extraction + // of all ISO based volumes + isExtractable = volume.isExtractable() && volume.getTemplateType() != Storage.TemplateType.SYSTEM; + } + } + + // update tag information + long tag_id = volume.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if (vtag != null) { + volResponse.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + + volResponse.setExtractable(isExtractable); + + // set async job + volResponse.setJobId(volume.getJobUuid()); + volResponse.setJobStatus(volume.getJobStatus()); + + volResponse.setObjectName("volume"); + return volResponse; + } + + + + @Override + public VolumeResponse setVolumeResponse(VolumeResponse volData, VolumeJoinVO vol) { + long tag_id = vol.getTagId(); + if (tag_id > 0) { + ResourceTagJoinVO vtag = ApiDBUtils.findResourceTagViewById(tag_id); + if ( vtag != null ){ + volData.addTag(ApiDBUtils.newResourceTagResponse(vtag, false)); + } + } + return volData; + } + + + + + @Override + public List newVolumeView(Volume vol) { + SearchCriteria sc = volIdSearch.create(); + sc.setParameters("id", vol.getId()); + return searchIncludingRemoved(sc, null, null, false); + } + + + + + @Override + public List searchByIds(Long... volIds) { + // set detail batch query size + int DETAILS_BATCH_SIZE = 2000; + String batchCfg = _configDao.getValue("detail.batch.query.size"); + if ( batchCfg != null ){ + DETAILS_BATCH_SIZE = Integer.parseInt(batchCfg); + } + // query details by batches + List uvList = new ArrayList(); + // query details by batches + int curr_index = 0; + if ( volIds.length > DETAILS_BATCH_SIZE ){ + while ( (curr_index + DETAILS_BATCH_SIZE ) <= volIds.length ) { + Long[] ids = new Long[DETAILS_BATCH_SIZE]; + for (int k = 0, j = curr_index; j < curr_index + DETAILS_BATCH_SIZE; j++, k++) { + ids[k] = volIds[j]; + } + SearchCriteria sc = volSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + curr_index += DETAILS_BATCH_SIZE; + } + } + if (curr_index < volIds.length) { + int batch_size = (volIds.length - curr_index); + // set the ids value + Long[] ids = new Long[batch_size]; + for (int k = 0, j = curr_index; j < curr_index + batch_size; j++, k++) { + ids[k] = volIds[j]; + } + SearchCriteria sc = volSearch.create(); + sc.setParameters("idIN", ids); + List vms = searchIncludingRemoved(sc, null, null, false); + if (vms != null) { + uvList.addAll(vms); + } + } + return uvList; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/AccountJoinVO.java b/server/src/com/cloud/api/query/vo/AccountJoinVO.java new file mode 100644 index 00000000000..6d37f4de00e --- /dev/null +++ b/server/src/com/cloud/api/query/vo/AccountJoinVO.java @@ -0,0 +1,571 @@ +// 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.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import com.cloud.user.Account.State; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="account_view") +public class AccountJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="type") + private short type; + + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + private State state; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="cleanup_needed") + private boolean needsCleanup = false; + + @Column(name="network_domain") + private String networkDomain; + + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName; + + @Column(name="bytesReceived") + private Long bytesReceived; + + @Column(name="bytesSent") + private Long bytesSent; + + @Column(name="vmLimit") + private Long vmLimit; + + @Column(name="vmTotal") + private Long vmTotal; + + + @Column(name="ipLimit") + private Long ipLimit; + + @Column(name="ipTotal") + private Long ipTotal; + + @Column(name="ipFree") + private Long ipFree; + + @Column(name="volumeLimit") + private Long volumeLimit; + + @Column(name="volumeTotal") + private Long volumeTotal; + + @Column(name="snapshotLimit") + private Long snapshotLimit; + + @Column(name="snapshotTotal") + private Long snapshotTotal; + + @Column(name="templateLimit") + private Long templateLimit; + + @Column(name="templateTotal") + private Long templateTotal; + + @Column(name="stoppedVms") + private Integer vmStopped; + + @Column(name="runningVms") + private Integer vmRunning; + + @Column(name="projectLimit") + private Long projectLimit; + + @Column(name="projectTotal") + private Long projectTotal; + + + @Column(name="networkLimit") + private Long networkLimit; + + @Column(name="networkTotal") + private Long networkTotal; + + + @Column(name="vpcLimit") + private Long vpcLimit; + + @Column(name="vpcTotal") + private Long vpcTotal; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + public AccountJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getType() { + return type; + } + + + public void setType(short type) { + this.type = type; + } + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public boolean isNeedsCleanup() { + return needsCleanup; + } + + + public void setNeedsCleanup(boolean needsCleanup) { + this.needsCleanup = needsCleanup; + } + + + public String getNetworkDomain() { + return networkDomain; + } + + + public void setNetworkDomain(String networkDomain) { + this.networkDomain = networkDomain; + } + + + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public long getDataCenterId() { + return dataCenterId; + } + + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + public void setDataCenterUuid(String dataCenterUuid) { + this.dataCenterUuid = dataCenterUuid; + } + + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String dataCenterName) { + this.dataCenterName = dataCenterName; + } + + + public Long getBytesReceived() { + return bytesReceived; + } + + + public void setBytesReceived(Long bytesReceived) { + this.bytesReceived = bytesReceived; + } + + + public Long getBytesSent() { + return bytesSent; + } + + + public void setBytesSent(Long bytesSent) { + this.bytesSent = bytesSent; + } + + + + + public Long getVmTotal() { + return vmTotal; + } + + + public void setVmTotal(Long vmTotal) { + this.vmTotal = vmTotal; + } + + + + + + public Long getIpTotal() { + return ipTotal; + } + + + public void setIpTotal(Long ipTotal) { + this.ipTotal = ipTotal; + } + + + public Long getIpFree() { + return ipFree; + } + + + public void setIpFree(Long ipFree) { + this.ipFree = ipFree; + } + + + + public Long getVolumeTotal() { + return volumeTotal; + } + + + public void setVolumeTotal(Long volumeTotal) { + this.volumeTotal = volumeTotal; + } + + + + public Long getSnapshotTotal() { + return snapshotTotal; + } + + + public void setSnapshotTotal(Long snapshotTotal) { + this.snapshotTotal = snapshotTotal; + } + + + + + public Long getTemplateTotal() { + return templateTotal; + } + + + public void setTemplateTotal(Long templateTotal) { + this.templateTotal = templateTotal; + } + + + public Integer getVmStopped() { + return vmStopped; + } + + + public void setVmStopped(Integer vmStopped) { + this.vmStopped = vmStopped; + } + + + public Integer getVmRunning() { + return vmRunning; + } + + + public void setVmRunning(Integer vmRunning) { + this.vmRunning = vmRunning; + } + + + + public Long getProjectTotal() { + return projectTotal; + } + + + public void setProjectTotal(Long projectTotal) { + this.projectTotal = projectTotal; + } + + + + public Long getNetworkTotal() { + return networkTotal; + } + + + public void setNetworkTotal(Long networkTotal) { + this.networkTotal = networkTotal; + } + + + + public Long getVpcTotal() { + return vpcTotal; + } + + + public void setVpcTotal(Long vpcTotal) { + this.vpcTotal = vpcTotal; + } + + + public Long getVmLimit() { + return vmLimit; + } + + + public void setVmLimit(Long vmLimit) { + this.vmLimit = vmLimit; + } + + + public Long getIpLimit() { + return ipLimit; + } + + + public void setIpLimit(Long ipLimit) { + this.ipLimit = ipLimit; + } + + + public Long getVolumeLimit() { + return volumeLimit; + } + + + public void setVolumeLimit(Long volumeLimit) { + this.volumeLimit = volumeLimit; + } + + + public Long getSnapshotLimit() { + return snapshotLimit; + } + + + public void setSnapshotLimit(Long snapshotLimit) { + this.snapshotLimit = snapshotLimit; + } + + + public Long getTemplateLimit() { + return templateLimit; + } + + + public void setTemplateLimit(Long templateLimit) { + this.templateLimit = templateLimit; + } + + + public Long getProjectLimit() { + return projectLimit; + } + + + public void setProjectLimit(Long projectLimit) { + this.projectLimit = projectLimit; + } + + + public Long getNetworkLimit() { + return networkLimit; + } + + + public void setNetworkLimit(Long networkLimit) { + this.networkLimit = networkLimit; + } + + + public Long getVpcLimit() { + return vpcLimit; + } + + + public void setVpcLimit(Long vpcLimit) { + this.vpcLimit = vpcLimit; + } + + + public long getJobId() { + return jobId; + } + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + public String getJobUuid() { + return jobUuid; + } + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + public int getJobStatus() { + return jobStatus; + } + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + +} diff --git a/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java b/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java new file mode 100644 index 00000000000..39bcb1777e6 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/AsyncJobJoinVO.java @@ -0,0 +1,333 @@ +// 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.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.async.AsyncJob.Type; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="async_job_view") +public class AsyncJobJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + + @Column(name="user_id") + private long userId; + + @Column(name="user_uuid") + private String userUuid; + + @Column(name="job_cmd") + private String cmd; + + @Column(name="job_status") + private int status; + + @Column(name="job_process_status") + private int processStatus; + + @Column(name="job_result_code") + private int resultCode; + + @Column(name="job_result", length=65535) + private String result; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Enumerated(value=EnumType.STRING) + @Column(name="instance_type", length=64) + private Type instanceType; + + @Column(name="instance_id", length=64) + private Long instanceId; + + @Column(name="instance_uuid") + private String instanceUuid; + + + public AsyncJobJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + public String getAccountUuid() { + return accountUuid; + } + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public long getUserId() { + return userId; + } + + + public void setUserId(long userId) { + this.userId = userId; + } + + + public String getUserUuid() { + return userUuid; + } + + + public void setUserUuid(String userUuid) { + this.userUuid = userUuid; + } + + + public String getCmd() { + return cmd; + } + + + public void setCmd(String cmd) { + this.cmd = cmd; + } + + + public int getStatus() { + return status; + } + + + public void setStatus(int status) { + this.status = status; + } + + + public int getProcessStatus() { + return processStatus; + } + + + public void setProcessStatus(int processStatus) { + this.processStatus = processStatus; + } + + + public int getResultCode() { + return resultCode; + } + + + public void setResultCode(int resultCode) { + this.resultCode = resultCode; + } + + + public String getResult() { + return result; + } + + + public void setResult(String result) { + this.result = result; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public Type getInstanceType() { + return instanceType; + } + + + public void setInstanceType(Type instanceType) { + this.instanceType = instanceType; + } + + + public Long getInstanceId() { + return instanceId; + } + + + public void setInstanceId(Long instanceId) { + this.instanceId = instanceId; + } + + + public String getInstanceUuid() { + return instanceUuid; + } + + + public void setInstanceUuid(String instanceUuid) { + this.instanceUuid = instanceUuid; + } + +} diff --git a/server/src/com/cloud/api/query/vo/BaseViewVO.java b/server/src/com/cloud/api/query/vo/BaseViewVO.java new file mode 100644 index 00000000000..604f4597a0e --- /dev/null +++ b/server/src/com/cloud/api/query/vo/BaseViewVO.java @@ -0,0 +1,49 @@ +// 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.query.vo; + +import javax.persistence.Column; + +public abstract class BaseViewVO { + + public abstract long getId(); + + public abstract void setId(long id); + + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (getId() ^ (getId() >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + BaseViewVO other = (BaseViewVO) obj; + if (getId() != other.getId()) + return false; + return true; + } +} diff --git a/server/src/com/cloud/api/query/vo/ControlledViewEntity.java b/server/src/com/cloud/api/query/vo/ControlledViewEntity.java new file mode 100644 index 00000000000..12557504807 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ControlledViewEntity.java @@ -0,0 +1,48 @@ +// 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.query.vo; + +import org.apache.cloudstack.acl.ControlledEntity; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * This is the interface for all VO classes representing DB views created for previous ControlledEntity. + * + * @author minc + * + */ +public interface ControlledViewEntity extends ControlledEntity, InternalIdentity, Identity { + + public String getDomainPath(); + + public short getAccountType(); + + public String getAccountUuid(); + + public String getAccountName(); + + public String getDomainUuid(); + + public String getDomainName(); + + public String getProjectUuid(); + + public String getProjectName(); + +} diff --git a/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java b/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java new file mode 100644 index 00000000000..a9c04586a92 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/DomainRouterJoinVO.java @@ -0,0 +1,923 @@ +// 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.query.vo; + +import java.net.URI; +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.Network.GuestType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.network.router.VirtualRouter.RedundantState; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="domain_router_view") +public class DomainRouterJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name", updatable=false, nullable=false, length=255) + private String name = null; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + /** + * Note that state is intentionally missing the setter. Any updates to + * the state machine needs to go through the DAO object because someone + * else could be updating it as well. + */ + @Enumerated(value=EnumType.STRING) + @Column(name="state", updatable=true, nullable=false, length=32) + private State state = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="instance_name", updatable=true, nullable=false) + private String instanceName; + + @Column(name="pod_id", updatable=true, nullable=false) + private Long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName = null; + + @Column(name="dns1") + private String dns1 = null; + + @Column(name="dns2") + private String dns2 = null; + + + @Column(name="host_id", updatable=true, nullable=true) + private long hostId; + + @Column(name="host_uuid") + private String hostUuid; + + @Column(name="host_name", nullable=false) + private String hostName; + + @Column(name="template_id", updatable=true, nullable=true, length=17) + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="service_offering_id") + private long serviceOfferingId; + + @Column(name="service_offering_uuid") + private String serviceOfferingUuid; + + @Column(name="service_offering_name") + private String serviceOfferingName; + + + @Column(name = "vpc_id") + private long vpcId; + + @Column(name = "vpc_uuid") + private String vpcUuid; + + @Column(name = "nic_id") + private long nicId; + + @Column(name = "nic_uuid") + private String nicUuid; + + @Column(name = "is_default_nic") + private boolean isDefaultNic; + + @Column(name = "ip_address") + private String ipAddress; + + @Column(name = "gateway") + private String gateway; + + @Column(name = "netmask") + private String netmask; + + @Column(name = "mac_address") + private String macAddress; + + @Column(name = "broadcast_uri") + private URI broadcastUri; + + @Column(name = "isolation_uri") + private URI isolationUri; + + @Column(name="network_id") + private long networkId; + + @Column(name="network_uuid") + private String networkUuid; + + @Column(name="network_name") + private String networkName; + + @Column(name="network_domain") + private String networkDomain; + + @Column(name="traffic_type") + @Enumerated(value=EnumType.STRING) + private TrafficType trafficType; + + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + + @Column(name="uuid") + private String uuid; + + @Column(name="template_version") + private String templateVersion; + + @Column(name="scripts_version") + private String scriptsVersion; + + @Column(name="redundant_state") + @Enumerated(EnumType.STRING) + private RedundantState redundantState; + + @Column(name="is_redundant_router") + boolean isRedundantRouter; + + @Column(name="guest_type") + @Enumerated(value=EnumType.STRING) + private GuestType guestType; + + + public DomainRouterJoinVO() { + } + + + + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + + + + @Override + public String getUuid() { + return uuid; + } + + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + + + @Override + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + + @Override + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + @Override + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + @Override + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + + @Override + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public String getInstanceName() { + return instanceName; + } + + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public String getPodUuid() { + return podUuid; + } + + + + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + public void setDataCenterUuid(String zoneUuid) { + this.dataCenterUuid = zoneUuid; + } + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String zoneName) { + this.dataCenterName = zoneName; + } + + + public Long getHostId() { + return hostId; + } + + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + + public String getHostUuid() { + return hostUuid; + } + + + + + public void setHostUuid(String hostUuid) { + this.hostUuid = hostUuid; + } + + + + + public String getHostName() { + return hostName; + } + + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + + public long getTemplateId() { + return templateId; + } + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + + + public String getServiceOfferingUuid() { + return serviceOfferingUuid; + } + + + public void setServiceOfferingUuid(String serviceOfferingUuid) { + this.serviceOfferingUuid = serviceOfferingUuid; + } + + + + + public String getServiceOfferingName() { + return serviceOfferingName; + } + + + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } + + public long getVpcId() { + return vpcId; + } + + public void setVpcId(long vpcId) { + this.vpcId = vpcId; + } + + + + + public long getNicId() { + return nicId; + } + + + public void setNicId(long nicId) { + this.nicId = nicId; + } + + + public boolean isDefaultNic() { + return isDefaultNic; + } + + + public void setDefaultNic(boolean isDefaultNic) { + this.isDefaultNic = isDefaultNic; + } + + + public String getIpAddress() { + return ipAddress; + } + + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + + public String getGateway() { + return gateway; + } + + + public void setGateway(String gateway) { + this.gateway = gateway; + } + + + public String getNetmask() { + return netmask; + } + + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + + public String getMacAddress() { + return macAddress; + } + + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + + public URI getBroadcastUri() { + return broadcastUri; + } + + + public void setBroadcastUri(URI broadcastUri) { + this.broadcastUri = broadcastUri; + } + + + public URI getIsolationUri() { + return isolationUri; + } + + + public void setIsolationUri(URI isolationUri) { + this.isolationUri = isolationUri; + } + + + public long getNetworkId() { + return networkId; + } + + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } + + + public String getNetworkName() { + return networkName; + } + + + + + public void setNetworkName(String networkName) { + this.networkName = networkName; + } + + + + + public String getNetworkDomain() { + return networkDomain; + } + + + + + public void setNetworkDomain(String networkDomain) { + this.networkDomain = networkDomain; + } + + + + + public TrafficType getTrafficType() { + return trafficType; + } + + + public void setTrafficType(TrafficType trafficType) { + this.trafficType = trafficType; + } + + + + public long getServiceOfferingId() { + return serviceOfferingId; + } + + + + + public void setServiceOfferingId(long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + + + + public long getProjectId() { + return projectId; + } + + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + + @Override + public String getProjectName() { + return projectName; + } + + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + + + public String getVpcUuid() { + return vpcUuid; + } + + + + + public void setVpcUuid(String vpcUuid) { + this.vpcUuid = vpcUuid; + } + + + + + public String getNicUuid() { + return nicUuid; + } + + + + + public void setNicUuid(String nicUuid) { + this.nicUuid = nicUuid; + } + + + + + public String getNetworkUuid() { + return networkUuid; + } + + + + + public void setNetworkUuid(String networkUuid) { + this.networkUuid = networkUuid; + } + + + public long getJobId() { + return jobId; + } + + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + + public String getJobUuid() { + return jobUuid; + } + + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + + public int getJobStatus() { + return jobStatus; + } + + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + public Long getPodId() { + return podId; + } + + + + + public void setPodId(Long podId) { + this.podId = podId; + } + + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + + public void setDataCenterId(long zoneId) { + this.dataCenterId = zoneId; + } + + + + + public String getDns1() { + return dns1; + } + + + + + public void setDns1(String dns1) { + this.dns1 = dns1; + } + + + + + public String getDns2() { + return dns2; + } + + + + + public void setDns2(String dns2) { + this.dns2 = dns2; + } + + + + + public String getTemplateVersion() { + return templateVersion; + } + + + + + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + + + + + public String getScriptsVersion() { + return scriptsVersion; + } + + + + + public void setScriptsVersion(String scriptsVersion) { + this.scriptsVersion = scriptsVersion; + } + + + + + public RedundantState getRedundantState() { + return redundantState; + } + + + + + public void setRedundantState(RedundantState redundantState) { + this.redundantState = redundantState; + } + + + + + public boolean isRedundantRouter() { + return isRedundantRouter; + } + + + + + public void setRedundantRouter(boolean isRedundantRouter) { + this.isRedundantRouter = isRedundantRouter; + } + + + + + public GuestType getGuestType() { + return guestType; + } + + + + + public void setGuestType(GuestType guestType) { + this.guestType = guestType; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/EventJoinVO.java b/server/src/com/cloud/api/query/vo/EventJoinVO.java new file mode 100644 index 00000000000..f29a942a59f --- /dev/null +++ b/server/src/com/cloud/api/query/vo/EventJoinVO.java @@ -0,0 +1,317 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import com.cloud.event.Event.State; + +@Entity +@Table(name="event_view") +public class EventJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="type") + private String type; + + @Enumerated(value=EnumType.STRING) + @Column(name="state") + private State state; + + @Column(name="description") + private String description; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date createDate; + + @Column(name="user_id") + private long userId; + + @Column(name="user_name") + private String userName; + + @Column(name="level") + private String level; + + @Column(name="start_id") + private long startId; + + @Column(name="start_uuid") + private String startUuid; + + @Column(name="parameters", length=1024) + private String parameters; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public EventJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Date getCreateDate() { + return createDate; + } + + public void setCreateDate(Date createDate) { + this.createDate = createDate; + } + + public long getUserId() { + return userId; + } + + public void setUserId(long userId) { + this.userId = userId; + } + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getLevel() { + return level; + } + + public void setLevel(String level) { + this.level = level; + } + + public long getStartId() { + return startId; + } + + public void setStartId(long startId) { + this.startId = startId; + } + + + public String getStartUuid() { + return startUuid; + } + + public void setStartUuid(String startUuid) { + this.startUuid = startUuid; + } + + public String getParameters() { + return parameters; + } + + public void setParameters(String parameters) { + this.parameters = parameters; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/HostJoinVO.java b/server/src/com/cloud/api/query/vo/HostJoinVO.java new file mode 100644 index 00000000000..a3796b97eba --- /dev/null +++ b/server/src/com/cloud/api/query/vo/HostJoinVO.java @@ -0,0 +1,509 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; + +import com.cloud.host.Status; +import com.cloud.host.Host.Type; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.org.Cluster; +import com.cloud.resource.ResourceState; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +/** + * Host DB view. + * @author minc + * + */ +@Entity +@Table(name="host_view") +public class HostJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + + @Column(name="status") + private Status status = null; + + @Column(name="type") + @Enumerated(value=EnumType.STRING) + private Type type; + + @Column(name="private_ip_address") + private String privateIpAddress; + + @Column(name="disconnected") + @Temporal(value=TemporalType.TIMESTAMP) + private Date disconnectedOn; + + @Column(name="version") + private String version; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + @Column(name="hypervisor_version") + private String hypervisorVersion; + + @Column(name="capabilities") + private String caps; + + @Column(name="last_ping") + private long lastPinged; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="resource_state") + @Enumerated(value=EnumType.STRING) + private ResourceState resourceState; + + @Column(name="mgmt_server_id") + private Long managementServerId; + + @Column(name="cpus") + private Integer cpus; + + @Column(name="speed") + private Long speed; + + @Column(name="ram") + private long totalMemory; + + @Column(name="cluster_id") + private long clusterId; + + @Column(name="cluster_uuid") + private String clusterUuid; + + @Column(name="cluster_name") + private String clusterName; + + @Column(name="cluster_type") + @Enumerated(value=EnumType.STRING) + Cluster.ClusterType clusterType; + + @Column(name="data_center_id") + private long zoneId; + + @Column(name="data_center_uuid") + private String zoneUuid; + + @Column(name="data_center_name") + private String zoneName; + + @Column(name="pod_id") + private long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="pod_name") + private String podName; + + + @Column(name="guest_os_category_id") + private long osCategoryId; + + @Column(name="guest_os_category_uuid") + private String osCategoryUuid; + + @Column(name="guest_os_category_name") + private String osCategoryName; + + @Column(name="tag") + private String tag; + + @Column(name="memory_used_capacity") + private long memUsedCapacity; + + @Column(name="memory_reserved_capacity") + private long memReservedCapacity; + + @Column(name="cpu_used_capacity") + private long cpuUsedCapacity; + + @Column(name="cpu_reserved_capacity") + private long cpuReservedCapacity; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + + /* (non-Javadoc) + * @see com.cloud.api.query.vo.BaseViewVO#getId() + */ + @Override + public long getId() { + return this.id; + } + + /* (non-Javadoc) + * @see com.cloud.api.query.vo.BaseViewVO#setId(long) + */ + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public long getZoneId() { + return zoneId; + } + + public void setZoneId(long zoneId) { + this.zoneId = zoneId; + } + + public String getZoneUuid() { + return zoneUuid; + } + + public void setZoneUuid(String zoneUuid) { + this.zoneUuid = zoneUuid; + } + + public String getZoneName() { + return zoneName; + } + + public void setZoneName(String zoneName) { + this.zoneName = zoneName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Status getStatus() { + return status; + } + + public void setStatus(Status status) { + this.status = status; + } + + public Type getType() { + return type; + } + + public void setType(Type type) { + this.type = type; + } + + public String getPrivateIpAddress() { + return privateIpAddress; + } + + public void setPrivateIpAddress(String privateIpAddress) { + this.privateIpAddress = privateIpAddress; + } + + public Date getDisconnectedOn() { + return disconnectedOn; + } + + public void setDisconnectedOn(Date disconnectedOn) { + this.disconnectedOn = disconnectedOn; + } + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + public String getHypervisorVersion() { + return hypervisorVersion; + } + + public void setHypervisorVersion(String hypervisorVersion) { + this.hypervisorVersion = hypervisorVersion; + } + + public String getCapabilities() { + return caps; + } + + public void setCapabilities(String caps) { + this.caps = caps; + } + + public long getLastPinged() { + return lastPinged; + } + + public void setLastPinged(long lastPinged) { + this.lastPinged = lastPinged; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public ResourceState getResourceState() { + return resourceState; + } + + public void setResourceState(ResourceState resourceState) { + this.resourceState = resourceState; + } + + public Long getManagementServerId() { + return managementServerId; + } + + public void setManagementServerId(Long managementServerId) { + this.managementServerId = managementServerId; + } + + public Integer getCpus() { + return cpus; + } + + public void setCpus(Integer cpus) { + this.cpus = cpus; + } + + public Long getSpeed() { + return speed; + } + + public void setSpeed(Long speed) { + this.speed = speed; + } + + public long getTotalMemory() { + return totalMemory; + } + + public void setTotalMemory(long totalMemory) { + this.totalMemory = totalMemory; + } + + public long getClusterId() { + return clusterId; + } + + public void setClusterId(long clusterId) { + this.clusterId = clusterId; + } + + public String getClusterUuid() { + return clusterUuid; + } + + public void setClusterUuid(String clusterUuid) { + this.clusterUuid = clusterUuid; + } + + public String getClusterName() { + return clusterName; + } + + public void setClusterName(String clusterName) { + this.clusterName = clusterName; + } + + public Cluster.ClusterType getClusterType() { + return clusterType; + } + + public void setClusterType(Cluster.ClusterType clusterType) { + this.clusterType = clusterType; + } + + public long getOsCategoryId() { + return osCategoryId; + } + + public void setOsCategoryId(long osCategoryId) { + this.osCategoryId = osCategoryId; + } + + public String getOsCategoryUuid() { + return osCategoryUuid; + } + + public void setOsCategoryUuid(String osCategoryUuid) { + this.osCategoryUuid = osCategoryUuid; + } + + public String getOsCategoryName() { + return osCategoryName; + } + + public void setOsCategoryName(String osCategoryName) { + this.osCategoryName = osCategoryName; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + public long getPodId() { + return podId; + } + + public void setPodId(long podId) { + this.podId = podId; + } + + public String getPodUuid() { + return podUuid; + } + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + public String getPodName() { + return podName; + } + + public void setPodName(String podName) { + this.podName = podName; + } + + public long getMemUsedCapacity() { + return memUsedCapacity; + } + + public void setMemUsedCapacity(long memUsedCapacity) { + this.memUsedCapacity = memUsedCapacity; + } + + public long getMemReservedCapacity() { + return memReservedCapacity; + } + + public void setMemReservedCapacity(long memReservedCapacity) { + this.memReservedCapacity = memReservedCapacity; + } + + public long getCpuUsedCapacity() { + return cpuUsedCapacity; + } + + public void setCpuUsedCapacity(long cpuUsedCapacity) { + this.cpuUsedCapacity = cpuUsedCapacity; + } + + public long getCpuReservedCapacity() { + return cpuReservedCapacity; + } + + public void setCpuReservedCapacity(long cpuReservedCapacity) { + this.cpuReservedCapacity = cpuReservedCapacity; + } + + public String getTag() { + return tag; + } + + public void setTag(String tag) { + this.tag = tag; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java b/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java new file mode 100644 index 00000000000..3fb43094ad3 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/InstanceGroupJoinVO.java @@ -0,0 +1,233 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; + +@Entity +@Table(name="instance_group_view") +public class InstanceGroupJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + String name; + + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public InstanceGroupJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java new file mode 100644 index 00000000000..1a8818a22e4 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectAccountJoinVO.java @@ -0,0 +1,216 @@ +// 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.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.projects.ProjectAccount.Role; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="project_account_view") +public class ProjectAccountJoinVO extends BaseViewVO implements InternalIdentity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName; + + @Column(name="account_type") + private short accountType; + + @Column(name="account_role") + @Enumerated(value=EnumType.STRING) + private Role accountRole; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + public ProjectAccountJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + + public String getAccountUuid() { + return accountUuid; + } + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + public String getAccountName() { + return accountName; + } + + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + + public short getAccountType() { + return accountType; + } + + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + + public Role getAccountRole() { + return accountRole; + } + + + + public void setAccountRole(Role accountRole) { + this.accountRole = accountRole; + } + + + + public long getProjectId() { + return projectId; + } + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + public String getProjectUuid() { + return projectUuid; + } + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + public String getProjectName() { + return projectName; + } + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java new file mode 100644 index 00000000000..a60c9370530 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectInvitationJoinVO.java @@ -0,0 +1,235 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="project_invitation_view") +public class ProjectInvitationJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name = "email") + private String email; + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private State state; + + @Column(name = GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + public ProjectInvitationJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/ProjectJoinVO.java b/server/src/com/cloud/api/query/vo/ProjectJoinVO.java new file mode 100644 index 00000000000..73ec9313289 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ProjectJoinVO.java @@ -0,0 +1,304 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine.State; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="project_view") +public class ProjectJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="name") + private String name; + + @Column(name="display_text") + String displayText; + + + @Column(name="owner") + String owner; + + @Column(name="state") + @Enumerated(value=EnumType.STRING) + private State state; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="account_id") + private long accountId; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName; + + @Column(name="domain_path") + private String domainPath; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + public ProjectJoinVO() { + } + + @Override + public long getId() { + return id; + } + + + @Override + public void setId(long id) { + this.id = id; + + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public State getState() { + return state; + } + + public void setState(State state) { + this.state = state; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public String getDisplayText() { + return displayText; + } + + public void setDisplayText(String displayText) { + this.displayText = displayText; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public long getTagId() { + return tagId; + } + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + public String getTagUuid() { + return tagUuid; + } + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + public String getTagKey() { + return tagKey; + } + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public long getTagDomainId() { + return tagDomainId; + } + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + public long getTagAccountId() { + return tagAccountId; + } + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + public long getTagResourceId() { + return tagResourceId; + } + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + public String getTagCustomer() { + return tagCustomer; + } + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + +} diff --git a/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java b/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java new file mode 100644 index 00000000000..9ce9555d1be --- /dev/null +++ b/server/src/com/cloud/api/query/vo/ResourceTagJoinVO.java @@ -0,0 +1,268 @@ +// 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.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.server.ResourceTag.TaggedResourceType; + +@Entity +@Table(name="resource_tag_view") +public class ResourceTagJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="key") + private String key; + + @Column(name="value") + String value; + + + @Column(name="resource_id") + long resourceId; + + @Column(name="resource_uuid") + private String resourceUuid; + + @Column(name="resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType resourceType; + + @Column(name="customer") + String customer; + + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + + + public ResourceTagJoinVO() { + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + public long getResourceId() { + return resourceId; + } + + public void setResourceId(long resourceId) { + this.resourceId = resourceId; + } + + public String getResourceUuid() { + return resourceUuid; + } + + public void setResourceUuid(String resourceUuid) { + this.resourceUuid = resourceUuid; + } + + public TaggedResourceType getResourceType() { + return resourceType; + } + + public void setResourceType(TaggedResourceType resourceType) { + this.resourceType = resourceType; + } + + public String getCustomer() { + return customer; + } + + public void setCustomer(String customer) { + this.customer = customer; + } + + +} diff --git a/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java b/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java new file mode 100644 index 00000000000..922e130ed30 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/SecurityGroupJoinVO.java @@ -0,0 +1,452 @@ +// 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.query.vo; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.network.security.SecurityRule.SecurityRuleType; +import com.cloud.server.ResourceTag.TaggedResourceType; + +@Entity +@Table(name="security_group_view") +public class SecurityGroupJoinVO extends BaseViewVO implements ControlledViewEntity{ + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name") + private String name; + + @Column(name = "description") + private String description; + + @Column(name = "uuid") + private String uuid; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name = "rule_id") + private Long ruleId; + + @Column(name = "rule_uuid") + private String ruleUuid; + + @Column(name = "rule_start_port") + private int ruleStartPort; + + @Column(name = "rule_end_port") + private int ruleEndPort; + + @Column(name = "rule_protocol") + private String ruleProtocol; + + @Column(name = "rule_type") + private String ruleType; + + @Column(name = "rule_allowed_network_id") + private Long ruleAllowedNetworkId = null; + + @Column(name = "rule_allowed_ip_cidr") + private String ruleAllowedSourceIpCidr = null; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + public SecurityGroupJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + @Override + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + @Override + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + @Override + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + @Override + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + @Override + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + @Override + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + @Override + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public long getProjectId() { + return projectId; + } + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + @Override + public String getProjectUuid() { + return projectUuid; + } + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + @Override + public String getProjectName() { + return projectName; + } + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public Long getRuleId() { + return ruleId; + } + + public void setRuleId(Long ruleId) { + this.ruleId = ruleId; + } + + public String getRuleUuid() { + return ruleUuid; + } + + public void setRuleUuid(String ruleUuid) { + this.ruleUuid = ruleUuid; + } + + public int getRuleStartPort() { + return ruleStartPort; + } + + public void setRuleStartPort(int ruleStartPort) { + this.ruleStartPort = ruleStartPort; + } + + public int getRuleEndPort() { + return ruleEndPort; + } + + public void setRuleEndPort(int ruleEndPort) { + this.ruleEndPort = ruleEndPort; + } + + public String getRuleProtocol() { + return ruleProtocol; + } + + public void setRuleProtocol(String ruleProtocol) { + this.ruleProtocol = ruleProtocol; + } + + public SecurityRuleType getRuleType() { + if ("ingress".equalsIgnoreCase(ruleType)) { + return SecurityRuleType.IngressRule; + } else { + return SecurityRuleType.EgressRule; + } + } + + public void setRuleType(String ruleType) { + this.ruleType = ruleType; + } + + public Long getRuleAllowedNetworkId() { + return ruleAllowedNetworkId; + } + + public void setRuleAllowedNetworkId(Long ruleAllowedNetworkId) { + this.ruleAllowedNetworkId = ruleAllowedNetworkId; + } + + public String getRuleAllowedSourceIpCidr() { + return ruleAllowedSourceIpCidr; + } + + public void setRuleAllowedSourceIpCidr(String ruleAllowedSourceIpCidr) { + this.ruleAllowedSourceIpCidr = ruleAllowedSourceIpCidr; + } + + public long getTagId() { + return tagId; + } + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + public String getTagUuid() { + return tagUuid; + } + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + public String getTagKey() { + return tagKey; + } + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + public String getTagValue() { + return tagValue; + } + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + public long getTagDomainId() { + return tagDomainId; + } + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + public long getTagAccountId() { + return tagAccountId; + } + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + public long getTagResourceId() { + return tagResourceId; + } + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + public String getTagCustomer() { + return tagCustomer; + } + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + +} diff --git a/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java b/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java new file mode 100644 index 00000000000..44637db3400 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/UserAccountJoinVO.java @@ -0,0 +1,350 @@ +// 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.query.vo; + +import java.util.Date; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.cloud.utils.db.Encrypt; +import com.cloud.utils.db.GenericDao; + +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name="user_view") +public class UserAccountJoinVO extends BaseViewVO implements InternalIdentity, Identity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="uuid") + private String uuid; + + @Column(name="username") + private String username = null; + + @Column(name="password") + private String password = null; + + @Column(name="firstname") + private String firstname = null; + + @Column(name="lastname") + private String lastname = null; + + @Column(name="email") + private String email = null; + + @Column(name="state") + private String state; + + @Column(name="api_key") + private String apiKey = null; + + @Encrypt + @Column(name="secret_key") + private String secretKey = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="timezone") + private String timezone; + + @Column(name="registration_token") + private String registrationToken = null; + + @Column(name="is_registered") + boolean registered; + + @Column (name="incorrect_login_attempts") + int loginAttempts; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + public UserAccountJoinVO() { + } + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + @Override + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public long getAccountId() { + return accountId; + } + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + public String getAccountUuid() { + return accountUuid; + } + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + public short getAccountType() { + return accountType; + } + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + public long getDomainId() { + return domainId; + } + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + public String getDomainUuid() { + return domainUuid; + } + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + public String getDomainName() { + return domainName; + } + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + public String getDomainPath() { + return domainPath; + } + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getSecretKey() { + return secretKey; + } + + public void setSecretKey(String secretKey) { + this.secretKey = secretKey; + } + + public Date getCreated() { + return created; + } + + public void setCreated(Date created) { + this.created = created; + } + + public Date getRemoved() { + return removed; + } + + public void setRemoved(Date removed) { + this.removed = removed; + } + + public String getTimezone() { + return timezone; + } + + public void setTimezone(String timezone) { + this.timezone = timezone; + } + + public String getRegistrationToken() { + return registrationToken; + } + + public void setRegistrationToken(String registrationToken) { + this.registrationToken = registrationToken; + } + + public boolean isRegistered() { + return registered; + } + + public void setRegistered(boolean registered) { + this.registered = registered; + } + + public int getLoginAttempts() { + return loginAttempts; + } + + public void setLoginAttempts(int loginAttempts) { + this.loginAttempts = loginAttempts; + } + + public long getJobId() { + return jobId; + } + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + public String getJobUuid() { + return jobUuid; + } + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + public int getJobStatus() { + return jobStatus; + } + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + +} diff --git a/server/src/com/cloud/api/query/vo/UserVmJoinVO.java b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java new file mode 100644 index 00000000000..025db47d599 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/UserVmJoinVO.java @@ -0,0 +1,1614 @@ +// 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.query.vo; + +import java.net.URI; +import java.util.Date; +import java.util.Map; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Transient; + +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.network.Network.GuestType; +import com.cloud.network.Networks.TrafficType; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.storage.Volume; +import com.cloud.storage.Storage.StoragePoolType; +import com.cloud.utils.db.Encrypt; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.VirtualMachine.State; + +@Entity +@Table(name="user_vm_view") +public class UserVmJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id", updatable=false, nullable = false) + private long id; + + @Column(name="name", updatable=false, nullable=false, length=255) + private String name = null; + + @Column(name="display_name", updatable=false, nullable=false, length=255) + private String displayName = null; + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="instance_group_id") + private long instanceGroupId; + + @Column(name="instance_group_uuid") + private String instanceGroupUuid; + + @Column(name="instance_group_name") + private String instanceGroupName; + + @Column(name="vm_type", updatable=false, nullable=false, length=32) + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.Type type; + + /** + * Note that state is intentionally missing the setter. Any updates to + * the state machine needs to go through the DAO object because someone + * else could be updating it as well. + */ + @Enumerated(value=EnumType.STRING) + @Column(name="state", updatable=true, nullable=false, length=32) + private State state = null; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + @Column(name="instance_name", updatable=true, nullable=false) + private String instanceName; + + @Column(name="guest_os_id", nullable=false, length=17) + private long guestOsId; + + @Column(name="guest_os_uuid") + private String guestOsUuid; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + @Column(name="ha_enabled", updatable=true, nullable=true) + private boolean haEnabled; + + @Encrypt + @Column(name="vnc_password", updatable=true, nullable=false, length=255) + protected String vncPassword; + + @Column(name="limit_cpu_use", updatable=true, nullable=true) + private boolean limitCpuUse; + + @Column(name="last_host_id", updatable=true, nullable=true) + private Long lastHostId; + + @Column(name="private_ip_address", updatable=true) + private String privateIpAddress; + + + @Column(name="private_mac_address", updatable=true, nullable=true) + private String privateMacAddress; + + @Column(name="pod_id", updatable=true, nullable=false) + private Long podId; + + @Column(name="pod_uuid") + private String podUuid; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName = null; + + @Column(name="security_group_enabled") + private boolean securityGroupEnabled; + + @Column(name="host_id", updatable=true, nullable=true) + private long hostId; + + @Column(name="host_uuid") + private String hostUuid; + + @Column(name="host_name", nullable=false) + private String hostName; + + @Column(name="template_id", updatable=true, nullable=true, length=17) + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="template_name") + private String templateName; + + @Column(name="template_display_text", length=4096) + private String templateDisplayText; + + @Column(name="password_enabled") + private boolean passwordEnabled; + + @Column(name="iso_id", updatable=true, nullable=true, length=17) + private long isoId; + + @Column(name="iso_uuid") + private String isoUuid; + + @Column(name="iso_name") + private String isoName; + + @Column(name="iso_display_text", length=4096) + private String isoDisplayText; + + @Column(name="service_offering_id") + private long serviceOfferingId; + + @Column(name="service_offering_uuid") + private String serviceOfferingUuid; + + @Column(name="service_offering_name") + private String serviceOfferingName; + + @Column(name="cpu") + private int cpu; + + @Column(name="speed") + private int speed; + + @Column(name="ram_size") + private int ramSize; + + @Column(name="pool_id", updatable=false, nullable = false) + private long poolId; + + @Column(name="pool_uuid") + private String poolUuid; + + @Column(name="pool_type", updatable=false, nullable=false, length=32) + @Enumerated(value=EnumType.STRING) + private StoragePoolType poolType; + + @Column(name = "volume_id") + private long volume_id; + + @Column(name = "volume_uuid") + private String volume_uuid; + + @Column(name = "volume_device_id") + private Long volumeDeviceId = null; + + @Column(name = "volume_type") + @Enumerated(EnumType.STRING) + private Volume.Type volumeType; + + @Column(name = "security_group_id") + private long securityGroupId; + + @Column(name = "security_group_uuid") + private String securityGroupUuid; + + @Column(name = "security_group_name") + private String securityGroupName; + + @Column(name = "security_group_description") + private String securityGroupDescription; + + @Column(name = "vpc_id") + private long vpcId; + + @Column(name = "vpc_uuid") + private String vpcUuid; + + @Column(name = "nic_id") + private long nicId; + + @Column(name = "nic_uuid") + private String nicUuid; + + @Column(name = "is_default_nic") + private boolean isDefaultNic; + + @Column(name = "ip_address") + private String ipAddress; + + @Column(name = "gateway") + private String gateway; + + @Column(name = "netmask") + private String netmask; + + @Column(name = "mac_address") + private String macAddress; + + @Column(name = "broadcast_uri") + private URI broadcastUri; + + @Column(name = "isolation_uri") + private URI isolationUri; + + @Column(name="network_id") + private long networkId; + + @Column(name="network_uuid") + private String networkUuid; + + @Column(name="traffic_type") + @Enumerated(value=EnumType.STRING) + private TrafficType trafficType; + + @Column(name="guest_type") + @Enumerated(value=EnumType.STRING) + private GuestType guestType; + + @Column(name = "public_ip_id") + private long publicIpId; + + @Column(name = "public_ip_uuid") + private String publicIpUuid; + + @Column(name = "public_ip_address") + private String publicIpAddress; + + @Column(name="user_data", updatable=true, nullable=true, length=2048) + private String userData; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="keypair_name") + private String keypairName; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + transient String password; + + @Transient + Map details; + + @Column(name="uuid") + private String uuid; + + public UserVmJoinVO() { + } + + + @Override + public long getId() { + return id; + } + + @Override + public void setId(long id) { + this.id = id; + } + + + @Override + public String getUuid() { + return uuid; + } + + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public String getDisplayName() { + return displayName; + } + + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + + @Override + public long getAccountId() { + return accountId; + } + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + + @Override + public String getAccountName() { + return accountName; + } + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + @Override + public short getAccountType() { + return accountType; + } + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + @Override + public long getDomainId() { + return domainId; + } + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + + @Override + public String getDomainName() { + return domainName; + } + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + @Override + public String getDomainPath() { + return domainPath; + } + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + + + public long getInstanceGroupId() { + return instanceGroupId; + } + + + public void setInstanceGroupId(long instanceGroupId) { + this.instanceGroupId = instanceGroupId; + } + + + public String getInstanceGroupUuid() { + return instanceGroupUuid; + } + + + + + public void setInstanceGroupUuid(String instanceGroupUuid) { + this.instanceGroupUuid = instanceGroupUuid; + } + + + + + public String getInstanceGroupName() { + return instanceGroupName; + } + + + public void setInstanceGroupName(String instanceGroupName) { + this.instanceGroupName = instanceGroupName; + } + + + public VirtualMachine.Type getType() { + return type; + } + + + + + public void setType(VirtualMachine.Type type) { + this.type = type; + } + + + + + public State getState() { + return state; + } + + + public void setState(State state) { + this.state = state; + } + + + public Date getCreated() { + return created; + } + + + public void setCreated(Date created) { + this.created = created; + } + + + public Date getRemoved() { + return removed; + } + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + public String getInstanceName() { + return instanceName; + } + + + public void setInstanceName(String instanceName) { + this.instanceName = instanceName; + } + + + public long getGuestOSId() { + return guestOsId; + } + + + public void setGuestOSId(long guestOSId) { + this.guestOsId = guestOSId; + } + + + public String getGuestOsUuid() { + return guestOsUuid; + } + + + + + public void setGuestOsUuid(String guestOsUuid) { + this.guestOsUuid = guestOsUuid; + } + + + + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + + public boolean isHaEnabled() { + return haEnabled; + } + + + public void setHaEnabled(boolean haEnabled) { + this.haEnabled = haEnabled; + } + + public void setVncPassword(String vncPassword) { + this.vncPassword = vncPassword; + } + + public String getVncPassword() { + return vncPassword; + } + + + + + public String getPrivateIpAddress() { + return privateIpAddress; + } + + + + + public void setPrivateIpAddress(String privateIpAddress) { + this.privateIpAddress = privateIpAddress; + } + + + + + public String getPrivateMacAddress() { + return privateMacAddress; + } + + + + + public void setPrivateMacAddress(String privateMacAddress) { + this.privateMacAddress = privateMacAddress; + } + + + + + public Long getLastHostId() { + return lastHostId; + } + + + + + public void setLastHostId(Long lastHostId) { + this.lastHostId = lastHostId; + } + + + + + + + public Long getPodId() { + return podId; + } + + + + + public void setPodId(Long podIdToDeployIn) { + this.podId = podIdToDeployIn; + } + + + + + public String getPodUuid() { + return podUuid; + } + + + + + public void setPodUuid(String podUuid) { + this.podUuid = podUuid; + } + + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + + public void setDataCenterId(long dataCenterIdToDeployIn) { + this.dataCenterId = dataCenterIdToDeployIn; + } + + + public boolean limitCpuUse() { + return limitCpuUse; + } + + public void setLimitCpuUse(boolean value) { + limitCpuUse = value; + } + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + + + public void setDataCenterUuid(String zoneUuid) { + this.dataCenterUuid = zoneUuid; + } + + + + + public String getDataCenterName() { + return dataCenterName; + } + + + public void setDataCenterName(String zoneName) { + this.dataCenterName = zoneName; + } + + + public boolean isSecurityGroupEnabled() { + return securityGroupEnabled; + } + + + public void setSecurityGroupEnabled(boolean securityGroupEnabled) { + this.securityGroupEnabled = securityGroupEnabled; + } + + + public Long getHostId() { + return hostId; + } + + + public void setHostId(long hostId) { + this.hostId = hostId; + } + + + public String getHostUuid() { + return hostUuid; + } + + + + + public void setHostUuid(String hostUuid) { + this.hostUuid = hostUuid; + } + + + + + public String getHostName() { + return hostName; + } + + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + + public long getTemplateId() { + return templateId; + } + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + + public String getTemplateName() { + return templateName; + } + + + public void setTemplateName(String templateName) { + this.templateName = templateName; + } + + + public String getTemplateDisplayText() { + return templateDisplayText; + } + + + public void setTemplateDisplayText(String templateDisplayText) { + this.templateDisplayText = templateDisplayText; + } + + + public boolean isPasswordEnabled() { + return passwordEnabled; + } + + + public void setPasswordEnabled(boolean passwordEnabled) { + this.passwordEnabled = passwordEnabled; + } + + + public Long getIsoId() { + return isoId; + } + + + public void setIsoId(long isoId) { + this.isoId = isoId; + } + + + public String getIsoUuid() { + return isoUuid; + } + + + + + public void setIsoUuid(String isoUuid) { + this.isoUuid = isoUuid; + } + + + + + public String getIsoName() { + return isoName; + } + + + public void setIsoName(String isoName) { + this.isoName = isoName; + } + + + public String getIsoDisplayText() { + return isoDisplayText; + } + + public void setIsoDisplayText(String isoDisplayText) { + this.isoDisplayText = isoDisplayText; + } + + + + + public String getServiceOfferingUuid() { + return serviceOfferingUuid; + } + + + + + public void setServiceOfferingUuid(String serviceOfferingUuid) { + this.serviceOfferingUuid = serviceOfferingUuid; + } + + + + + public String getServiceOfferingName() { + return serviceOfferingName; + } + + + public void setServiceOfferingName(String serviceOfferingName) { + this.serviceOfferingName = serviceOfferingName; + } + + + public int getCpu() { + return cpu; + } + + + public void setCpu(int cpu) { + this.cpu = cpu; + } + + + public int getSpeed() { + return speed; + } + + + public void setSpeed(int speed) { + this.speed = speed; + } + + + public int getRamSize() { + return ramSize; + } + + + public void setRamSize(int ramSize) { + this.ramSize = ramSize; + } + + + public long getPoolId() { + return poolId; + } + + + public void setPoolId(long poolId) { + this.poolId = poolId; + } + + + public StoragePoolType getPoolType() { + return poolType; + } + + + public void setPoolType(StoragePoolType poolType) { + this.poolType = poolType; + } + + + public long getVolume_id() { + return volume_id; + } + + + public void setVolume_id(long volume_id) { + this.volume_id = volume_id; + } + + + public Long getVolumeDeviceId() { + return volumeDeviceId; + } + + + public void setVolumeDeviceId(Long volumeDeviceId) { + this.volumeDeviceId = volumeDeviceId; + } + + + public Volume.Type getVolumeType() { + return volumeType; + } + + + public void setVolumeType(Volume.Type volumeType) { + this.volumeType = volumeType; + } + + + public long getSecurityGroupId() { + return securityGroupId; + } + + + public void setSecurityGroupId(long securityGroupId) { + this.securityGroupId = securityGroupId; + } + + + public String getSecurityGroupName() { + return securityGroupName; + } + + + public void setSecurityGroupName(String securityGroupName) { + this.securityGroupName = securityGroupName; + } + + + public String getSecurityGroupDescription() { + return securityGroupDescription; + } + + + public void setSecurityGroupDescription(String securityGroupDescription) { + this.securityGroupDescription = securityGroupDescription; + } + + + public long getVpcId() { + return vpcId; + } + + + + public void setVpcId(long vpcId) { + this.vpcId = vpcId; + } + + + + + public long getNicId() { + return nicId; + } + + + public void setNicId(long nicId) { + this.nicId = nicId; + } + + + public boolean isDefaultNic() { + return isDefaultNic; + } + + + public void setDefaultNic(boolean isDefaultNic) { + this.isDefaultNic = isDefaultNic; + } + + + public String getIpAddress() { + return ipAddress; + } + + + public void setIpAddress(String ipAddress) { + this.ipAddress = ipAddress; + } + + + public String getGateway() { + return gateway; + } + + + public void setGateway(String gateway) { + this.gateway = gateway; + } + + + public String getNetmask() { + return netmask; + } + + + public void setNetmask(String netmask) { + this.netmask = netmask; + } + + + public String getMacAddress() { + return macAddress; + } + + + public void setMacAddress(String macAddress) { + this.macAddress = macAddress; + } + + + public URI getBroadcastUri() { + return broadcastUri; + } + + + public void setBroadcastUri(URI broadcastUri) { + this.broadcastUri = broadcastUri; + } + + + public URI getIsolationUri() { + return isolationUri; + } + + + public void setIsolationUri(URI isolationUri) { + this.isolationUri = isolationUri; + } + + + public long getNetworkId() { + return networkId; + } + + + public void setNetworkId(long networkId) { + this.networkId = networkId; + } + + + public TrafficType getTrafficType() { + return trafficType; + } + + + public void setTrafficType(TrafficType trafficType) { + this.trafficType = trafficType; + } + + + public GuestType getGuestType() { + return guestType; + } + + + public void setGuestType(GuestType guestType) { + this.guestType = guestType; + } + + + public long getPublicIpId() { + return publicIpId; + } + + + + + public void setPublicIpId(long publicIpId) { + this.publicIpId = publicIpId; + } + + + + + public String getPublicIpAddress() { + return publicIpAddress; + } + + + public void setPublicIpAddress(String publicIpAddress) { + this.publicIpAddress = publicIpAddress; + } + + + + public long getServiceOfferingId() { + return serviceOfferingId; + } + + + + + public void setServiceOfferingId(long serviceOfferingId) { + this.serviceOfferingId = serviceOfferingId; + } + + + public Map getDetails() { + return details; + } + + public String getDetail(String name) { + assert (details != null) : "Did you forget to load the details?"; + + return details != null ? details.get(name) : null; + } + + public void setDetail(String name, String value) { + assert (details != null) : "Did you forget to load the details?"; + + details.put(name, value); + } + + public void setDetails(Map details) { + this.details = details; + } + + public void setUserData(String userData) { + this.userData = userData; + } + + public String getUserData() { + return userData; + } + + + + public long getGuestOsId() { + return guestOsId; + } + + + + + public void setGuestOsId(long guestOsId) { + this.guestOsId = guestOsId; + } + + + + + public long getProjectId() { + return projectId; + } + + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + + @Override + public String getProjectName() { + return projectName; + } + + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + + public String getKeypairName() { + return keypairName; + } + + + + + public void setKeypairName(String keypairName) { + this.keypairName = keypairName; + } + + + + + public long getTagId() { + return tagId; + } + + + + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + + + + public String getTagUuid() { + return tagUuid; + } + + + + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + + + + public String getTagKey() { + return tagKey; + } + + + + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + + + + public String getTagValue() { + return tagValue; + } + + + + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + + + + public long getTagDomainId() { + return tagDomainId; + } + + + + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + + + + public long getTagAccountId() { + return tagAccountId; + } + + + + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + + + + public long getTagResourceId() { + return tagResourceId; + } + + + + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + + + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + + + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + + + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + + + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + + + + public String getTagCustomer() { + return tagCustomer; + } + + + + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + + + + public boolean isLimitCpuUse() { + return limitCpuUse; + } + + + + public String getPoolUuid() { + return poolUuid; + } + + + + + public void setPoolUuid(String poolUuid) { + this.poolUuid = poolUuid; + } + + + + + public String getVolume_uuid() { + return volume_uuid; + } + + + + + public void setVolume_uuid(String volume_uuid) { + this.volume_uuid = volume_uuid; + } + + + + + public String getSecurityGroupUuid() { + return securityGroupUuid; + } + + + + + public void setSecurityGroupUuid(String securityGroupUuid) { + this.securityGroupUuid = securityGroupUuid; + } + + + + + public String getVpcUuid() { + return vpcUuid; + } + + + + + public void setVpcUuid(String vpcUuid) { + this.vpcUuid = vpcUuid; + } + + + + + public String getNicUuid() { + return nicUuid; + } + + + + + public void setNicUuid(String nicUuid) { + this.nicUuid = nicUuid; + } + + + + + public String getNetworkUuid() { + return networkUuid; + } + + + + + public void setNetworkUuid(String networkUuid) { + this.networkUuid = networkUuid; + } + + + + + public String getPublicIpUuid() { + return publicIpUuid; + } + + + + + public void setPublicIpUuid(String publicIpUuid) { + this.publicIpUuid = publicIpUuid; + } + + + + public long getJobId() { + return jobId; + } + + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + + public String getJobUuid() { + return jobUuid; + } + + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + + public int getJobStatus() { + return jobStatus; + } + + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + transient String toString; + @Override + public String toString() { + if (toString == null) { + toString = new StringBuilder("VM[").append(id).append("|").append(hostName).append("]").toString(); + } + return toString; + } + +} diff --git a/server/src/com/cloud/api/query/vo/VolumeJoinVO.java b/server/src/com/cloud/api/query/vo/VolumeJoinVO.java new file mode 100644 index 00000000000..4f6b35bab82 --- /dev/null +++ b/server/src/com/cloud/api/query/vo/VolumeJoinVO.java @@ -0,0 +1,1034 @@ +// 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.query.vo; + +import java.util.Date; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.Temporal; +import javax.persistence.TemporalType; +import com.cloud.hypervisor.Hypervisor.HypervisorType; +import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.storage.Storage; +import com.cloud.storage.Volume; +import com.cloud.storage.VMTemplateStorageResourceAssoc.Status; +import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine; + +@Entity +@Table(name="volume_view") +public class VolumeJoinVO extends BaseViewVO implements ControlledViewEntity { + + @Id + @Column(name="id") + private long id; + + @Column(name="uuid") + private String uuid; + + + @Column(name="name") + private String name; + + @Column(name = "device_id") + Long deviceId = null; + + @Column(name = "volume_type") + @Enumerated(EnumType.STRING) + Volume.Type volumeType; + + @Column(name = "size") + long size; + + @Column(name = "state") + @Enumerated(value = EnumType.STRING) + private Volume.State state; + + @Column(name=GenericDao.CREATED_COLUMN) + private Date created; + + @Column(name = "attached") + @Temporal(value = TemporalType.TIMESTAMP) + Date attached; + + @Column(name=GenericDao.REMOVED_COLUMN) + private Date removed; + + + @Column(name="account_id") + private long accountId; + + @Column(name="account_uuid") + private String accountUuid; + + @Column(name="account_name") + private String accountName = null; + + @Column(name="account_type") + private short accountType; + + @Column(name="domain_id") + private long domainId; + + @Column(name="domain_uuid") + private String domainUuid; + + @Column(name="domain_name") + private String domainName = null; + + @Column(name="domain_path") + private String domainPath = null; + + @Column(name="project_id") + private long projectId; + + @Column(name="project_uuid") + private String projectUuid; + + @Column(name="project_name") + private String projectName; + + @Column(name="pod_id") + private long podId; + + @Column(name="data_center_id") + private long dataCenterId; + + @Column(name="data_center_uuid") + private String dataCenterUuid; + + @Column(name="data_center_name") + private String dataCenterName; + + @Column(name="vm_id") + private long vmId; + + @Column(name="vm_uuid") + private String vmUuid; + + @Column(name="vm_name") + private String vmName; + + @Column(name="vm_display_name") + private String vmDisplayName; + + @Column(name="vm_state") + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.State vmState = null; + + @Column(name="vm_type") + @Enumerated(value=EnumType.STRING) + protected VirtualMachine.Type vmType; + + @Column (name="volume_host_size") + private long volumeHostSize; + + @Column(name="volume_host_created") + private Date volumeHostCreated; + + @Column(name="format") + private Storage.ImageFormat format; + + @Column (name="download_pct") + private int downloadPercent; + + @Column (name="download_state") + @Enumerated(EnumType.STRING) + private Status downloadState; + + @Column (name="error_str") + private String errorString; + + @Column(name="hypervisor_type") + @Enumerated(value=EnumType.STRING) + private HypervisorType hypervisorType; + + + @Column(name="disk_offering_id") + private long diskOfferingId; + + @Column(name="disk_offering_uuid") + private String diskOfferingUuid; + + @Column(name="disk_offering_name") + private String diskOfferingName; + + @Column(name="disk_offering_display_text") + private String diskOfferingDisplayText; + + @Column(name="system_use") + private boolean systemUse; + + + @Column(name="use_local_storage") + private boolean useLocalStorage; + + @Column(name="pool_id") + private long poolId; + + @Column(name="pool_uuid") + private String poolUuid; + + @Column(name="pool_name") + private String poolName; + + @Column(name="template_id") + private long templateId; + + @Column(name="template_uuid") + private String templateUuid; + + @Column(name="extractable") + private boolean extractable; + + @Column(name="template_type") + private Storage.TemplateType templateType; + + @Column(name="job_id") + private long jobId; + + @Column(name="job_uuid") + private String jobUuid; + + @Column(name="job_status") + private int jobStatus; + + @Column(name="tag_id") + private long tagId; + + @Column(name="tag_uuid") + private String tagUuid; + + @Column(name="tag_key") + private String tagKey; + + @Column(name="tag_value") + private String tagValue; + + @Column(name="tag_domain_id") + private long tagDomainId; + + @Column(name="tag_account_id") + private long tagAccountId; + + @Column(name="tag_resource_id") + private long tagResourceId; + + @Column(name="tag_resource_uuid") + private String tagResourceUuid; + + @Column(name="tag_resource_type") + @Enumerated(value=EnumType.STRING) + private TaggedResourceType tagResourceType; + + @Column(name="tag_customer") + private String tagCustomer; + + + + public VolumeJoinVO() { + } + + + + @Override + public long getId() { + return id; + } + + + + @Override + public void setId(long id) { + this.id = id; + } + + + + @Override + public String getUuid() { + return uuid; + } + + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + + public String getName() { + return name; + } + + + + public void setName(String name) { + this.name = name; + } + + + + public Long getDeviceId() { + return deviceId; + } + + + + public void setDeviceId(Long deviceId) { + this.deviceId = deviceId; + } + + + + public Volume.Type getVolumeType() { + return volumeType; + } + + + + public void setVolumeType(Volume.Type volumeType) { + this.volumeType = volumeType; + } + + + + public long getSize() { + return size; + } + + + + public void setSize(long size) { + this.size = size; + } + + + + public Volume.State getState() { + return state; + } + + + + public void setState(Volume.State state) { + this.state = state; + } + + + + public Date getCreated() { + return created; + } + + + + public void setCreated(Date created) { + this.created = created; + } + + + + public Date getAttached() { + return attached; + } + + + + public void setAttached(Date attached) { + this.attached = attached; + } + + + + public Date getRemoved() { + return removed; + } + + + + public void setRemoved(Date removed) { + this.removed = removed; + } + + + + @Override + public long getAccountId() { + return accountId; + } + + + + public void setAccountId(long accountId) { + this.accountId = accountId; + } + + + + @Override + public String getAccountUuid() { + return accountUuid; + } + + + + public void setAccountUuid(String accountUuid) { + this.accountUuid = accountUuid; + } + + + + @Override + public String getAccountName() { + return accountName; + } + + + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + + + @Override + public short getAccountType() { + return accountType; + } + + + + public void setAccountType(short accountType) { + this.accountType = accountType; + } + + + + @Override + public long getDomainId() { + return domainId; + } + + + + public void setDomainId(long domainId) { + this.domainId = domainId; + } + + + + @Override + public String getDomainUuid() { + return domainUuid; + } + + + + public void setDomainUuid(String domainUuid) { + this.domainUuid = domainUuid; + } + + + + @Override + public String getDomainName() { + return domainName; + } + + + + public void setDomainName(String domainName) { + this.domainName = domainName; + } + + + + @Override + public String getDomainPath() { + return domainPath; + } + + + + public void setDomainPath(String domainPath) { + this.domainPath = domainPath; + } + + + + public long getProjectId() { + return projectId; + } + + + + public void setProjectId(long projectId) { + this.projectId = projectId; + } + + + + @Override + public String getProjectUuid() { + return projectUuid; + } + + + + public void setProjectUuid(String projectUuid) { + this.projectUuid = projectUuid; + } + + + + @Override + public String getProjectName() { + return projectName; + } + + + + public void setProjectName(String projectName) { + this.projectName = projectName; + } + + + + public long getVmId() { + return vmId; + } + + + + public void setVmId(long vmId) { + this.vmId = vmId; + } + + + + public String getVmUuid() { + return vmUuid; + } + + + + public void setVmUuid(String vmUuid) { + this.vmUuid = vmUuid; + } + + + + public String getVmName() { + return vmName; + } + + + + public void setVmName(String vmName) { + this.vmName = vmName; + } + + + + public String getVmDisplayName() { + return vmDisplayName; + } + + + + public void setVmDisplayName(String vmDisplayName) { + this.vmDisplayName = vmDisplayName; + } + + + + public VirtualMachine.State getVmState() { + return vmState; + } + + + + public void setVmState(VirtualMachine.State vmState) { + this.vmState = vmState; + } + + + + public VirtualMachine.Type getVmType() { + return vmType; + } + + + + public void setVmType(VirtualMachine.Type vmType) { + this.vmType = vmType; + } + + + + public long getVolumeHostSize() { + return volumeHostSize; + } + + + + public void setVolumeHostSize(long volumeHostSize) { + this.volumeHostSize = volumeHostSize; + } + + + + public Date getVolumeHostCreated() { + return volumeHostCreated; + } + + + + public void setVolumeHostCreated(Date volumeHostCreated) { + this.volumeHostCreated = volumeHostCreated; + } + + + + public Storage.ImageFormat getFormat() { + return format; + } + + + + public void setFormat(Storage.ImageFormat format) { + this.format = format; + } + + + + public int getDownloadPercent() { + return downloadPercent; + } + + + + public void setDownloadPercent(int downloadPercent) { + this.downloadPercent = downloadPercent; + } + + + + public Status getDownloadState() { + return downloadState; + } + + + + public void setDownloadState(Status downloadState) { + this.downloadState = downloadState; + } + + + + public String getErrorString() { + return errorString; + } + + + + public void setErrorString(String errorString) { + this.errorString = errorString; + } + + + + public HypervisorType getHypervisorType() { + return hypervisorType; + } + + + + public void setHypervisorType(HypervisorType hypervisorType) { + this.hypervisorType = hypervisorType; + } + + + + public long getDiskOfferingId() { + return diskOfferingId; + } + + + + public void setDiskOfferingId(long diskOfferingId) { + this.diskOfferingId = diskOfferingId; + } + + + + public String getDiskOfferingUuid() { + return diskOfferingUuid; + } + + + + public void setDiskOfferingUuid(String diskOfferingUuid) { + this.diskOfferingUuid = diskOfferingUuid; + } + + + + public String getDiskOfferingName() { + return diskOfferingName; + } + + + + public void setDiskOfferingName(String diskOfferingName) { + this.diskOfferingName = diskOfferingName; + } + + + + public String getDiskOfferingDisplayText() { + return diskOfferingDisplayText; + } + + + + public void setDiskOfferingDisplayText(String diskOfferingDisplayText) { + this.diskOfferingDisplayText = diskOfferingDisplayText; + } + + + + public boolean isUseLocalStorage() { + return useLocalStorage; + } + + + + public void setUseLocalStorage(boolean useLocalStorage) { + this.useLocalStorage = useLocalStorage; + } + + + + public long getPoolId() { + return poolId; + } + + + + public void setPoolId(long poolId) { + this.poolId = poolId; + } + + + + public String getPoolUuid() { + return poolUuid; + } + + + + public void setPoolUuid(String poolUuid) { + this.poolUuid = poolUuid; + } + + + + public String getPoolName() { + return poolName; + } + + + + public void setPoolName(String poolName) { + this.poolName = poolName; + } + + + + public long getTemplateId() { + return templateId; + } + + + + public void setTemplateId(long templateId) { + this.templateId = templateId; + } + + + + public String getTemplateUuid() { + return templateUuid; + } + + + + public void setTemplateUuid(String templateUuid) { + this.templateUuid = templateUuid; + } + + + + public boolean isExtractable() { + return extractable; + } + + + + public void setExtractable(boolean extractable) { + this.extractable = extractable; + } + + + + public Storage.TemplateType getTemplateType() { + return templateType; + } + + + + public void setTemplateType(Storage.TemplateType templateType) { + this.templateType = templateType; + } + + + + public long getJobId() { + return jobId; + } + + + + public void setJobId(long jobId) { + this.jobId = jobId; + } + + + + public String getJobUuid() { + return jobUuid; + } + + + + public void setJobUuid(String jobUuid) { + this.jobUuid = jobUuid; + } + + + + public int getJobStatus() { + return jobStatus; + } + + + + public void setJobStatus(int jobStatus) { + this.jobStatus = jobStatus; + } + + + + public long getTagId() { + return tagId; + } + + + + public void setTagId(long tagId) { + this.tagId = tagId; + } + + + + public String getTagUuid() { + return tagUuid; + } + + + + public void setTagUuid(String tagUuid) { + this.tagUuid = tagUuid; + } + + + + public String getTagKey() { + return tagKey; + } + + + + public void setTagKey(String tagKey) { + this.tagKey = tagKey; + } + + + + public String getTagValue() { + return tagValue; + } + + + + public void setTagValue(String tagValue) { + this.tagValue = tagValue; + } + + + + public long getTagDomainId() { + return tagDomainId; + } + + + + public void setTagDomainId(long tagDomainId) { + this.tagDomainId = tagDomainId; + } + + + + public long getTagAccountId() { + return tagAccountId; + } + + + + public void setTagAccountId(long tagAccountId) { + this.tagAccountId = tagAccountId; + } + + + + public long getTagResourceId() { + return tagResourceId; + } + + + + public void setTagResourceId(long tagResourceId) { + this.tagResourceId = tagResourceId; + } + + + + public String getTagResourceUuid() { + return tagResourceUuid; + } + + + + public void setTagResourceUuid(String tagResourceUuid) { + this.tagResourceUuid = tagResourceUuid; + } + + + + public TaggedResourceType getTagResourceType() { + return tagResourceType; + } + + + + public void setTagResourceType(TaggedResourceType tagResourceType) { + this.tagResourceType = tagResourceType; + } + + + + public String getTagCustomer() { + return tagCustomer; + } + + + + public void setTagCustomer(String tagCustomer) { + this.tagCustomer = tagCustomer; + } + + + + public long getDataCenterId() { + return dataCenterId; + } + + + + public void setDataCenterId(long dataCenterId) { + this.dataCenterId = dataCenterId; + } + + + + public String getDataCenterUuid() { + return dataCenterUuid; + } + + + + public void setDataCenterUuid(String dataCenterUuid) { + this.dataCenterUuid = dataCenterUuid; + } + + + + public String getDataCenterName() { + return dataCenterName; + } + + + + public void setDataCenterName(String dataCenterName) { + this.dataCenterName = dataCenterName; + } + + + + public long getPodId() { + return podId; + } + + + + public void setPodId(long podId) { + this.podId = podId; + } + + + + public boolean isSystemUse() { + return systemUse; + } + + + + public void setSystemUse(boolean systemUse) { + this.systemUse = systemUse; + } + + + + +} diff --git a/server/src/com/cloud/api/response/ApiResponseSerializer.java b/server/src/com/cloud/api/response/ApiResponseSerializer.java index 124bee1f2e3..470cc5f9587 100644 --- a/server/src/com/cloud/api/response/ApiResponseSerializer.java +++ b/server/src/com/cloud/api/response/ApiResponseSerializer.java @@ -21,20 +21,23 @@ import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.apache.cloudstack.api.response.ListResponse; +import org.apache.cloudstack.api.response.*; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; import com.cloud.api.ApiResponseGsonHelper; import com.cloud.api.ApiServer; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ResponseObject; import com.cloud.utils.IdentityProxy; -import com.cloud.api.ResponseObject; import com.cloud.utils.encoding.URLEncoder; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.uuididentity.dao.IdentityDao; @@ -46,6 +49,7 @@ public class ApiResponseSerializer { private static final Logger s_logger = Logger.getLogger(ApiResponseSerializer.class.getName()); public static String toSerializedString(ResponseObject result, String responseType) { + s_logger.trace("===Serializing Response==="); if (BaseCmd.RESPONSE_TYPE_JSON.equalsIgnoreCase(responseType)) { return toJSONSerializedString(result); } else { @@ -67,36 +71,45 @@ public class ApiResponseSerializer { public static String toJSONSerializedString(ResponseObject result) { if (result != null) { Gson gson = ApiResponseGsonHelper.getBuilder().excludeFieldsWithModifiers(Modifier.TRANSIENT).create(); - + StringBuilder sb = new StringBuilder(); - sb.append("{ \"" + result.getResponseName() + "\" : "); + sb.append("{ \"").append(result.getResponseName()).append("\" : "); if (result instanceof ListResponse) { List responses = ((ListResponse) result).getResponses(); - if ((responses != null) && !responses.isEmpty()) { + Integer count = ((ListResponse) result).getCount(); + boolean nonZeroCount = (count != null && count.longValue() != 0); + if (nonZeroCount) { + sb.append("{ \"").append(ApiConstants.COUNT).append("\":").append(count); + } - Integer count = ((ListResponse) result).getCount(); - String jsonStr = gson.toJson(responses.get(0)); + if ((responses != null) && !responses.isEmpty()) { + String jsonStr = gson.toJson(responses.get(0)); jsonStr = unescape(jsonStr); - if (count != null && count != 0) { - sb.append("{ \"" + ApiConstants.COUNT + "\":" + ((ListResponse) result).getCount() + " ,\"" + responses.get(0).getObjectName() + "\" : [ " + jsonStr); + if (nonZeroCount) { + sb.append(" ,\"").append(responses.get(0).getObjectName()).append("\" : [ ").append(jsonStr); } - for (int i = 1; i < count; i++) { + + for (int i = 1; i < ((ListResponse) result).getResponses().size(); i++) { jsonStr = gson.toJson(responses.get(i)); jsonStr = unescape(jsonStr); - sb.append(", " + jsonStr); + sb.append(", ").append(jsonStr); } sb.append(" ] }"); - } else { - sb.append("{ }"); + } else { + if (!nonZeroCount){ + sb.append("{"); + } + + sb.append(" }"); } } else if (result instanceof SuccessResponse) { - sb.append("{ \"success\" : \"" + ((SuccessResponse) result).getSuccess() + "\"} "); - } else if (result instanceof ExceptionResponse) { + sb.append("{ \"success\" : \"").append(((SuccessResponse) result).getSuccess()).append("\"} "); + } else if (result instanceof ExceptionResponse) { String jsonErrorText = gson.toJson((ExceptionResponse) result); jsonErrorText = unescape(jsonErrorText); - sb.append(jsonErrorText); + sb.append(jsonErrorText); } else { String jsonStr = gson.toJson(result); if ((jsonStr != null) && !"".equals(jsonStr)) { @@ -104,13 +117,15 @@ public class ApiResponseSerializer { if (result instanceof AsyncJobResponse || result instanceof CreateCmdResponse) { sb.append(jsonStr); } else { - sb.append(" { \"" + result.getObjectName() + "\" : " + jsonStr + " } "); + sb.append(" { \"").append(result.getObjectName()).append("\" : ").append(jsonStr).append(" } "); } } else { sb.append("{ }"); } } - sb.append(" }"); + sb.append(", \"cloudstack-version\": \""); + sb.append(ApiDBUtils.getVersion()); + sb.append("\" }"); return sb.toString(); } return null; @@ -119,13 +134,14 @@ public class ApiResponseSerializer { private static String toXMLSerializedString(ResponseObject result) { StringBuilder sb = new StringBuilder(); sb.append(""); - sb.append("<" + result.getResponseName() + " cloud-stack-version=\"" + ApiDBUtils.getVersion() + "\">"); + sb.append("<").append(result.getResponseName()).append(" cloudstack-version=\"").append(ApiDBUtils.getVersion()).append("\">"); if (result instanceof ListResponse) { Integer count = ((ListResponse) result).getCount(); if (count != null && count != 0) { - sb.append("<" + ApiConstants.COUNT + ">" + ((ListResponse) result).getCount() + ""); + sb.append("<").append(ApiConstants.COUNT).append(">").append(((ListResponse) result).getCount()). + append(""); } List responses = ((ListResponse) result).getResponses(); if ((responses != null) && !responses.isEmpty()) { @@ -141,17 +157,17 @@ public class ApiResponseSerializer { } } - sb.append(""); + sb.append(""); return sb.toString(); } private static void serializeResponseObjXML(StringBuilder sb, ResponseObject obj) { if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) { - sb.append("<" + obj.getObjectName() + ">"); + sb.append("<").append(obj.getObjectName()).append(">"); } serializeResponseObjFieldsXML(sb, obj); if (!(obj instanceof SuccessResponse) && !(obj instanceof ExceptionResponse)) { - sb.append(""); + sb.append(""); } } @@ -163,7 +179,7 @@ public class ApiResponseSerializer { } return fields.toArray(new Field[] {}); } - + private static void serializeResponseObjFieldsXML(StringBuilder sb, ResponseObject obj) { boolean isAsync = false; if (obj instanceof AsyncJobResponse) @@ -200,8 +216,8 @@ public class ApiResponseSerializer { if (isAsync) { sb.append(""); } - } else if (fieldValue instanceof List) { - List subResponseList = (List) fieldValue; + } else if (fieldValue instanceof Collection) { + Collection subResponseList = (Collection) fieldValue; boolean usedUuidList = false; for (Object value : subResponseList) { if (value instanceof ResponseObject) { @@ -212,34 +228,35 @@ public class ApiResponseSerializer { serializeResponseObjXML(sb, subObj); } else if (value instanceof IdentityProxy) { // Only exception reponses carry a list of IdentityProxy objects. - IdentityProxy idProxy = (IdentityProxy)value; + IdentityProxy idProxy = (IdentityProxy)value; String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : ""); if(!id.isEmpty()) { IdentityDao identityDao = new IdentityDaoImpl(); id = identityDao.getIdentityUuid(idProxy.getTableName(), id); - } + } if(id != null && !id.isEmpty()) { // If this is the first IdentityProxy field encountered, put in a uuidList tag. if (!usedUuidList) { - sb.append("<" + serializedName.value() + ">"); + sb.append("<").append(serializedName.value()).append(">"); usedUuidList = true; } - sb.append("<" + "uuid" + ">" + id + ""); + sb.append("").append(id).append(""); } // Append the new idFieldName property also. String idFieldName = idProxy.getidFieldName(); if (idFieldName != null) { - sb.append("<" + "uuidProperty" + ">" + idFieldName + ""); + sb.append("").append(idFieldName).append(""); } - } + } } if (usedUuidList) { // close the uuidList. - sb.append(""); + sb.append(""); } } else if (fieldValue instanceof Date) { - sb.append("<" + serializedName.value() + ">" + BaseCmd.getDateString((Date) fieldValue) + ""); - } else if (fieldValue instanceof IdentityProxy) { + sb.append("<").append(serializedName.value()).append(">").append(BaseCmd.getDateString((Date) fieldValue)). + append(""); + } else if (fieldValue instanceof IdentityProxy) { IdentityProxy idProxy = (IdentityProxy)fieldValue; String id = (idProxy.getValue() != null ? String.valueOf(idProxy.getValue()) : ""); if(!id.isEmpty()) { @@ -251,14 +268,14 @@ public class ApiResponseSerializer { } } if(id != null && !id.isEmpty()) - sb.append("<" + serializedName.value() + ">" + id + ""); + sb.append("<").append(serializedName.value()).append(">").append(id).append(""); } else { String resultString = escapeSpecialXmlChars(fieldValue.toString()); if (!(obj instanceof ExceptionResponse)) { resultString = encodeParam(resultString); } - - sb.append("<" + serializedName.value() + ">" + resultString + ""); + + sb.append("<").append(serializedName.value()).append(">").append(resultString).append(""); } } } @@ -324,10 +341,10 @@ public class ApiResponseSerializer { resultString.append(singleChar); } } - + return resultString.toString(); } - + private static String encodeParam(String value) { if (!ApiServer.encodeApiResponse) { return value; @@ -339,5 +356,5 @@ public class ApiResponseSerializer { } return value; } - + } diff --git a/server/src/com/cloud/api/response/SecurityGroupResultObject.java b/server/src/com/cloud/api/response/SecurityGroupResultObject.java index 5c3b7633c5d..aab13cdc529 100644 --- a/server/src/com/cloud/api/response/SecurityGroupResultObject.java +++ b/server/src/com/cloud/api/response/SecurityGroupResultObject.java @@ -21,14 +21,15 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.api.ApiDBUtils; import com.cloud.network.security.SecurityGroup; import com.cloud.network.security.SecurityGroupRules; import com.cloud.serializer.Param; import com.cloud.user.Account; +import org.apache.cloudstack.api.InternalIdentity; -public class SecurityGroupResultObject implements ControlledEntity{ +public class SecurityGroupResultObject implements ControlledEntity, InternalIdentity { @Param(name = "id") private Long id; @@ -63,7 +64,7 @@ public class SecurityGroupResultObject implements ControlledEntity{ this.securityGroupRules = ingressRules; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/async/AsyncJobManager.java b/server/src/com/cloud/async/AsyncJobManager.java index 4664e1b07c0..4cd67f3e39c 100644 --- a/server/src/com/cloud/async/AsyncJobManager.java +++ b/server/src/com/cloud/async/AsyncJobManager.java @@ -18,15 +18,16 @@ package com.cloud.async; import java.util.List; -import com.cloud.api.commands.QueryAsyncJobResultCmd; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; import com.cloud.utils.component.Manager; public interface AsyncJobManager extends Manager { public AsyncJobExecutorContext getExecutorContext(); - public AsyncJobVO getAsyncJob(long jobId); - public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId); + public AsyncJobVO getAsyncJob(long jobId); + public AsyncJobVO findInstancePendingAsyncJob(String instanceType, long instanceId); + public List findInstancePendingAsyncJobs(AsyncJob.Type instanceType, Long accountId); public long submitAsyncJob(AsyncJobVO job); @@ -39,7 +40,7 @@ public interface AsyncJobManager extends Manager { public void releaseSyncSource(AsyncJobExecutor executor); - public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId); + public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId, long queueSizeLimit); /** * Queries for the status or final result of an async job. diff --git a/server/src/com/cloud/async/AsyncJobManagerImpl.java b/server/src/com/cloud/async/AsyncJobManagerImpl.java index 00546fb9574..e4016f73096 100644 --- a/server/src/com/cloud/async/AsyncJobManagerImpl.java +++ b/server/src/com/cloud/async/AsyncJobManagerImpl.java @@ -34,6 +34,7 @@ import java.util.concurrent.TimeUnit; import javax.ejb.Local; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.job.QueryAsyncJobResultCmd; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import org.springframework.stereotype.Component; @@ -41,11 +42,10 @@ import org.springframework.stereotype.Component; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; import com.cloud.api.ApiSerializerHelper; -import com.cloud.api.BaseAsyncCmd; -import com.cloud.api.BaseCmd; -import com.cloud.api.ServerApiException; -import com.cloud.api.commands.QueryAsyncJobResultCmd; -import com.cloud.api.response.ExceptionResponse; +import org.apache.cloudstack.api.BaseAsyncCmd; +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.ServerApiException; +import org.apache.cloudstack.api.response.ExceptionResponse; import com.cloud.async.dao.AsyncJobDao; import com.cloud.cluster.ClusterManager; import com.cloud.cluster.ClusterManagerListener; @@ -94,7 +94,8 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe private AccountDao _accountDao; private AsyncJobDao _jobDao; private long _jobExpireSeconds = 86400; // 1 day - private long _jobCancelThresholdSeconds = 3600; // 1 hour + private long _jobCancelThresholdSeconds = 3600; // 1 hour (for cancelling the jobs blocking other jobs) + private ApiDispatcher _dispatcher; private final ScheduledExecutorService _heartbeatScheduler = @@ -250,7 +251,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } @Override - public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId) { + public void syncAsyncJobExecution(AsyncJob job, String syncObjType, long syncObjId, long queueSizeLimit) { // This method is re-entrant. If an API developer wants to synchronized on an object, e.g. the router, // when executing business logic, they will call this method (actually a method in BaseAsyncCmd that calls this). // This method will get called every time their business logic executes. The first time it exectues for a job @@ -271,7 +272,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe Random random = new Random(); for(int i = 0; i < 5; i++) { - queue = _queueMgr.queue(syncObjType, syncObjId, "AsyncJob", job.getId()); + queue = _queueMgr.queue(syncObjType, syncObjId, SyncQueueItem.AsyncJobContentType, job.getId(), queueSizeLimit); if(queue != null) { break; } @@ -613,7 +614,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } } - private void reallyRun() { + public void reallyRun() { try { s_logger.trace("Begin cleanup expired async-jobs"); @@ -624,16 +625,17 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe List l = _jobDao.getExpiredJobs(cutTime, 100); if(l != null && l.size() > 0) { for(AsyncJobVO job : l) { - _jobDao.expunge(job.getId()); + expungeAsyncJob(job); } } - // forcely cancel blocking queue items if they've been staying there for too long + // forcefully cancel blocking queue items if they've been staying there for too long List blockItems = _queueMgr.getBlockedQueueItems(_jobCancelThresholdSeconds*1000, false); if(blockItems != null && blockItems.size() > 0) { for(SyncQueueItemVO item : blockItems) { - if(item.getContentType().equalsIgnoreCase("AsyncJob")) { - completeAsyncJob(item.getContentId(), AsyncJobResult.STATUS_FAILED, 0, getResetResultResponse("Job is cancelled as it has been blocking others for too long")); + if(item.getContentType().equalsIgnoreCase(SyncQueueItem.AsyncJobContentType)) { + completeAsyncJob(item.getContentId(), AsyncJobResult.STATUS_FAILED, 0, + getResetResultResponse("Job is cancelled as it has been blocking others for too long")); } // purge the item and resume queue processing @@ -648,9 +650,21 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe StackMaid.current().exitCleanup(); } } + + }; } + @DB + protected void expungeAsyncJob(AsyncJobVO job) { + Transaction txn = Transaction.currentTxn(); + txn.start(); + _jobDao.expunge(job.getId()); + //purge corresponding sync queue item + _queueMgr.purgeAsyncJobQueueItemId(job.getId()); + txn.commit(); + } + private long getMsid() { if(_clusterMgr != null) { return _clusterMgr.getManagementNodeId(); @@ -667,7 +681,7 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe } String contentType = item.getContentType(); - if(contentType != null && contentType.equals("AsyncJob")) { + if(contentType != null && contentType.equalsIgnoreCase(SyncQueueItem.AsyncJobContentType)) { Long jobId = item.getContentId(); if(jobId != null) { s_logger.warn("Mark job as failed as its correspoding queue-item has been discarded. job id: " + jobId); @@ -757,7 +771,6 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe txn.start(); List items = _queueMgr.getActiveQueueItems(msHost.getId(), true); cleanupPendingJobs(items); - _queueMgr.resetQueueProcess(msHost.getId()); _jobDao.resetJobProcess(msHost.getId(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); txn.commit(); } catch(Throwable e) { @@ -778,7 +791,6 @@ public class AsyncJobManagerImpl implements AsyncJobManager, ClusterManagerListe try { List l = _queueMgr.getActiveQueueItems(getMsid(), false); cleanupPendingJobs(l); - _queueMgr.resetQueueProcess(getMsid()); _jobDao.resetJobProcess(getMsid(), BaseCmd.INTERNAL_ERROR, getSerializedErrorMessage("job cancelled because of management server restart")); } catch(Throwable e) { s_logger.error("Unexpected exception " + e.getMessage(), e); diff --git a/server/src/com/cloud/async/SyncQueueManager.java b/server/src/com/cloud/async/SyncQueueManager.java index 1dd82530c2a..a7032daaa47 100644 --- a/server/src/com/cloud/async/SyncQueueManager.java +++ b/server/src/com/cloud/async/SyncQueueManager.java @@ -20,14 +20,16 @@ import java.util.List; import com.cloud.utils.component.Manager; -public interface SyncQueueManager extends Manager { - public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId); - public SyncQueueItemVO dequeueFromOne(long queueId, Long msid); - public List dequeueFromAny(Long msid, int maxItems); - public void purgeItem(long queueItemId); + +public interface SyncQueueManager extends Manager { + public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId, long queueSizeLimit); + public SyncQueueItemVO dequeueFromOne(long queueId, Long msid); + public List dequeueFromAny(Long msid, int maxItems); + public void purgeItem(long queueItemId); public void returnItem(long queueItemId); public List getActiveQueueItems(Long msid, boolean exclusive); public List getBlockedQueueItems(long thresholdMs, boolean exclusive); - public void resetQueueProcess(long msid); -} + + void purgeAsyncJobQueueItemId(long asyncJobId); +} diff --git a/server/src/com/cloud/async/SyncQueueManagerImpl.java b/server/src/com/cloud/async/SyncQueueManagerImpl.java index f316ff64610..94fcf0bc4a5 100644 --- a/server/src/com/cloud/async/SyncQueueManagerImpl.java +++ b/server/src/com/cloud/async/SyncQueueManagerImpl.java @@ -35,7 +35,7 @@ import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.exception.CloudRuntimeException; -@Component + @Local(value={SyncQueueManager.class}) public class SyncQueueManagerImpl implements SyncQueueManager { public static final Logger s_logger = Logger.getLogger(SyncQueueManagerImpl.class.getName()); @@ -47,7 +47,7 @@ public class SyncQueueManagerImpl implements SyncQueueManager { @Override @DB - public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId) { + public SyncQueueVO queue(String syncObjType, long syncObjId, String itemType, long itemId, long queueSizeLimit) { Transaction txn = Transaction.currentTxn(); try { txn.start(); @@ -57,6 +57,8 @@ public class SyncQueueManagerImpl implements SyncQueueManager { if(queueVO == null) throw new CloudRuntimeException("Unable to queue item into DB, DB is full?"); + queueVO.setQueueSizeLimit(queueSizeLimit); + _syncQueueDao.update(queueVO.getId(), queueVO); Date dt = DateUtil.currentGMTTime(); SyncQueueItemVO item = new SyncQueueItemVO(); @@ -90,7 +92,7 @@ public class SyncQueueManagerImpl implements SyncQueueManager { return null; } - if(queueVO.getLastProcessTime() == null) { + if(queueReadyToProcess(queueVO)) { SyncQueueItemVO itemVO = _syncQueueItemDao.getNextQueueItem(queueVO.getId()); if(itemVO != null) { Long processNumber = queueVO.getLastProcessNumber(); @@ -99,14 +101,14 @@ public class SyncQueueManagerImpl implements SyncQueueManager { else processNumber = processNumber + 1; Date dt = DateUtil.currentGMTTime(); - queueVO.setLastProcessMsid(msid); queueVO.setLastProcessNumber(processNumber); - queueVO.setLastProcessTime(dt); queueVO.setLastUpdated(dt); + queueVO.setQueueSize(queueVO.getQueueSize() + 1); _syncQueueDao.update(queueVO.getId(), queueVO); itemVO.setLastProcessMsid(msid); itemVO.setLastProcessNumber(processNumber); + itemVO.setLastProcessTime(dt); _syncQueueItemDao.update(itemVO.getId(), itemVO); txt.commit(); @@ -142,7 +144,7 @@ public class SyncQueueManagerImpl implements SyncQueueManager { for(SyncQueueItemVO item : l) { SyncQueueVO queueVO = _syncQueueDao.lockRow(item.getQueueId(), true); SyncQueueItemVO itemVO = _syncQueueItemDao.lockRow(item.getId(), true); - if(queueVO.getLastProcessTime() == null && itemVO.getLastProcessNumber() == null) { + if(queueReadyToProcess(queueVO) && itemVO.getLastProcessNumber() == null) { Long processNumber = queueVO.getLastProcessNumber(); if(processNumber == null) processNumber = new Long(1); @@ -150,14 +152,14 @@ public class SyncQueueManagerImpl implements SyncQueueManager { processNumber = processNumber + 1; Date dt = DateUtil.currentGMTTime(); - queueVO.setLastProcessMsid(msid); queueVO.setLastProcessNumber(processNumber); - queueVO.setLastProcessTime(dt); queueVO.setLastUpdated(dt); + queueVO.setQueueSize(queueVO.getQueueSize() + 1); _syncQueueDao.update(queueVO.getId(), queueVO); itemVO.setLastProcessMsid(msid); itemVO.setLastProcessNumber(processNumber); + itemVO.setLastProcessTime(dt); _syncQueueItemDao.update(item.getId(), itemVO); resultList.add(item); @@ -186,10 +188,15 @@ public class SyncQueueManagerImpl implements SyncQueueManager { _syncQueueItemDao.expunge(itemVO.getId()); - queueVO.setLastProcessTime(null); + //if item is active, reset queue information + if (itemVO.getLastProcessMsid() != null) { queueVO.setLastUpdated(DateUtil.currentGMTTime()); + //decrement the count + assert (queueVO.getQueueSize() > 0) : "Count reduce happens when it's already <= 0!"; + queueVO.setQueueSize(queueVO.getQueueSize() - 1); _syncQueueDao.update(queueVO.getId(), queueVO); } + } txt.commit(); } catch(Exception e) { s_logger.error("Unexpected exception: ", e); @@ -210,9 +217,9 @@ public class SyncQueueManagerImpl implements SyncQueueManager { itemVO.setLastProcessMsid(null); itemVO.setLastProcessNumber(null); + itemVO.setLastProcessTime(null); _syncQueueItemDao.update(queueItemId, itemVO); - queueVO.setLastProcessTime(null); queueVO.setLastUpdated(DateUtil.currentGMTTime()); _syncQueueDao.update(queueVO.getId(), queueVO); } @@ -233,11 +240,6 @@ public class SyncQueueManagerImpl implements SyncQueueManager { return _syncQueueItemDao.getBlockedQueueItems(thresholdMs, exclusive); } - @Override - public void resetQueueProcess(long msid) { - _syncQueueDao.resetQueueProcessing(msid); - } - @Override public boolean configure(String name, Map params) throws ConfigurationException { _name = name; @@ -272,5 +274,16 @@ public class SyncQueueManagerImpl implements SyncQueueManager { public String getName() { return _name; } -} + private boolean queueReadyToProcess(SyncQueueVO queueVO) { + return queueVO.getQueueSize() < queueVO.getQueueSizeLimit(); + } + + @Override + public void purgeAsyncJobQueueItemId(long asyncJobId) { + Long itemId = _syncQueueItemDao.getQueueItemIdByContentIdAndType(asyncJobId, SyncQueueItem.AsyncJobContentType); + if (itemId != null) { + purgeItem(itemId); + } + } +} diff --git a/server/src/com/cloud/async/dao/SyncQueueDao.java b/server/src/com/cloud/async/dao/SyncQueueDao.java index 1b04973d6f9..816f9dd1c30 100644 --- a/server/src/com/cloud/async/dao/SyncQueueDao.java +++ b/server/src/com/cloud/async/dao/SyncQueueDao.java @@ -22,5 +22,4 @@ import com.cloud.utils.db.GenericDao; public interface SyncQueueDao extends GenericDao{ public void ensureQueue(String syncObjType, long syncObjId); public SyncQueueVO find(String syncObjType, long syncObjId); - public void resetQueueProcessing(long msid); -} +} diff --git a/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java b/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java index 599e345901c..7b4c182c6aa 100644 --- a/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java +++ b/server/src/com/cloud/async/dao/SyncQueueDaoImpl.java @@ -14,6 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. + package com.cloud.async.dao; import java.sql.PreparedStatement; @@ -28,7 +29,6 @@ import org.springframework.stereotype.Component; import com.cloud.async.SyncQueueVO; import com.cloud.utils.DateUtil; -import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; @@ -44,7 +44,8 @@ public class SyncQueueDaoImpl extends GenericDaoBase implemen @Override public void ensureQueue(String syncObjType, long syncObjId) { Date dt = DateUtil.currentGMTTime(); - String sql = "INSERT IGNORE INTO sync_queue(sync_objtype, sync_objid, created, last_updated) values(?, ?, ?, ?)"; + String sql = "INSERT IGNORE INTO sync_queue(sync_objtype, sync_objid, created, last_updated)" + + " values(?, ?, ?, ?)"; Transaction txn = Transaction.currentTxn(); PreparedStatement pstmt = null; @@ -70,23 +71,6 @@ public class SyncQueueDaoImpl extends GenericDaoBase implemen return findOneBy(sc); } - @Override @DB - public void resetQueueProcessing(long msid) { - String sql = "UPDATE sync_queue set queue_proc_msid=NULL, queue_proc_time=NULL where queue_proc_msid=?"; - - Transaction txn = Transaction.currentTxn(); - PreparedStatement pstmt = null; - try { - pstmt = txn.prepareAutoCloseStatement(sql); - pstmt.setLong(1, msid); - pstmt.execute(); - } catch (SQLException e) { - s_logger.warn("Unable to reset sync queue for management server " + msid, e); - } catch (Throwable e) { - s_logger.warn("Unable to reset sync queue for management server " + msid, e); - } - } - protected SyncQueueDaoImpl() { super(); TypeIdSearch = createSearchBuilder(); diff --git a/server/src/com/cloud/async/dao/SyncQueueItemDao.java b/server/src/com/cloud/async/dao/SyncQueueItemDao.java index cd9df2f4682..6b9da8b63ea 100644 --- a/server/src/com/cloud/async/dao/SyncQueueItemDao.java +++ b/server/src/com/cloud/async/dao/SyncQueueItemDao.java @@ -26,4 +26,5 @@ public interface SyncQueueItemDao extends GenericDao { public List getNextQueueItems(int maxItems); public List getActiveQueueItems(Long msid, boolean exclusive); public List getBlockedQueueItems(long thresholdMs, boolean exclusive); -} + public Long getQueueItemIdByContentIdAndType(long contentId, String contentType); +} diff --git a/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java b/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java index 6d7342cbb50..8ee21f39af5 100644 --- a/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java +++ b/server/src/com/cloud/async/dao/SyncQueueItemDaoImpl.java @@ -14,6 +14,7 @@ // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. + package com.cloud.async.dao; import java.sql.PreparedStatement; @@ -31,22 +32,30 @@ import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.async.SyncQueueItemVO; -import com.cloud.async.SyncQueueVO; import com.cloud.utils.DateUtil; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; -import com.cloud.utils.db.JoinBuilder; +import com.cloud.utils.db.GenericSearchBuilder; 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; @Component @Local(value = { SyncQueueItemDao.class }) public class SyncQueueItemDaoImpl extends GenericDaoBase implements SyncQueueItemDao { private static final Logger s_logger = Logger.getLogger(SyncQueueItemDaoImpl.class); + final GenericSearchBuilder queueIdSearch; + + protected SyncQueueItemDaoImpl() { + super(); + queueIdSearch = createSearchBuilder(Long.class); + queueIdSearch.and("contentId", queueIdSearch.entity().getContentId(), Op.EQ); + queueIdSearch.and("contentType", queueIdSearch.entity().getContentType(), Op.EQ); + queueIdSearch.selectField(queueIdSearch.entity().getId()); + queueIdSearch.done(); + } - // private final SyncQueueDao _syncQueueDao = new SyncQueueDaoImpl(); - @Inject private SyncQueueDao _syncQueueDao; @Override public SyncQueueItemVO getNextQueueItem(long queueId) { @@ -73,7 +82,7 @@ public class SyncQueueItemDaoImpl extends GenericDaoBase String sql = "SELECT i.id, i.queue_id, i.content_type, i.content_id, i.created " + " FROM sync_queue AS q JOIN sync_queue_item AS i ON q.id = i.queue_id " + - " WHERE q.queue_proc_time IS NULL AND i.queue_proc_number IS NULL " + + " WHERE q.queue_size < q.queue_size_limit AND i.queue_proc_number IS NULL " + " GROUP BY q.id " + " ORDER BY i.id " + " LIMIT 0, ?"; @@ -118,28 +127,35 @@ public class SyncQueueItemDaoImpl extends GenericDaoBase return listBy(sc, filter); } + @Override public List getBlockedQueueItems(long thresholdMs, boolean exclusive) { Date cutTime = DateUtil.currentGMTTime(); - cutTime = new Date(cutTime.getTime() - thresholdMs); - - SearchBuilder sbQueue = _syncQueueDao.createSearchBuilder(); - sbQueue.and("lastProcessTime", sbQueue.entity().getLastProcessTime(), SearchCriteria.Op.NNULL); - sbQueue.and("lastProcessTime2", sbQueue.entity().getLastProcessTime(), SearchCriteria.Op.LT); SearchBuilder sbItem = createSearchBuilder(); - sbItem.join("queueItemJoinQueue", sbQueue, sbQueue.entity().getId(), sbItem.entity().getQueueId(), JoinBuilder.JoinType.INNER); sbItem.and("lastProcessMsid", sbItem.entity().getLastProcessMsid(), SearchCriteria.Op.NNULL); sbItem.and("lastProcessNumber", sbItem.entity().getLastProcessNumber(), SearchCriteria.Op.NNULL); + sbItem.and("lastProcessNumber", sbItem.entity().getLastProcessTime(), SearchCriteria.Op.NNULL); + sbItem.and("lastProcessTime2", sbItem.entity().getLastProcessTime(), SearchCriteria.Op.LT); - sbQueue.done(); sbItem.done(); SearchCriteria sc = sbItem.create(); - sc.setJoinParameters("queueItemJoinQueue", "lastProcessTime2", cutTime); + sc.setParameters("lastProcessTime2", new Date(cutTime.getTime() - thresholdMs)); if(exclusive) return lockRows(sc, null, true); return listBy(sc, null); } + + + @Override + public Long getQueueItemIdByContentIdAndType(long contentId, String contentType) { + SearchCriteria sc = queueIdSearch.create(); + sc.setParameters("contentId", contentId); + sc.setParameters("contentType", contentType); + List id = customSearch(sc, null); + + return id.size() == 0 ? null : id.get(0); + } } diff --git a/server/src/com/cloud/baremetal/BareMetalDiscoverer.java b/server/src/com/cloud/baremetal/BareMetalDiscoverer.java index a56f378e3c1..eb168da44a7 100755 --- a/server/src/com/cloud/baremetal/BareMetalDiscoverer.java +++ b/server/src/com/cloud/baremetal/BareMetalDiscoverer.java @@ -32,7 +32,7 @@ import org.springframework.stereotype.Component; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.dc.ClusterVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.dao.ClusterDao; diff --git a/server/src/com/cloud/baremetal/BareMetalResourceBase.java b/server/src/com/cloud/baremetal/BareMetalResourceBase.java index 2f679e7d678..36afa8ba54b 100755 --- a/server/src/com/cloud/baremetal/BareMetalResourceBase.java +++ b/server/src/com/cloud/baremetal/BareMetalResourceBase.java @@ -54,7 +54,7 @@ import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand.BootDev; import com.cloud.agent.api.baremetal.IpmiBootorResetCommand; import com.cloud.agent.api.to.VirtualMachineTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor; import com.cloud.resource.ServerResource; diff --git a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java index e61b94238c8..cd3f2cbcea2 100755 --- a/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java +++ b/server/src/com/cloud/baremetal/BareMetalTemplateAdapter.java @@ -22,12 +22,12 @@ import java.util.List; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; diff --git a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java index 02775bdfc82..c419f5ab89a 100755 --- a/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java +++ b/server/src/com/cloud/baremetal/BareMetalVmManagerImpl.java @@ -27,6 +27,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.log4j.Logger; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @@ -36,12 +41,7 @@ import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.baremetal.IpmISetBootDevCommand; import com.cloud.agent.api.baremetal.IpmiBootorResetCommand; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; diff --git a/server/src/com/cloud/baremetal/DhcpServerResponse.java b/server/src/com/cloud/baremetal/DhcpServerResponse.java index 761f604e8f3..db46ccd1a1d 100644 --- a/server/src/com/cloud/baremetal/DhcpServerResponse.java +++ b/server/src/com/cloud/baremetal/DhcpServerResponse.java @@ -16,21 +16,20 @@ // under the License. package com.cloud.baremetal; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class DhcpServerResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the Dhcp server") - private IdentityProxy id = new IdentityProxy("host"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java index 411a7b812d0..b3d5e972229 100755 --- a/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java +++ b/server/src/com/cloud/baremetal/ExternalDhcpManagerImpl.java @@ -169,7 +169,7 @@ public class ExternalDhcpManagerImpl implements ExternalDhcpManager, ResourceSta @Override public DhcpServerResponse getApiResponse(Host dhcpServer) { DhcpServerResponse response = new DhcpServerResponse(); - response.setId(dhcpServer.getId()); + response.setId(dhcpServer.getUuid()); return response; } diff --git a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java index 03f91d25f38..6e123afc710 100755 --- a/server/src/com/cloud/baremetal/PxeServerManagerImpl.java +++ b/server/src/com/cloud/baremetal/PxeServerManagerImpl.java @@ -103,7 +103,7 @@ public class PxeServerManagerImpl implements PxeServerManager, ResourceStateAdap @Override public PxeServerResponse getApiResponse(Host pxeServer) { PxeServerResponse response = new PxeServerResponse(); - response.setId(pxeServer.getId()); + response.setId(pxeServer.getUuid()); return response; } diff --git a/server/src/com/cloud/baremetal/PxeServerResponse.java b/server/src/com/cloud/baremetal/PxeServerResponse.java index 26ea865e825..32fcc7fb5b9 100644 --- a/server/src/com/cloud/baremetal/PxeServerResponse.java +++ b/server/src/com/cloud/baremetal/PxeServerResponse.java @@ -16,21 +16,20 @@ // under the License. package com.cloud.baremetal; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class PxeServerResponse extends BaseResponse { @SerializedName(ApiConstants.ID) @Param(description="the ID of the PXE server") - private IdentityProxy id = new IdentityProxy("host"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/cluster/CheckPointVO.java b/server/src/com/cloud/cluster/CheckPointVO.java index 27b7f93419e..db4f828721a 100644 --- a/server/src/com/cloud/cluster/CheckPointVO.java +++ b/server/src/com/cloud/cluster/CheckPointVO.java @@ -26,10 +26,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="stack_maid") -public class CheckPointVO { +public class CheckPointVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/ClusterManagerImpl.java b/server/src/com/cloud/cluster/ClusterManagerImpl.java index 19705eceebe..9976bd7f7d0 100755 --- a/server/src/com/cloud/cluster/ClusterManagerImpl.java +++ b/server/src/com/cloud/cluster/ClusterManagerImpl.java @@ -414,6 +414,23 @@ public class ClusterManagerImpl implements ClusterManager { Answer[] answers = new Answer[1]; answers[0] = new Answer(cmd, result, null); return _gson.toJson(answers); + } else if (cmds.length == 1 && cmds[0] instanceof PropagateResourceEventCommand ) { + PropagateResourceEventCommand cmd = (PropagateResourceEventCommand) cmds[0]; + + s_logger.debug("Intercepting command to propagate event " + cmd.getEvent().name() + " for host " + cmd.getHostId()); + + boolean result = false; + try { + result = executeResourceUserRequest(cmd.getHostId(), cmd.getEvent()); + s_logger.debug("Result is " + result); + } catch (AgentUnavailableException ex) { + s_logger.warn("Agent is unavailable", ex); + return null; + } + + Answer[] answers = new Answer[1]; + answers[0] = new Answer(cmd, result, null); + return _gson.toJson(answers); } try { @@ -801,6 +818,7 @@ public class ClusterManagerImpl implements ClusterManager { invalidHeartbeatConnection(); } finally { + txn.transitToAutoManagedConnection(Transaction.CLOUD_DB); txn.close("ClusterHeartBeat"); } } 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/cluster/ManagementServerHostPeerVO.java b/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java index 4699f15a5ff..e5e12ecb8bf 100644 --- a/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java +++ b/server/src/com/cloud/cluster/ManagementServerHostPeerVO.java @@ -30,10 +30,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.DateUtil; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mshost_peer") -public class ManagementServerHostPeerVO { +public class ManagementServerHostPeerVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/ManagementServerHostVO.java b/server/src/com/cloud/cluster/ManagementServerHostVO.java index ba2498d7352..31642e4d0c5 100644 --- a/server/src/com/cloud/cluster/ManagementServerHostVO.java +++ b/server/src/com/cloud/cluster/ManagementServerHostVO.java @@ -30,10 +30,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="mshost") -public class ManagementServerHostVO implements ManagementServerHost{ +public class ManagementServerHostVO implements ManagementServerHost { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java b/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java index 9255c277e90..9c2edde299b 100644 --- a/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java +++ b/server/src/com/cloud/cluster/agentlb/HostTransferMapVO.java @@ -26,11 +26,12 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "op_host_transfer") @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) -public class HostTransferMapVO { +public class HostTransferMapVO implements InternalIdentity { public enum HostTransferState { TransferRequested, TransferStarted; diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index dbcc97a3739..b91fbdd69bf 100755 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -5,7 +5,7 @@ // 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, @@ -35,15 +35,15 @@ import com.cloud.template.TemplateManager; import com.cloud.vm.UserVmManager; public enum Config { - + // Alert - + AlertEmailAddresses("Alert", ManagementServer.class, String.class, "alert.email.addresses", null, "Comma separated list of email addresses used for sending alerts.", null), AlertEmailSender("Alert", ManagementServer.class, String.class, "alert.email.sender", null, "Sender of alert email (will be in the From header of the email).", null), AlertSMTPHost("Alert", ManagementServer.class, String.class, "alert.smtp.host", null, "SMTP hostname used for sending out email alerts.", null), AlertSMTPPassword("Secure", ManagementServer.class, String.class, "alert.smtp.password", null, "Password for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertSMTPPort("Alert", ManagementServer.class, Integer.class, "alert.smtp.port", "465", "Port the SMTP server is listening on.", null), - AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), + AlertSMTPUseAuth("Alert", ManagementServer.class, String.class, "alert.smtp.useAuth", null, "If true, use SMTP authentication when sending emails.", null), AlertSMTPUsername("Alert", ManagementServer.class, String.class, "alert.smtp.username", null, "Username for SMTP authentication (applies only if alert.smtp.useAuth is true).", null), AlertWait("Alert", AgentManager.class, Integer.class, "alert.wait", null, "Seconds to wait before alerting on a disconnected agent", null), CapacityCheckPeriod("Alert", ManagementServer.class, Integer.class, "capacity.check.period", "300000", "The interval in milliseconds between capacity checks", null), @@ -62,9 +62,9 @@ public enum Config { CPUCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.cpu.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of cpu utilization above which allocators will disable using the cluster for low cpu available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null), MemoryCapacityDisableThreshold("Alert", ManagementServer.class, Float.class, "cluster.memory.allocated.capacity.disablethreshold", "0.85", "Percentage (as a value between 0 and 1) of memory utilization above which allocators will disable using the cluster for low memory available. Keep the corresponding notification threshold lower than this to be notified beforehand.", null), - + // Storage - + StorageOverprovisioningFactor("Storage", StoragePoolAllocator.class, String.class, "storage.overprovisioning.factor", "2", "Used for storage overprovisioning calculation; available storage will be (actualStorageSize * storage.overprovisioning.factor)", null), StorageStatsInterval("Storage", ManagementServer.class, String.class, "storage.stats.interval", "60000", "The interval (in milliseconds) when storage stats (per host) are retrieved from agents.", null), MaxVolumeSize("Storage", ManagementServer.class, Integer.class, "storage.max.volume.size", "2000", "The maximum size for a volume (in GB).", null), @@ -84,9 +84,9 @@ public enum Config { NetworkLBHaproxyStatsVisbility("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.visibility", "global", "Load Balancer(haproxy) stats visibilty, the value can be one of the following six parameters : global,guest-network,link-local,disabled,all,default", null), NetworkLBHaproxyStatsUri("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.uri","/admin?stats","Load Balancer(haproxy) uri.",null), NetworkLBHaproxyStatsAuth("Secure", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.auth","admin1:AdMiN123","Load Balancer(haproxy) authetication string in the format username:password",null), - NetworkLBHaproxyStatsPort("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.port","8081","Load Balancer(haproxy) stats port number.",null), + NetworkLBHaproxyStatsPort("Network", ManagementServer.class, String.class, "network.loadbalancer.haproxy.stats.port","8081","Load Balancer(haproxy) stats port number.",null), NetworkRouterRpFilter("Network", ManagementServer.class, Integer.class, "network.disable.rpfilter", "true", "disable rp_filter on Domain Router VM public interfaces.", null), - + GuestVlanBits("Network", ManagementServer.class, Integer.class, "guest.vlan.bits", "12", "The number of bits to reserve for the VLAN identifier in the guest subnet.", null), //MulticastThrottlingRate("Network", ManagementServer.class, Integer.class, "multicast.throttling.rate", "10", "Default multicast rate in megabits per second allowed.", null), NetworkThrottlingRate("Network", ManagementServer.class, Integer.class, "network.throttling.rate", "200", "Default data transfer rate in megabits per second allowed in network.", null), @@ -102,16 +102,18 @@ public enum Config { SecurityGroupWorkerThreads("Network", ManagementServer.class, Integer.class, "network.securitygroups.workers.pool.size", "50", "Number of worker threads processing the security group update work queue", null), SecurityGroupWorkGlobalLockTimeout("Network", ManagementServer.class, Integer.class, "network.securitygroups.work.lock.timeout", "300", "Lock wait timeout (seconds) while updating the security group work queue", null), SecurityGroupWorkPerAgentMaxQueueSize("Network", ManagementServer.class, Integer.class, "network.securitygroups.work.per.agent.queue.size", "100", "The number of outstanding security group work items that can be queued to a host. If exceeded, work items will get dropped to conserve memory. Security Group Sync will take care of ensuring that the host gets updated eventually", null), - + 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), - RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), + RemoteAccessVpnUserLimit("Network", AgentManager.class, String.class, "remote.access.vpn.user.limit", "8", "The maximum number of VPN users that can be created per account", null), Site2SiteVpnConnectionPerVpnGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.vpngateway.connection.limit", "4", "The maximum number of VPN connection per VPN gateway", null), Site2SiteVpnSubnetsPerCustomerGatewayLimit("Network", ManagementServer.class, Integer.class, "site2site.vpn.customergateway.subnets.limit", "10", "The maximum number of subnets per customer gateway", null), - + // Console Proxy ConsoleProxyCapacityStandby("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacity.standby", "10", "The minimal number of console proxy viewer sessions that system is able to serve immediately(standby capacity)", null), ConsoleProxyCapacityScanInterval("Console Proxy", AgentManager.class, String.class, "consoleproxy.capacityscan.interval", "30000", "The time interval(in millisecond) to scan whether or not system needs more console proxy to ensure minimal standby capacity", null), @@ -123,11 +125,11 @@ public enum Config { ConsoleProxySessionTimeout("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.session.timeout", "300000", "Timeout(in milliseconds) that console proxy tries to maintain a viewer session before it times out the session for no activity", null), ConsoleProxyDisableRpFilter("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.disable.rpfilter", "true", "disable rp_filter on console proxy VM public interface", null), ConsoleProxyLaunchMax("Console Proxy", AgentManager.class, Integer.class, "consoleproxy.launch.max", "10", "maximum number of console proxy instances per zone can be launched", null), - ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), + ConsoleProxyManagementState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "console proxy service management state", null), - ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), + ConsoleProxyManagementLastState("Console Proxy", AgentManager.class, String.class, "consoleproxy.management.state.last", com.cloud.consoleproxy.ConsoleProxyManagementState.Auto.toString(), "last console proxy service management state", null), - + // Snapshots SnapshotHourlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.hourly", "8", "Maximum hourly snapshots for a volume", null), SnapshotDailyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.daily", "8", "Maximum daily snapshots for a volume", null), @@ -135,14 +137,13 @@ public enum Config { SnapshotMonthlyMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.max.monthly", "8", "Maximum monthly snapshots for a volume", null), SnapshotPollInterval("Snapshots", SnapshotManager.class, Integer.class, "snapshot.poll.interval", "300", "The time interval in seconds when the management server polls for snapshots to be scheduled.", null), SnapshotDeltaMax("Snapshots", SnapshotManager.class, Integer.class, "snapshot.delta.max", "16", "max delta snapshots between two full snapshots.", null), - + // Advanced 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), + SwiftEnable("Advanced", ManagementServer.class, Boolean.class, "swift.enable", "false", "enable swift ", 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"), @@ -164,8 +165,9 @@ public enum Config { RouterCpuMHz("Advanced", NetworkManager.class, Integer.class, "router.cpu.mhz", String.valueOf(VpcVirtualNetworkApplianceManager.DEFAULT_ROUTER_CPU_MHZ), "Default CPU speed (MHz) for router VM.", null), RestartRetryInterval("Advanced", HighAvailabilityManager.class, Integer.class, "restart.retry.interval", "600", "Time (in seconds) between retries to restart a vm", null), RouterStatsInterval("Advanced", NetworkManager.class, Integer.class, "router.stats.interval", "300", "Interval (in seconds) to report router statistics.", null), - ExternalNetworkStatsInterval("Advanced", NetworkManager.class, Integer.class, "external.network.stats.interval", "300", "Interval (in seconds) to report external network statistics.", null), + ExternalNetworkStatsInterval("Advanced", NetworkManager.class, Integer.class, "external.network.stats.interval", "300", "Interval (in seconds) to report external network statistics.", null), RouterCheckInterval("Advanced", NetworkManager.class, Integer.class, "router.check.interval", "30", "Interval (in seconds) to report redundant router status.", null), + RouterCheckPoolSize("Advanced", NetworkManager.class, Integer.class, "router.check.poolsize", "10", "Numbers of threads using to check redundant router status.", null), RouterTemplateId("Advanced", NetworkManager.class, Long.class, "router.template.id", "1", "Default ID for template.", null), RouterExtraPublicNics("Advanced", NetworkManager.class, Integer.class, "router.extra.public.nics", "2", "specify extra public nics used for virtual router(up to 5)", "0-5"), StartRetry("Advanced", AgentManager.class, Integer.class, "start.retry", "10", "Number of times to retry create and start commands", null), @@ -195,23 +197,23 @@ public enum Config { MaxTemplateAndIsoSize("Advanced", ManagementServer.class, Long.class, "max.template.iso.size", "50", "The maximum size for a downloaded template or ISO (in GB).", null), SecStorageAllowedInternalDownloadSites("Advanced", ManagementServer.class, String.class, "secstorage.allowed.internal.sites", null, "Comma separated list of cidrs internal to the datacenter that can host template download servers, please note 0.0.0.0 is not a valid site", null), SecStorageEncryptCopy("Advanced", ManagementServer.class, Boolean.class, "secstorage.encrypt.copy", "false", "Use SSL method used to encrypt copy traffic between zones", "true,false"), - SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), + SecStorageSecureCopyCert("Advanced", ManagementServer.class, String.class, "secstorage.ssl.cert.domain", "realhostip.com", "SSL certificate used to encrypt copy traffic between zones", null), SecStorageCapacityStandby("Advanced", AgentManager.class, Integer.class, "secstorage.capacity.standby", "10", "The minimal number of command execution sessions that system is able to serve immediately(standby capacity)", null), SecStorageSessionMax("Advanced", AgentManager.class, Integer.class, "secstorage.session.max", "50", "The max number of command execution sessions that a SSVM can handle", null), SecStorageCmdExecutionTimeMax("Advanced", AgentManager.class, Integer.class, "secstorage.cmd.execution.time.max", "30", "The max command execution time in minute", null), SecStorageProxy("Advanced", AgentManager.class, String.class, "secstorage.proxy", null, "http proxy used by ssvm, in http://username:password@proxyserver:port format", null), - + DirectAttachNetworkEnabled("Advanced", ManagementServer.class, Boolean.class, "direct.attach.network.externalIpAllocator.enabled", "false", "Direct-attach VMs using external DHCP server", "true,false"), DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null), CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"), NetworkGcWait("Advanced", ManagementServer.class, Integer.class, "network.gc.wait", "600", "Time (in seconds) to wait before shutting down a network that's not in used", null), - NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), + NetworkGcInterval("Advanced", ManagementServer.class, Integer.class, "network.gc.interval", "600", "Seconds to wait before checking for networks to shutdown", null), CapacitySkipcountingHours("Advanced", ManagementServer.class, Integer.class, "capacity.skipcounting.hours", "3600", "Time (in seconds) to wait before release VM's cpu and memory when VM in stopped state", null), VmStatsInterval("Advanced", ManagementServer.class, Integer.class, "vm.stats.interval", "60000", "The interval (in milliseconds) when vm stats are retrieved from agents.", null), VmTransitionWaitInterval("Advanced", ManagementServer.class, Integer.class, "vm.tranisition.wait.interval", "3600", "Time (in seconds) to wait before taking over a VM in transition state", null), VmDestroyForcestop("Advanced", ManagementServer.class, Boolean.class, "vm.destroy.forcestop", "false", "On destroy, force-stop takes this value ", null), - + ControlCidr("Advanced", ManagementServer.class, String.class, "control.cidr", "169.254.0.0/16", "Changes the cidr for the control network traffic. Defaults to using link local. Must be unique within pods", null), ControlGateway("Advanced", ManagementServer.class, String.class, "control.gateway", "169.254.0.1", "gateway for the control network traffic", null), HostCapacityTypeToOrderClusters("Advanced", ManagementServer.class, String.class, "host.capacityType.to.order.clusters", "CPU", "The host capacity type (CPU or RAM) is used by deployment planner to order clusters during VM resource allocation", "CPU,RAM"), @@ -234,7 +236,7 @@ public enum Config { OvmPublicNetwork("Hidden", ManagementServer.class, String.class, "ovm.public.network.device", null, "Specify the public bridge on host for public network", null), OvmPrivateNetwork("Hidden", ManagementServer.class, String.class, "ovm.private.network.device", null, "Specify the private bridge on host for private network", null), OvmGuestNetwork("Hidden", ManagementServer.class, String.class, "ovm.guest.network.device", null, "Specify the private bridge on host for private network", null), - + // XenServer XenPublicNetwork("Hidden", ManagementServer.class, String.class, "xen.public.network.device", null, "[ONLY IF THE PUBLIC NETWORK IS ON A DEDICATED NIC]:The network name label of the physical device dedicated to the public network on a XenServer host", null), XenStorageNetwork1("Hidden", ManagementServer.class, String.class, "xen.storage.network.device1", null, "Specify when there are storage networks", null), @@ -245,7 +247,7 @@ public enum Config { XenBondStorageNic("Advanced", ManagementServer.class, String.class, "xen.bond.storage.nics", null, "Attempt to bond the two networks if found", null), XenHeartBeatInterval("Advanced", ManagementServer.class, Integer.class, "xen.heartbeat.interval", "60", "heartbeat to use when implementing XenServer Self Fencing", null), XenGuestNetwork("Hidden", ManagementServer.class, String.class, "xen.guest.network.device", null, "Specify for guest network name label", null), - + // VMware VmwarePrivateNetworkVSwitch("Hidden", ManagementServer.class, String.class, "vmware.private.vswitch", null, "Specify the vSwitch on host for private network", null), VmwarePublicNetworkVSwitch("Hidden", ManagementServer.class, String.class, "vmware.public.vswitch", null, "Specify the vSwitch on host for public network", null), @@ -262,7 +264,7 @@ public enum Config { VmwareRootDiskControllerType("Advanced", ManagementServer.class, String.class, "vmware.root.disk.controller", "ide", "Specify the default disk controller for root volumes, valid values are scsi, ide", null), VmwareSystemVmNicDeviceType("Advanced", ManagementServer.class, String.class, "vmware.systemvm.nic.device.type", "E1000", "Specify the default network device type for system VMs, valid values are E1000, PCNet32, Vmxnet2, Vmxnet3", null), VmwareRecycleHungWorker("Advanced", ManagementServer.class, Boolean.class, "vmware.recycle.hung.wokervm", "false", "Specify whether or not to recycle hung worker VMs", null), - + // KVM KvmPublicNetwork("Hidden", ManagementServer.class, String.class, "kvm.public.network.device", null, "Specify the public bridge on host for public network", null), KvmPrivateNetwork("Hidden", ManagementServer.class, String.class, "kvm.private.network.device", null, "Specify the private bridge on host for private network", null), @@ -275,7 +277,9 @@ 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), CreatePoolsInPod("Hidden", ManagementServer.class, Boolean.class, "xen.create.pools.in.pod", "false", "Should we automatically add XenServers into pools that are inside a Pod", null), @@ -291,11 +295,12 @@ public enum Config { VmOpCleanupInterval("Advanced", ManagementServer.class, Long.class, "vm.op.cleanup.interval", "86400", "Interval to run the thread that cleans up the vm operations (in seconds)", "Seconds"), 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"), - + // Account Default Limits DefaultMaxAccountUserVms("Account Defaults", ManagementServer.class, Long.class, "max.account.user.vms", "20", "The default maximum number of user VMs that can be deployed for an account", null), DefaultMaxAccountPublicIPs("Account Defaults", ManagementServer.class, Long.class, "max.account.public.ips", "20", "The default maximum number of public IPs that can be consumed by an account", null), @@ -305,10 +310,10 @@ public enum Config { DefaultMaxAccountNetworks("Account Defaults", ManagementServer.class, Long.class, "max.account.networks", "20", "The default maximum number of networks that can be created for an account", null), DefaultMaxAccountVpcs("Account Defaults", ManagementServer.class, Long.class, "max.account.vpcs", "20", "The default maximum number of vpcs that can be created for an account", null), - + ResourceCountCheckInterval("Advanced", ManagementServer.class, Long.class, "resourcecount.check.interval", "0", "Time (in seconds) to wait before retrying resource count check task. Default is 0 which is to never run the task", "Seconds"), DirectAgentLoadSize("Advanced", ManagementServer.class, Integer.class, "direct.agent.load.size", "16", "The number of direct agents to load each time", null), - + //disabling lb as cluster sync does not work with distributed cluster AgentLbEnable("Advanced", ManagementServer.class, Boolean.class, "agent.lb.enabled", "false", "If agent load balancing enabled in cluster setup", null), SubDomainNetworkAccess("Advanced", NetworkManager.class, Boolean.class, "allow.subdomain.network.access", "true", "Allow subdomains to use networks dedicated to their parent domain(s)", null), @@ -318,9 +323,9 @@ public enum Config { ClusterMessageTimeOutSeconds("Advanced", ManagementServer.class, Integer.class, "cluster.message.timeout.seconds", "300", "Time (in seconds) to wait before a inter-management server message post times out.", null), AgentLoadThreshold("Advanced", ManagementServer.class, Float.class, "agent.load.threshold", "0.7", "Percentage (as a value between 0 and 1) of connected agents after which agent load balancing will start happening", null), - + JavaScriptDefaultContentType("Advanced", ManagementServer.class, String.class, "json.content.type", "text/javascript", "Http response content type for .js files (default is text/javascript)", null), - + DefaultMaxProjectUserVms("Project Defaults", ManagementServer.class, Long.class, "max.project.user.vms", "20", "The default maximum number of user VMs that can be deployed for a project", null), DefaultMaxProjectPublicIPs("Project Defaults", ManagementServer.class, Long.class, "max.project.public.ips", "20", "The default maximum number of public IPs that can be consumed by a project", null), DefaultMaxProjectTemplates("Project Defaults", ManagementServer.class, Long.class, "max.project.templates", "20", "The default maximum number of templates that can be deployed for a project", null), @@ -328,11 +333,11 @@ public enum Config { DefaultMaxProjectVolumes("Project Defaults", ManagementServer.class, Long.class, "max.project.volumes", "20", "The default maximum number of volumes that can be created for a project", null), DefaultMaxProjectNetworks("Project Defaults", ManagementServer.class, Long.class, "max.project.networks", "20", "The default maximum number of networks that can be created for a project", null), DefaultMaxProjectVpcs("Project Defaults", ManagementServer.class, Long.class, "max.project.vpcs", "20", "The default maximum number of vpcs that can be created for a project", null), - + ProjectInviteRequired("Project Defaults", ManagementServer.class, Boolean.class, "project.invite.required", "false", "If invitation confirmation is required when add account to project. Default value is false", null), ProjectInvitationExpirationTime("Project Defaults", ManagementServer.class, Long.class, "project.invite.timeout", "86400", "Invitation expiration time (in seconds). Default is 1 day - 86400 seconds", null), AllowUserToCreateProject("Project Defaults", ManagementServer.class, Long.class, "allow.user.create.projects", "true", "If regular user can create a project; true by default", null), - + ProjectEmailSender("Project Defaults", ManagementServer.class, String.class, "project.email.sender", null, "Sender of project invitation email (will be in the From header of the email)", null), ProjectSMTPHost("Project Defaults", ManagementServer.class, String.class, "project.smtp.host", null, "SMTP hostname used for sending out email project invitations", null), ProjectSMTPPassword("Secure", ManagementServer.class, String.class, "project.smtp.password", null, "Password for SMTP authentication (applies only if project.smtp.useAuth is true)", null), @@ -349,9 +354,13 @@ public enum Config { SecondaryStorageServiceOffering("Advanced", ManagementServer.class, Long.class, "secstorage.service.offering", null, "Service offering used by secondary storage; if NULL - system offering will be used", null), HaTag("Advanced", ManagementServer.class, String.class, "ha.tag", null, "HA tag defining that the host marked with this tag can be used for HA purposes only", null), VpcCleanupInterval("Advanced", ManagementServer.class, Integer.class, "vpc.cleanup.interval", "3600", "The interval (in seconds) between cleanup for Inactive VPCs", null), - VpcMaxNetworks("Advanced", ManagementServer.class, Integer.class, "vpc.max.networks", "3", "Maximum number of networks per vpc", null); - - + VpcMaxNetworks("Advanced", ManagementServer.class, Integer.class, "vpc.max.networks", "3", "Maximum number of networks per vpc", null), + DetailBatchQuerySize("Advanced", ManagementServer.class, Integer.class, "detail.batch.query.size", "2000", "Default entity detail batch query size for listing", null), + + ConcurrentSnapshotsThresholdPerHost("Advanced", ManagementServer.class, Long.class, "concurrent.snapshots.threshold.perhost", + null, "Limits number of snapshots that can be handled by the host concurrently; default is NULL - unlimited", null); + + private final String _category; private final Class _componentClass; private final Class _type; @@ -376,7 +385,7 @@ public enum Config { _configs.put("Account Defaults", new ArrayList()); _configs.put("Project Defaults", new ArrayList()); _configs.put("Secure", new ArrayList()); - + // Add values into HashMap for (Config c : Config.values()) { String category = c.getCategory(); @@ -385,7 +394,7 @@ public enum Config { _configs.put(category, currentConfigs); } } - + private Config(String category, Class componentClass, Class type, String name, String defaultValue, String description, String range) { _category = category; _componentClass = componentClass; @@ -395,15 +404,15 @@ public enum Config { _description = description; _range = range; } - + public String getCategory() { return _category; } - + public String key() { return _name; } - + public String getDescription() { return _description; } @@ -419,7 +428,7 @@ public enum Config { public Class getComponentClass() { return _componentClass; } - + public String getComponent() { if (_componentClass == ManagementServer.class) { return "management-server"; @@ -445,16 +454,16 @@ public enum Config { public String getRange() { return _range; } - + @Override public String toString() { return _name; } - + public static List getConfigs(String category) { return _configs.get(category); } - + public static Config getConfig(String name) { List categories = getCategories(); for (String category : categories) { @@ -465,10 +474,10 @@ public enum Config { } } } - + return null; } - + public static List getCategories() { Object[] keys = _configs.keySet().toArray(); List categories = new ArrayList(); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 0a6aaa8e02f..bb943c96600 100755 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -39,33 +39,31 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateDiskOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker; +import org.apache.cloudstack.acl.SecurityChecker; import com.cloud.alert.AlertManager; -import com.cloud.api.ApiConstants.LDAPParams; +import org.apache.cloudstack.api.ApiConstants.LDAPParams; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; import com.cloud.capacity.dao.CapacityDao; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -140,7 +138,9 @@ 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; @@ -188,6 +188,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Inject SwiftDao _swiftDao; @Inject + S3Dao _s3Dao; + @Inject ServiceOfferingDao _serviceOfferingDao; @Inject DiskOfferingDao _diskOfferingDao; @@ -230,6 +232,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura @Inject SwiftManager _swiftMgr; @Inject + S3Manager _s3Mgr; + @Inject PhysicalNetworkTrafficTypeDao _trafficTypeDao; @Inject NicDao _nicDao; @@ -491,6 +495,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; } @@ -1592,6 +1604,7 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura createDefaultSystemNetworks(zone.getId()); _swiftMgr.propagateSwiftTmplteOnZone(zone.getId()); + _s3Mgr.propagateTemplatesToZone(zone); txn.commit(); return zone; } catch (Exception ex) { @@ -3088,8 +3101,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura void validateLoadBalancerServiceCapabilities(Map lbServiceCapabilityMap) { if (lbServiceCapabilityMap != null && !lbServiceCapabilityMap.isEmpty()) { - if (lbServiceCapabilityMap.keySet().size() > 2 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + if (lbServiceCapabilityMap.keySet().size() > 3 || !lbServiceCapabilityMap.containsKey(Capability.SupportedLBIsolation)) { + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); } for (Capability cap : lbServiceCapabilityMap.keySet()) { @@ -3106,8 +3119,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (!enabled && !disabled) { throw new InvalidParameterValueException("Unknown specified value for " + Capability.ElasticLb.getName()); } + } else if (cap == Capability.InlineMode) { + boolean enabled = value.contains("true"); + boolean disabled = value.contains("false"); + if (!enabled && !disabled) { + throw new InvalidParameterValueException("Unknown specified value for " + Capability.InlineMode.getName()); + } } else { - throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + " and " + Capability.ElasticLb + " capabilities can be sepcified for LB service"); + throw new InvalidParameterValueException("Only " + Capability.SupportedLBIsolation.getName() + ", " + Capability.ElasticLb.getName() + ", " + Capability.InlineMode.getName() + " capabilities can be sepcified for LB service"); } } } @@ -3142,20 +3161,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"); } } } @@ -3209,6 +3241,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura boolean sharedSourceNat = false; boolean redundantRouter = false; boolean elasticIp = false; + boolean associatePublicIp = false; + boolean inline = false; if (serviceCapabilityMap != null && !serviceCapabilityMap.isEmpty()) { Map lbServiceCapabilityMap = serviceCapabilityMap.get(Service.Lb); @@ -3225,6 +3259,14 @@ public class ConfigurationManagerImpl implements ConfigurationManager, Configura if (param != null) { elasticLb = param.contains("true"); } + + String inlineMode = lbServiceCapabilityMap.get(Capability.InlineMode); + if (inlineMode != null) { + _networkMgr.checkCapabilityForProvider(serviceProviderMap.get(Service.Lb), Service.Lb, Capability.InlineMode, inlineMode); + inline = inlineMode.contains("true"); + } else { + inline = false; + } } Map sourceNatServiceCapabilityMap = serviceCapabilityMap.get(Service.SourceNat); @@ -3249,13 +3291,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, inline); 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 e5482d2b20d..79bd7985a68 100755 --- a/server/src/com/cloud/configuration/DefaultComponentLibrary.java +++ b/server/src/com/cloud/configuration/DefaultComponentLibrary.java @@ -24,6 +24,20 @@ import java.util.Map; import com.cloud.agent.manager.ClusteredAgentManagerImpl; import com.cloud.alert.AlertManagerImpl; import com.cloud.alert.dao.AlertDaoImpl; +import com.cloud.api.query.QueryManagerImpl; +import com.cloud.api.query.dao.AccountJoinDaoImpl; +import com.cloud.api.query.dao.AsyncJobJoinDaoImpl; +import com.cloud.api.query.dao.DomainRouterJoinDaoImpl; +import com.cloud.api.query.dao.InstanceGroupJoinDaoImpl; +import com.cloud.api.query.dao.ProjectAccountJoinDaoImpl; +import com.cloud.api.query.dao.ProjectInvitationJoinDaoImpl; +import com.cloud.api.query.dao.ProjectJoinDaoImpl; +import com.cloud.api.query.dao.ResourceTagJoinDaoImpl; +import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; +import com.cloud.api.query.dao.UserAccountJoinDaoImpl; +import com.cloud.api.query.dao.UserVmJoinDaoImpl; +import com.cloud.api.query.dao.HostJoinDaoImpl; +import com.cloud.api.query.dao.VolumeJoinDaoImpl; import com.cloud.async.AsyncJobExecutorContextImpl; import com.cloud.async.AsyncJobManagerImpl; import com.cloud.async.SyncQueueManagerImpl; @@ -75,6 +89,14 @@ import com.cloud.maint.dao.AgentUpgradeDaoImpl; import com.cloud.network.ExternalLoadBalancerUsageManagerImpl; import com.cloud.network.NetworkManagerImpl; import com.cloud.network.StorageNetworkManagerImpl; +import com.cloud.network.as.AutoScaleManagerImpl; +import com.cloud.network.as.dao.AutoScalePolicyConditionMapDaoImpl; +import com.cloud.network.as.dao.AutoScalePolicyDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmGroupDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDaoImpl; +import com.cloud.network.as.dao.AutoScaleVmProfileDaoImpl; +import com.cloud.network.as.dao.ConditionDaoImpl; +import com.cloud.network.as.dao.CounterDaoImpl; import com.cloud.network.dao.ExternalFirewallDeviceDaoImpl; import com.cloud.network.dao.ExternalLoadBalancerDeviceDaoImpl; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; @@ -139,6 +161,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; @@ -151,11 +174,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; @@ -197,6 +222,8 @@ import com.cloud.vm.dao.SecondaryStorageVmDaoImpl; import com.cloud.vm.dao.UserVmDaoImpl; import com.cloud.vm.dao.UserVmDetailsDaoImpl; import com.cloud.vm.dao.VMInstanceDaoImpl; +import com.cloud.event.dao.EventJoinDaoImpl; + public class DefaultComponentLibrary extends ComponentLibraryBase implements ComponentLibrary { @@ -238,6 +265,13 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("NetworkRuleConfigDao", NetworkRuleConfigDaoImpl.class); addDao("LoadBalancerVMMapDao", LoadBalancerVMMapDaoImpl.class); addDao("LBStickinessPolicyDao", LBStickinessPolicyDaoImpl.class); + addDao("CounterDao", CounterDaoImpl.class); + addDao("ConditionDao", ConditionDaoImpl.class); + addDao("AutoScalePolicyDao", AutoScalePolicyDaoImpl.class); + addDao("AutoScalePolicyConditionMapDao", AutoScalePolicyConditionMapDaoImpl.class); + addDao("AutoScaleVmProfileDao", AutoScaleVmProfileDaoImpl.class); + addDao("AutoScaleVmGroupDao", AutoScaleVmGroupDaoImpl.class); + addDao("AutoScaleVmGroupPolicyMapDao", AutoScaleVmGroupPolicyMapDaoImpl.class); addDao("DataCenterIpAddressDao", DataCenterIpAddressDaoImpl.class); addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); addDao("SecurityGroupRuleDao", SecurityGroupRuleDaoImpl.class); @@ -255,6 +289,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); @@ -286,6 +321,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("NetworkOfferingDao", NetworkOfferingDaoImpl.class); addDao("NicDao", NicDaoImpl.class); addDao("InstanceGroupDao", InstanceGroupDaoImpl.class); + addDao("InstanceGroupJoinDao", InstanceGroupJoinDaoImpl.class); addDao("InstanceGroupVMMapDao", InstanceGroupVMMapDaoImpl.class); addDao("RemoteAccessVpnDao", RemoteAccessVpnDaoImpl.class); addDao("VpnUserDao", VpnUserDaoImpl.class); @@ -303,6 +339,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); @@ -337,6 +374,20 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addDao("Site2SiteVpnGatewayDao", Site2SiteVpnGatewayDaoImpl.class); addDao("Site2SiteCustomerGatewayDao", Site2SiteCustomerGatewayDaoImpl.class); addDao("Site2SiteVpnConnnectionDao", Site2SiteVpnConnectionDaoImpl.class); + + addDao("UserVmJoinDao", UserVmJoinDaoImpl.class); + addDao("DomainRouterJoinDao", DomainRouterJoinDaoImpl.class); + addDao("SecurityGroupJoinDao", SecurityGroupJoinDaoImpl.class); + addDao("ResourceTagJoinDao", ResourceTagJoinDaoImpl.class); + addDao("EventJoinDao", EventJoinDaoImpl.class); + addDao("UserAccountJoinDao", UserAccountJoinDaoImpl.class); + addDao("ProjectJoinDao", ProjectJoinDaoImpl.class); + addDao("ProjectAccountJoinDao", ProjectAccountJoinDaoImpl.class); + addDao("ProjectInvitationJoinDao", ProjectInvitationJoinDaoImpl.class); + addDao("HostJoinDao", HostJoinDaoImpl.class); + addDao("VolumeJoinDao", VolumeJoinDaoImpl.class); + addDao("AccountJoinDao", AccountJoinDaoImpl.class); + addDao("AsyncJobJoinDao", AsyncJobJoinDaoImpl.class); } @Override @@ -344,6 +395,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com if (_daos.size() == 0) { populateDaos(); } + //FIXME: Incorrect method return definition return _daos; } @@ -374,6 +426,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addManager("SecurityGroupManager", SecurityGroupManagerImpl2.class); addManager("EntityManager", EntityManagerImpl.class); addManager("LoadBalancingRulesManager", LoadBalancingRulesManagerImpl.class); + addManager("AutoScaleManager", AutoScaleManagerImpl.class); addManager("RulesManager", RulesManagerImpl.class); addManager("RemoteAccessVpnManager", RemoteAccessVpnManagerImpl.class); addManager("Capacity Manager", CapacityManagerImpl.class); @@ -387,6 +440,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); @@ -395,6 +449,7 @@ public class DefaultComponentLibrary extends ComponentLibraryBase implements Com addManager("NetworkACLManager", NetworkACLManagerImpl.class); addManager("TaggedResourcesManager", TaggedResourceManagerImpl.class); addManager("Site2SiteVpnManager", Site2SiteVpnManagerImpl.class); + addManager("QueryManager", QueryManagerImpl.class); } @Override diff --git a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java index ccfb3537d9e..63b3da84318 100755 --- a/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java +++ b/server/src/com/cloud/consoleproxy/ConsoleProxyManagerImpl.java @@ -55,7 +55,7 @@ import com.cloud.agent.api.proxy.StartConsoleProxyAgentHttpHandlerCommand; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.ServerApiException; +import org.apache.cloudstack.api.ServerApiException; import com.cloud.api.commands.DestroyConsoleProxyCmd; import com.cloud.certificate.dao.CertificateDao; import com.cloud.cluster.ClusterManager; diff --git a/server/src/com/cloud/dao/EntityManagerImpl.java b/server/src/com/cloud/dao/EntityManagerImpl.java index 13cf73ef0f1..3c335beb28e 100644 --- a/server/src/com/cloud/dao/EntityManagerImpl.java +++ b/server/src/com/cloud/dao/EntityManagerImpl.java @@ -49,7 +49,14 @@ public class EntityManagerImpl implements EntityManager, Manager { } @Override - public T findByXid(Class entityType, String xid) { + public T findByUuid(Class entityType, String uuid) { + // Finds and returns a unique VO using uuid, null if entity not found in db + GenericDao dao = (GenericDao)GenericDaoBase.getDao(entityType); + return dao.findByUuid(uuid); + } + + @Override + public T findByXId(Class entityType, String xid) { return null; } diff --git a/server/src/com/cloud/dc/AccountVlanMapVO.java b/server/src/com/cloud/dc/AccountVlanMapVO.java index f8cb9000332..b1bf919df09 100644 --- a/server/src/com/cloud/dc/AccountVlanMapVO.java +++ b/server/src/com/cloud/dc/AccountVlanMapVO.java @@ -24,15 +24,16 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_vlan_map") -public class AccountVlanMapVO implements OwnedBy { +public class AccountVlanMapVO implements OwnedBy, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") - private Long id; + private long id; @Column(name="account_id") private long accountId; @@ -49,7 +50,7 @@ public class AccountVlanMapVO implements OwnedBy { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/ClusterDetailsVO.java b/server/src/com/cloud/dc/ClusterDetailsVO.java index 972d50ecc0e..11a55258f23 100644 --- a/server/src/com/cloud/dc/ClusterDetailsVO.java +++ b/server/src/com/cloud/dc/ClusterDetailsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="cluster_details") -public class ClusterDetailsVO { +public class ClusterDetailsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/ClusterVO.java b/server/src/com/cloud/dc/ClusterVO.java index c2368016db7..4195b74f87f 100644 --- a/server/src/com/cloud/dc/ClusterVO.java +++ b/server/src/com/cloud/dc/ClusterVO.java @@ -28,63 +28,64 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.org.Cluster; import com.cloud.org.Managed.ManagedState; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="cluster") -public class ClusterVO implements Cluster, Identity { +public class ClusterVO implements Cluster { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="name") String name; - + @Column(name="guid") String guid; - + @Column(name="data_center_id") long dataCenterId; - + @Column(name="pod_id") long podId; - + @Column(name="hypervisor_type") String hypervisorType; @Column(name="cluster_type") @Enumerated(value=EnumType.STRING) Cluster.ClusterType clusterType; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; - + @Column(name="managed_state") @Enumerated(value=EnumType.STRING) ManagedState managedState; - + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @Column(name="uuid") String uuid; - + public ClusterVO() { clusterType = Cluster.ClusterType.CloudManaged; allocationState = Grouping.AllocationState.Enabled; - + this.uuid = UUID.randomUUID().toString(); } - + public ClusterVO(long dataCenterId, long podId, String name) { this.dataCenterId = dataCenterId; this.podId = podId; @@ -110,23 +111,23 @@ public class ClusterVO implements Cluster, Identity { public long getPodId() { return podId; } - + public Cluster.ClusterType getClusterType() { return clusterType; } - + public void setClusterType(Cluster.ClusterType clusterType) { this.clusterType = clusterType; } - + public AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + public ManagedState getManagedState() { return managedState; } @@ -143,7 +144,7 @@ public class ClusterVO implements Cluster, Identity { public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof ClusterVO)) { @@ -152,7 +153,7 @@ public class ClusterVO implements Cluster, Identity { ClusterVO that = (ClusterVO)obj; return this.id == that.id; } - + public HypervisorType getHypervisorType() { return HypervisorType.getType(hypervisorType); } @@ -160,11 +161,11 @@ public class ClusterVO implements Cluster, Identity { public void setHypervisorType(String hy) { hypervisorType = hy; } - + public String getGuid() { return guid; } - + public void setGuid(String guid) { this.guid = guid; } @@ -176,12 +177,12 @@ public class ClusterVO implements Cluster, Identity { public void setName(String name) { this.name = name; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/dc/DataCenterIpAddressVO.java b/server/src/com/cloud/dc/DataCenterIpAddressVO.java index 4c407ba1d04..d92227fd6f6 100755 --- a/server/src/com/cloud/dc/DataCenterIpAddressVO.java +++ b/server/src/com/cloud/dc/DataCenterIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_ip_address_alloc") -public class DataCenterIpAddressVO { +public class DataCenterIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -75,7 +77,7 @@ public class DataCenterIpAddressVO { this.podId = podId; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java b/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java index feab6d4f578..ffa754954bc 100644 --- a/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java +++ b/server/src/com/cloud/dc/DataCenterLinkLocalIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_link_local_ip_address_alloc") -public class DataCenterLinkLocalIpAddressVO { +public class DataCenterLinkLocalIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -64,7 +66,7 @@ public class DataCenterLinkLocalIpAddressVO { this.podId = podId; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/DataCenterVO.java b/server/src/com/cloud/dc/DataCenterVO.java index 7b5280cc2d3..28fb11f8cc0 100644 --- a/server/src/com/cloud/dc/DataCenterVO.java +++ b/server/src/com/cloud/dc/DataCenterVO.java @@ -5,7 +5,7 @@ // 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, @@ -31,99 +31,100 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.Network.Provider; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="data_center") -public class DataCenterVO implements DataCenter, Identity { - +public class DataCenterVO implements DataCenter { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - + @Column(name="name") private String name = null; - + @Column(name="description") private String description = null; - + @Column(name="dns1") private String dns1 = null; - + @Column(name="dns2") private String dns2 = null; - + @Column(name="internal_dns1") private String internalDns1 = null; - + @Column(name="internal_dns2") private String internalDns2 = null; - + @Column(name="router_mac_address", updatable = false, nullable=false) private String routerMacAddress = "02:00:00:00:00:01"; - + @Column(name="guest_network_cidr") private String guestNetworkCidr = null; - + @Column(name="domain_id") private Long domainId = null; @Column(name="domain") private String domain; - + @Column(name="networktype") - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.STRING) NetworkType networkType; - + @Column(name="dns_provider") private String dnsProvider; - + @Column(name="dhcp_provider") private String dhcpProvider; - + @Column(name="gateway_provider") private String gatewayProvider; - + @Column(name="vpn_provider") private String vpnProvider; - + @Column(name="userdata_provider") private String userDataProvider; - + @Column(name="lb_provider") private String loadBalancerProvider; - + @Column(name="firewall_provider") private String firewallProvider; - + @Column(name="mac_address", nullable=false) @TableGenerator(name="mac_address_sq", table="data_center", pkColumnName="id", valueColumnName="mac_address", allocationSize=1) private long macAddress = 1; - + @Column(name="zone_token") - private String zoneToken; - + private String zoneToken; + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; - + // This is a delayed load value. If the value is null, // then this field has not been loaded yet. // Call the dao to load it. @Transient Map details; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; @Column(name="uuid") - private String uuid; - + private String uuid; + @Column(name="is_security_group_enabled") boolean securityGroupEnabled; @@ -168,13 +169,13 @@ public class DataCenterVO implements DataCenter, Identity { @Override public String getFirewallProvider() { - return firewallProvider; + return firewallProvider; } public void setFirewallProvider(String firewallProvider) { this.firewallProvider = firewallProvider; } - + public DataCenterVO(long id, String name, String description, String dns1, String dns2, String dns3, String dns4, String guestCidr, String domain, Long domainId, NetworkType zoneType, String zoneToken, String domainSuffix) { this(name, description, dns1, dns2, dns3, dns4, guestCidr, domain, domainId, zoneType, zoneToken, domainSuffix, false, false); this.id = id; @@ -216,7 +217,7 @@ public class DataCenterVO implements DataCenter, Identity { this.domain = domainSuffix; this.uuid = UUID.randomUUID().toString(); } - + @Override public String getVpnProvider() { return vpnProvider; @@ -234,13 +235,13 @@ public class DataCenterVO implements DataCenter, Identity { public void setUserDataProvider(String userDataProvider) { this.userDataProvider = userDataProvider; } - + @Override public String getGuestNetworkCidr() { return guestNetworkCidr; } - + public void setGuestNetworkCidr(String guestNetworkCidr) { this.guestNetworkCidr = guestNetworkCidr; @@ -254,7 +255,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomainId(Long domainId) { this.domainId = domainId; } - + @Override public String getDescription() { return description; @@ -263,12 +264,12 @@ public class DataCenterVO implements DataCenter, Identity { public String getRouterMacAddress() { return routerMacAddress; } - + @Override public String getDns1() { return dns1; } - + @Override public String getDns2() { return dns2; @@ -291,28 +292,28 @@ public class DataCenterVO implements DataCenter, Identity { public long getId() { return id; } - + @Override public String getName() { return name; } - + public void setName(String name) { this.name = name; } - + public void setDns1(String dns1) { this.dns1 = dns1; } - + public void setDns2(String dns2) { this.dns2 = dns2; } - + public void setInternalDns1(String dns3) { this.internalDns1 = dns3; } - + public void setInternalDns2(String dns4) { this.internalDns2 = dns4; } @@ -320,7 +321,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setRouterMacAddress(String routerMacAddress) { this.routerMacAddress = routerMacAddress; } - + @Override public String getDomain() { return domain; @@ -329,7 +330,7 @@ public class DataCenterVO implements DataCenter, Identity { public void setDomain(String domain) { this.domain = domain; } - + public void setNetworkType(NetworkType zoneNetworkType) { this.networkType = zoneNetworkType; } @@ -338,12 +339,12 @@ public class DataCenterVO implements DataCenter, Identity { public NetworkType getNetworkType() { return networkType; } - - @Override + + @Override public boolean isSecurityGroupEnabled() { return securityGroupEnabled; } - + public void setSecurityGroupEnabled(boolean enabled) { this.securityGroupEnabled = enabled; } @@ -364,34 +365,34 @@ public class DataCenterVO implements DataCenter, Identity { @Override public void setDetails(Map details2) { - details = details2; + details = details2; } - + public String getDetail(String name) { assert (details != null) : "Did you forget to load the details?"; - + return details != null ? details.get(name) : null; } - + public void setDetail(String name, String value) { assert (details != null) : "Did you forget to load the details?"; - + details.put(name, value); } - + public AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + @Override public int hashCode() { return NumbersUtil.hash(id); } - + @Override public boolean equals(Object obj) { if (!(obj instanceof DataCenterVO)) { @@ -405,20 +406,20 @@ public class DataCenterVO implements DataCenter, Identity { public String getZoneToken() { return zoneToken; } - + public void setZoneToken(String zoneToken) { this.zoneToken = zoneToken; } - + public Date getRemoved() { return removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -430,4 +431,4 @@ public class DataCenterVO implements DataCenter, Identity { public void setMacAddress(long macAddress) { this.macAddress = macAddress; } -} +} diff --git a/server/src/com/cloud/dc/DataCenterVnetVO.java b/server/src/com/cloud/dc/DataCenterVnetVO.java index af6f4788a70..52d7ad2067b 100755 --- a/server/src/com/cloud/dc/DataCenterVnetVO.java +++ b/server/src/com/cloud/dc/DataCenterVnetVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_vnet_alloc") -public class DataCenterVnetVO { +public class DataCenterVnetVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/DcDetailVO.java b/server/src/com/cloud/dc/DcDetailVO.java index 49838637dec..15bfacbb3e1 100644 --- a/server/src/com/cloud/dc/DcDetailVO.java +++ b/server/src/com/cloud/dc/DcDetailVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="data_center_details") -public class DcDetailVO { +public class DcDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/dc/HostPodVO.java b/server/src/com/cloud/dc/HostPodVO.java index 549e27eda3f..e4ba9d0c111 100644 --- a/server/src/com/cloud/dc/HostPodVO.java +++ b/server/src/com/cloud/dc/HostPodVO.java @@ -28,14 +28,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.org.Grouping; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "host_pod_ref") -public class HostPodVO implements Pod, Identity { +public class HostPodVO implements Pod { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) long id; @@ -45,7 +46,7 @@ public class HostPodVO implements Pod, Identity { @Column(name = "data_center_id") private long dataCenterId; - + @Column(name = "gateway") private String gateway; @@ -57,14 +58,14 @@ public class HostPodVO implements Pod, Identity { @Column(name = "description") private String description; - + @Column(name="allocation_state") @Enumerated(value=EnumType.STRING) AllocationState allocationState; @Column(name = "external_dhcp") private Boolean externalDhcp; - + @Column(name=GenericDao.REMOVED_COLUMN) private Date removed; @@ -128,12 +129,12 @@ public class HostPodVO implements Pod, Identity { public void setCidrSize(int cidrSize) { this.cidrSize = cidrSize; } - + @Override public String getGateway() { return gateway; } - + public void setGateway(String gateway) { this.gateway = gateway; } @@ -145,33 +146,33 @@ public class HostPodVO implements Pod, Identity { public void setDescription(String description) { this.description = description; } - + public AllocationState getAllocationState() { return allocationState; } - + public void setAllocationState(AllocationState allocationState) { this.allocationState = allocationState; } - + // Use for comparisons only. public HostPodVO(Long id) { this.id = id; } - + @Override public int hashCode() { return NumbersUtil.hash(id); } - + public boolean getExternalDhcp() { return externalDhcp; } - + public void setExternalDhcp(boolean use) { externalDhcp = use; } - + @Override public boolean equals(Object obj) { if (obj instanceof HostPodVO) { @@ -180,16 +181,16 @@ public class HostPodVO implements Pod, Identity { return false; } } - + public Date getRemoved() { return removed; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/dc/PodVlanMapVO.java b/server/src/com/cloud/dc/PodVlanMapVO.java index 2e419ba8141..8853fac48ca 100644 --- a/server/src/com/cloud/dc/PodVlanMapVO.java +++ b/server/src/com/cloud/dc/PodVlanMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="pod_vlan_map") -public class PodVlanMapVO { +public class PodVlanMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/dc/PodVlanVO.java b/server/src/com/cloud/dc/PodVlanVO.java index 0d4f1cca27e..5324c8400f3 100755 --- a/server/src/com/cloud/dc/PodVlanVO.java +++ b/server/src/com/cloud/dc/PodVlanVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_pod_vlan_alloc") -public class PodVlanVO { +public class PodVlanVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -67,7 +69,7 @@ public class PodVlanVO { this.takenAt = null; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java index 1f252994ea1..6ad1ecd3c39 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -33,7 +35,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="op_dc_storage_network_ip_address") @SecondaryTables({@SecondaryTable(name = "dc_storage_network_ip_range", pkJoinColumns = { @PrimaryKeyJoinColumn(name = "range_id", referencedColumnName = "id")})}) -public class StorageNetworkIpAddressVO { +public class StorageNetworkIpAddressVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") @@ -64,7 +66,7 @@ public class StorageNetworkIpAddressVO { protected StorageNetworkIpAddressVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java index bb17e4ab603..e410d22959e 100755 --- a/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java +++ b/server/src/com/cloud/dc/StorageNetworkIpRangeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.dc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; diff --git a/server/src/com/cloud/dc/VlanVO.java b/server/src/com/cloud/dc/VlanVO.java index ff57f5e3d6f..fcb46c4971e 100644 --- a/server/src/com/cloud/dc/VlanVO.java +++ b/server/src/com/cloud/dc/VlanVO.java @@ -27,45 +27,46 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vlan") -public class VlanVO implements Vlan, Identity { - +public class VlanVO implements Vlan { + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) - @Column(name="id") + @Column(name="id") Long id; - - @Column(name="vlan_id") + + @Column(name="vlan_id") String vlanTag; - - @Column(name="vlan_gateway") + + @Column(name="vlan_gateway") String vlanGateway; - - @Column(name="vlan_netmask") + + @Column(name="vlan_netmask") String vlanNetmask; - - @Column(name="data_center_id") + + @Column(name="data_center_id") long dataCenterId; - - @Column(name="description") + + @Column(name="description") String ipRange; - + @Column(name="network_id") Long networkId; - + @Column(name="physical_network_id") Long physicalNetworkId; - + @Column(name="vlan_type") - @Enumerated(EnumType.STRING) + @Enumerated(EnumType.STRING) VlanType vlanType; @Column(name="uuid") String uuid; - + public VlanVO(VlanType vlanType, String vlanTag, String vlanGateway, String vlanNetmask, long dataCenterId, String ipRange, Long networkId, Long physicalNetworkId) { this.vlanType = vlanType; this.vlanTag = vlanTag; @@ -77,16 +78,16 @@ public class VlanVO implements Vlan, Identity { this.uuid = UUID.randomUUID().toString(); this.physicalNetworkId = physicalNetworkId; } - + public VlanVO() { this.uuid = UUID.randomUUID().toString(); } - + @Override public long getId() { return id; } - + @Override public String getVlanTag() { return vlanTag; @@ -96,12 +97,12 @@ public class VlanVO implements Vlan, Identity { public String getVlanGateway() { return vlanGateway; } - + @Override public String getVlanNetmask() { return vlanNetmask; } - + @Override public long getDataCenterId() { return dataCenterId; @@ -125,12 +126,12 @@ public class VlanVO implements Vlan, Identity { public void setNetworkId(Long networkId) { this.networkId = networkId; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -142,7 +143,7 @@ public class VlanVO implements Vlan, Identity { public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } - + transient String toString; @Override public String toString() { @@ -152,5 +153,5 @@ public class VlanVO implements Vlan, Identity { } return toString; } - + } diff --git a/server/src/com/cloud/dc/dao/HostPodDao.java b/server/src/com/cloud/dc/dao/HostPodDao.java index f031ac977e8..ced348425fd 100644 --- a/server/src/com/cloud/dc/dao/HostPodDao.java +++ b/server/src/com/cloud/dc/dao/HostPodDao.java @@ -21,11 +21,14 @@ import java.util.List; import com.cloud.dc.HostPodVO; import com.cloud.utils.db.GenericDao; +import com.cloud.vm.VirtualMachine; public interface HostPodDao extends GenericDao { public List listByDataCenterId(long id); - - public HostPodVO findByName(String name, long dcId); + + public List listByDataCenterIdVMTypeAndStates(long id, VirtualMachine.Type type, VirtualMachine.State... states); + + public HostPodVO findByName(String name, long dcId); public HashMap> getCurrentPodCidrSubnets(long zoneId, long podIdToSkip); diff --git a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java index 91106670ae4..a06bd3fe10a 100644 --- a/server/src/com/cloud/dc/dao/HostPodDaoImpl.java +++ b/server/src/com/cloud/dc/dao/HostPodDaoImpl.java @@ -32,10 +32,15 @@ import com.cloud.dc.HostPodVO; import com.cloud.org.Grouping; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.JoinBuilder; 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.component.ComponentLocator; +import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.VMInstanceDaoImpl; @Component @Local(value={HostPodDao.class}) @@ -64,6 +69,27 @@ public class HostPodDaoImpl extends GenericDaoBase implements H return listBy(sc); } + @Override + public List listByDataCenterIdVMTypeAndStates(long id, VirtualMachine.Type type, VirtualMachine.State... states) { + final VMInstanceDaoImpl _vmDao = ComponentLocator.inject(VMInstanceDaoImpl.class); + SearchBuilder vmInstanceSearch = _vmDao.createSearchBuilder(); + vmInstanceSearch.and("type", vmInstanceSearch.entity().getType(), SearchCriteria.Op.EQ); + vmInstanceSearch.and("states", vmInstanceSearch.entity().getState(), SearchCriteria.Op.IN); + + SearchBuilder podIdSearch = createSearchBuilder(); + podIdSearch.and("dc", podIdSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + podIdSearch.select(null, SearchCriteria.Func.DISTINCT, podIdSearch.entity().getId()); + podIdSearch.join("vmInstanceSearch", vmInstanceSearch, podIdSearch.entity().getId(), + vmInstanceSearch.entity().getPodIdToDeployIn(), JoinBuilder.JoinType.INNER); + podIdSearch.done(); + + SearchCriteria sc = podIdSearch.create(); + sc.setParameters("dc", id); + sc.setJoinParameters("vmInstanceSearch", "type", type); + sc.setJoinParameters("vmInstanceSearch", "states", (Object[]) states); + return listBy(sc); + } + @Override public HostPodVO findByName(String name, long dcId) { SearchCriteria sc = DataCenterAndNameSearch.create(); diff --git a/server/src/com/cloud/deploy/FirstFitPlanner.java b/server/src/com/cloud/deploy/FirstFitPlanner.java index 9b5646db301..bcc1d264219 100755 --- a/server/src/com/cloud/deploy/FirstFitPlanner.java +++ b/server/src/com/cloud/deploy/FirstFitPlanner.java @@ -37,7 +37,6 @@ import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; -import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterVO; @@ -75,7 +74,6 @@ import com.cloud.storage.dao.VolumeDao; import com.cloud.user.AccountManager; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.StringUtils; import com.cloud.utils.component.Adapters; import com.cloud.vm.DiskProfile; import com.cloud.vm.ReservationContext; diff --git a/server/src/com/cloud/domain/DomainVO.java b/server/src/com/cloud/domain/DomainVO.java index 02d3efe7ac3..bb4ce0cecf7 100644 --- a/server/src/com/cloud/domain/DomainVO.java +++ b/server/src/com/cloud/domain/DomainVO.java @@ -26,16 +26,17 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; +import org.apache.cloudstack.api.InternalIdentity; import org.apache.log4j.Logger; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; @Entity @Table(name="domain") -public class DomainVO implements Domain, Identity { +public class DomainVO implements Domain { public static final Logger s_logger = Logger.getLogger(DomainVO.class.getName()); - + @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -49,10 +50,10 @@ public class DomainVO implements Domain, Identity { @Column(name="owner") private long accountId; - + @Column(name="path") private String path = null; - + @Column(name="level") private int level; @@ -64,18 +65,18 @@ public class DomainVO implements Domain, Identity { @Column(name="next_child_seq") private long nextChildSeq = 1L; - + @Column(name="state") private Domain.State state; - + @Column(name="network_domain") private String networkDomain; - + @Column(name="uuid") private String uuid; - + public DomainVO() {} - + public DomainVO(long id, String name, long owner, Long parentId, String networkDomain) { this(name, owner, parentId, networkDomain); this.id = id; @@ -102,7 +103,7 @@ public class DomainVO implements Domain, Identity { public Long getParent() { return parent; } - + @Override public void setParent(Long parent) { if(parent == null) { @@ -119,7 +120,7 @@ public class DomainVO implements Domain, Identity { public String getName() { return name; } - + @Override public void setName(String name) { this.name = name; @@ -129,59 +130,59 @@ public class DomainVO implements Domain, Identity { public long getAccountId() { return accountId; } - + @Override public Date getRemoved() { return removed; } - + @Override public String getPath() { return path; } - + @Override public void setPath(String path) { this.path = path; } - + @Override public int getLevel() { - return level; + return level; } - + public void setLevel(int level) { this.level = level; } - + @Override public int getChildCount() { - return childCount; + return childCount; } - + public void setChildCount(int count) { childCount = count; } - + @Override public long getNextChildSeq() { return nextChildSeq; } - + public void setNextChildSeq(long seq) { nextChildSeq = seq; } - - @Override + + @Override public Domain.State getState() { return state; } - + @Override public void setState(Domain.State state) { this.state = state; } - + @Override public String toString() { return new StringBuilder("Domain:").append(id).append(path).toString(); @@ -195,12 +196,12 @@ public class DomainVO implements Domain, Identity { public void setNetworkDomain(String domainSuffix) { this.networkDomain = domainSuffix; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } diff --git a/server/src/com/cloud/event/dao/EventJoinDao.java b/server/src/com/cloud/event/dao/EventJoinDao.java new file mode 100644 index 00000000000..cd37d7893df --- /dev/null +++ b/server/src/com/cloud/event/dao/EventJoinDao.java @@ -0,0 +1,40 @@ +// 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.event.dao; + +import java.util.List; + +import org.apache.cloudstack.api.response.EventResponse; + +import com.cloud.api.query.vo.EventJoinVO; +import com.cloud.event.Event; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.SearchCriteria; + +public interface EventJoinDao extends GenericDao { + + EventResponse newEventResponse(EventJoinVO uvo); + + EventJoinVO newEventView(Event vr); + + List searchByIds(Long... ids); + + List searchAllEvents(SearchCriteria sc, Filter filter); + + EventJoinVO findCompletedEvent(long startId); +} diff --git a/server/src/com/cloud/event/dao/EventJoinDaoImpl.java b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java new file mode 100644 index 00000000000..764df99557f --- /dev/null +++ b/server/src/com/cloud/event/dao/EventJoinDaoImpl.java @@ -0,0 +1,124 @@ +// 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.event.dao; + +import java.util.ArrayList; +import java.util.List; + +import javax.ejb.Local; + +import org.apache.log4j.Logger; + +import com.cloud.api.ApiResponseHelper; +import com.cloud.api.query.vo.EventJoinVO; + +import org.apache.cloudstack.api.response.EventResponse; +import com.cloud.event.Event; +import com.cloud.event.Event.State; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; + + +@Local(value={EventJoinDao.class}) +public class EventJoinDaoImpl extends GenericDaoBase implements EventJoinDao { + public static final Logger s_logger = Logger.getLogger(EventJoinDaoImpl.class); + + private SearchBuilder vrSearch; + + private SearchBuilder vrIdSearch; + + private SearchBuilder CompletedEventSearch; + + protected EventJoinDaoImpl() { + + vrSearch = createSearchBuilder(); + vrSearch.and("idIN", vrSearch.entity().getId(), SearchCriteria.Op.IN); + vrSearch.done(); + + vrIdSearch = createSearchBuilder(); + vrIdSearch.and("id", vrIdSearch.entity().getId(), SearchCriteria.Op.EQ); + vrIdSearch.done(); + + CompletedEventSearch = createSearchBuilder(); + CompletedEventSearch.and("state",CompletedEventSearch.entity().getState(),SearchCriteria.Op.EQ); + CompletedEventSearch.and("startId", CompletedEventSearch.entity().getStartId(), SearchCriteria.Op.EQ); + CompletedEventSearch.done(); + + + this._count = "select count(distinct id) from event_view WHERE "; + } + + + + @Override + public List searchAllEvents(SearchCriteria sc, Filter filter) { + return listIncludingRemovedBy(sc, filter); + } + + + + @Override + public EventJoinVO findCompletedEvent(long startId) { + SearchCriteria sc = CompletedEventSearch.create(); + sc.setParameters("state", State.Completed); + sc.setParameters("startId", startId); + return findOneIncludingRemovedBy(sc); + } + + + + @Override + public EventResponse newEventResponse(EventJoinVO event) { + EventResponse responseEvent = new EventResponse(); + responseEvent.setCreated(event.getCreateDate()); + responseEvent.setDescription(event.getDescription()); + responseEvent.setEventType(event.getType()); + responseEvent.setId(event.getUuid()); + responseEvent.setLevel(event.getLevel()); + responseEvent.setParentId(event.getStartUuid()); + responseEvent.setState(event.getState()); + responseEvent.setUsername(event.getUserName()); + + ApiResponseHelper.populateOwner(responseEvent, event); + responseEvent.setObjectName("event"); + return responseEvent; + } + + + + @Override + public List searchByIds(Long... ids) { + SearchCriteria sc = vrSearch.create(); + sc.setParameters("idIN", ids); + return searchIncludingRemoved(sc, null, null, false); + } + + + @Override + public EventJoinVO newEventView(Event vr) { + + SearchCriteria sc = vrIdSearch.create(); + sc.setParameters("id", vr.getId()); + List vms = searchIncludingRemoved(sc, null, null, false); + assert vms != null && vms.size() == 1 : "No event found for event id " + vr.getId(); + return vms.get(0); + + } + +} diff --git a/server/src/com/cloud/ha/HaWorkVO.java b/server/src/com/cloud/ha/HaWorkVO.java index d5f41e0f76a..adfa3ec4e27 100644 --- a/server/src/com/cloud/ha/HaWorkVO.java +++ b/server/src/com/cloud/ha/HaWorkVO.java @@ -34,10 +34,11 @@ import com.cloud.ha.HighAvailabilityManager.WorkType; import com.cloud.utils.db.GenericDao; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="op_ha_work") -public class HaWorkVO { +public class HaWorkVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -87,7 +88,7 @@ public class HaWorkVO { protected HaWorkVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/host/dao/HostDaoImpl.java b/server/src/com/cloud/host/dao/HostDaoImpl.java index e58d2673eca..0767befcb70 100755 --- a/server/src/com/cloud/host/dao/HostDaoImpl.java +++ b/server/src/com/cloud/host/dao/HostDaoImpl.java @@ -67,7 +67,7 @@ import com.cloud.utils.exception.CloudRuntimeException; @Local(value = { HostDao.class }) @DB(txn = false) @TableGenerator(name = "host_req_sq", table = "op_host", pkColumnName = "id", valueColumnName = "sequence", allocationSize = 1) -public class HostDaoImpl extends GenericDaoBase implements HostDao { +public class HostDaoImpl extends GenericDaoBase implements HostDao { //FIXME: , ExternalIdDao { private static final Logger s_logger = Logger.getLogger(HostDaoImpl.class); private static final Logger status_logger = Logger.getLogger(Status.class); private static final Logger state_logger = Logger.getLogger(ResourceState.class); diff --git a/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java b/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java index d14773469b4..6fead23dad0 100644 --- a/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java +++ b/server/src/com/cloud/hypervisor/kvm/discoverer/KvmServerDiscoverer.java @@ -71,7 +71,6 @@ import com.cloud.utils.ssh.SSHCmdHelper; public class KvmServerDiscoverer extends DiscovererBase implements Discoverer, Listener, ResourceStateAdapter { private static final Logger s_logger = Logger.getLogger(KvmServerDiscoverer.class); - private String _setupAgentPath; private ConfigurationDao _configDao; private String _hostIp; private int _waitTime = 5; /*wait for 5 minutes*/ @@ -178,9 +177,9 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer, } List netInfos = _networkMgr.getPhysicalNetworkInfo(dcId, HypervisorType.KVM); - String kvmPrivateNic = _kvmPrivateNic; - String kvmPublicNic = _kvmPublicNic; - String kvmGuestNic = _kvmGuestNic; + String kvmPrivateNic = null; + String kvmPublicNic = null; + String kvmGuestNic = null; for (PhysicalNetworkSetupInfo info : netInfos) { if (info.getPrivateNetworkName() != null) { @@ -194,20 +193,30 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer, } } - String parameters = " -m " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -g " + guid + " -a"; + if (kvmPrivateNic == null && kvmPublicNic == null && kvmGuestNic == null) { + kvmPrivateNic = _kvmPrivateNic; + kvmPublicNic = _kvmPublicNic; + kvmGuestNic = _kvmGuestNic; + } - if (kvmPublicNic != null) { - parameters += " --pubNic=" + kvmPublicNic; + if (kvmPublicNic == null) { + kvmPublicNic = (kvmGuestNic != null) ? kvmGuestNic : kvmPrivateNic; } - if (kvmPrivateNic != null) { - parameters += " --prvNic=" + kvmPrivateNic; + if (kvmPrivateNic == null) { + kvmPrivateNic = (kvmPublicNic != null) ? kvmPublicNic : kvmGuestNic; } - if (kvmGuestNic != null) { - parameters += " --guestNic=" + kvmGuestNic; + if (kvmGuestNic == null) { + kvmGuestNic = (kvmPublicNic != null) ? kvmPublicNic : kvmPrivateNic; } + String parameters = " -m " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -g " + guid + " -a"; + + parameters += " --pubNic=" + kvmPublicNic; + parameters += " --prvNic=" + kvmPrivateNic; + parameters += " --guestNic=" + kvmGuestNic; + SSHCmdHelper.sshExecuteCmd(sshConnection, "cloud-setup-agent " + parameters, 3); KvmDummyResourceBase kvmResource = new KvmDummyResourceBase(); @@ -280,7 +289,6 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer, public boolean configure(String name, Map params) throws ConfigurationException { ComponentLocator locator = ComponentLocator.getCurrentLocator(); _configDao = locator.getDao(ConfigurationDao.class); - _setupAgentPath = Script.findScript(getPatchPath(), "setup_agent.sh"); _kvmPrivateNic = _configDao.getValue(Config.KvmPrivateNetwork.key()); if (_kvmPrivateNic == null) { _kvmPrivateNic = "cloudbr0"; @@ -296,9 +304,6 @@ public class KvmServerDiscoverer extends DiscovererBase implements Discoverer, _kvmGuestNic = _kvmPrivateNic; } - if (_setupAgentPath == null) { - throw new ConfigurationException("Can't find setup_agent.sh"); - } _hostIp = _configDao.getValue("host"); if (_hostIp == null) { throw new ConfigurationException("Can't get host IP"); diff --git a/server/src/com/cloud/keystore/KeystoreVO.java b/server/src/com/cloud/keystore/KeystoreVO.java index a7be602fe45..f590607e3a1 100644 --- a/server/src/com/cloud/keystore/KeystoreVO.java +++ b/server/src/com/cloud/keystore/KeystoreVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.keystore; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name="keystore") -public class KeystoreVO { +public class KeystoreVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -49,7 +51,7 @@ public class KeystoreVO { public KeystoreVO() { } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/maint/AgentUpgradeVO.java b/server/src/com/cloud/maint/AgentUpgradeVO.java index b784ead7825..b36f5b7dd6c 100644 --- a/server/src/com/cloud/maint/AgentUpgradeVO.java +++ b/server/src/com/cloud/maint/AgentUpgradeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.maint; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; @@ -26,7 +28,7 @@ import javax.persistence.Table; @Entity @Table(name="op_host_upgrade") -public class AgentUpgradeVO { +public class AgentUpgradeVO implements InternalIdentity { @Id @Column(name="host_id") private long id; diff --git a/server/src/com/cloud/maint/UpgradeManagerImpl.java b/server/src/com/cloud/maint/UpgradeManagerImpl.java index 0b02598c7e8..463761477aa 100644 --- a/server/src/com/cloud/maint/UpgradeManagerImpl.java +++ b/server/src/com/cloud/maint/UpgradeManagerImpl.java @@ -36,6 +36,7 @@ import javax.naming.ConfigurationException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -56,6 +57,7 @@ import com.cloud.utils.component.ComponentLocator; @Local(UpgradeManager.class) public class UpgradeManagerImpl implements UpgradeManager { private final static Logger s_logger = Logger.getLogger(UpgradeManagerImpl.class); + private static final MultiThreadedHttpConnectionManager s_httpClientManager = new MultiThreadedHttpConnectionManager(); String _name; String _minimalVersion; @@ -94,7 +96,7 @@ public class UpgradeManagerImpl implements UpgradeManager { public String deployNewAgent(String url) { s_logger.info("Updating agent with binary from " + url); - final HttpClient client = new HttpClient(); + final HttpClient client = new HttpClient(s_httpClientManager); final GetMethod method = new GetMethod(url); int response; File file = null; @@ -131,6 +133,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/migration/DiskOffering20VO.java b/server/src/com/cloud/migration/DiskOffering20VO.java index 8c261715e39..e50328d7cd7 100644 --- a/server/src/com/cloud/migration/DiskOffering20VO.java +++ b/server/src/com/cloud/migration/DiskOffering20VO.java @@ -26,10 +26,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="disk_offering") -public class DiskOffering20VO { +public class DiskOffering20VO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -64,7 +65,7 @@ public class DiskOffering20VO { this.mirrored = mirrored; } - public Long getId() { + public long getId() { return id; } public void setId(Long id) { diff --git a/server/src/com/cloud/migration/DiskOffering21VO.java b/server/src/com/cloud/migration/DiskOffering21VO.java index f428c519e87..593f7ba61ff 100644 --- a/server/src/com/cloud/migration/DiskOffering21VO.java +++ b/server/src/com/cloud/migration/DiskOffering21VO.java @@ -32,12 +32,13 @@ import javax.persistence.Table; import javax.persistence.Transient; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="disk_offering_21") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="type", discriminatorType=DiscriminatorType.STRING, length=32) -public class DiskOffering21VO { +public class DiskOffering21VO implements InternalIdentity { public enum Type { Disk, Service diff --git a/server/src/com/cloud/migration/ServiceOffering20VO.java b/server/src/com/cloud/migration/ServiceOffering20VO.java index 065c9246964..bed29ecf3b9 100644 --- a/server/src/com/cloud/migration/ServiceOffering20VO.java +++ b/server/src/com/cloud/migration/ServiceOffering20VO.java @@ -30,10 +30,11 @@ import javax.persistence.Table; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="service_offering") -public class ServiceOffering20VO { +public class ServiceOffering20VO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -108,7 +109,7 @@ public class ServiceOffering20VO { this.offerHA = offerHA; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/migration/ServiceOffering21VO.java b/server/src/com/cloud/migration/ServiceOffering21VO.java index adfac1aad61..fdec30e3b8a 100644 --- a/server/src/com/cloud/migration/ServiceOffering21VO.java +++ b/server/src/com/cloud/migration/ServiceOffering21VO.java @@ -32,25 +32,25 @@ import com.cloud.offering.ServiceOffering; public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffering { @Column(name="cpu") private int cpu; - + @Column(name="speed") private int speed; - + @Column(name="ram_size") private int ramSize; - + @Column(name="nw_rate") private Integer rateMbps; - + @Column(name="mc_rate") private Integer multicastRateMbps; - + @Column(name="ha_enabled") private boolean offerHA; - + @Column(name="host_tag") - private String hostTag; - + private String hostTag; + protected ServiceOffering21VO() { super(); } @@ -64,19 +64,19 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe this.multicastRateMbps = multicastRateMbps; this.offerHA = offerHA; } - + public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) { this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags); this.hostTag = hostTag; } - + @Override public boolean getOfferHA() { return offerHA; } - @Override + @Override public boolean getLimitCpuUse() { return false; } @@ -84,7 +84,7 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setOfferHA(boolean offerHA) { this.offerHA = offerHA; } - + @Override @Transient public String[] getTagsArray() { @@ -92,15 +92,15 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe if (tags == null || tags.length() == 0) { return new String[0]; } - + return tags.split(","); } - + @Override public int getCpu() { return cpu; } - + public void setCpu(int cpu) { this.cpu = cpu; } @@ -112,17 +112,17 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setRamSize(int ramSize) { this.ramSize = ramSize; } - + @Override public int getSpeed() { return speed; } - + @Override public int getRamSize() { return ramSize; } - + public void setRateMbps(Integer rateMbps) { this.rateMbps = rateMbps; } @@ -135,7 +135,7 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setMulticastRateMbps(Integer multicastRateMbps) { this.multicastRateMbps = multicastRateMbps; } - + @Override public Integer getMulticastRateMbps() { return multicastRateMbps; @@ -147,8 +147,8 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe public void setHostTag(String hostTag) { this.hostTag = hostTag; - } - + } + public String getHostTag() { return hostTag; } @@ -156,10 +156,18 @@ public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffe @Override public boolean getDefaultUse() { return false; - } - + } + @Override public String getSystemVmType() { return null; - } + } + + @Override + public String getUuid() { + // TODO Auto-generated method stub + return null; + } + + } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManager.java b/server/src/com/cloud/network/ExternalFirewallDeviceManager.java index f6a39d96cea..f758ca1d341 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceManager.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceManager.java @@ -22,6 +22,7 @@ import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.host.Host; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.PortForwardingRule; import com.cloud.resource.ServerResource; import com.cloud.utils.component.Manager; @@ -94,4 +95,12 @@ public interface ExternalFirewallDeviceManager extends Manager { */ public boolean manageGuestNetworkWithExternalFirewall(boolean add, Network guestConfig) throws ResourceUnavailableException, InsufficientCapacityException; + /** + * applies port forwarding rules + * @param network guest network if + * @param rules load balancer rules + * @return true if successfully applied rules + * @throws ResourceUnavailableException + */ + public boolean applyPortForwardingRules(Network network, List rules) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java index fdccdd3d1f5..927a1164647 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceManagerImpl.java @@ -31,17 +31,18 @@ import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupExternalFirewallCommand; -import com.cloud.agent.api.StartupExternalLoadBalancerCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; +import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; +import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -50,7 +51,6 @@ import com.cloud.dc.Vlan; import com.cloud.dc.VlanVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; -import com.cloud.exception.AgentUnavailableException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientNetworkCapacityException; import com.cloud.exception.InvalidParameterValueException; @@ -60,12 +60,10 @@ import com.cloud.host.Host; import com.cloud.host.HostVO; import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; -import com.cloud.network.ExternalFirewallDeviceVO.FirewallDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; -import com.cloud.network.Network.Capability; -import com.cloud.network.Network.Service; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.ExternalFirewallDeviceDao; +import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.InlineLoadBalancerNicMapDao; import com.cloud.network.dao.LoadBalancerDao; @@ -77,17 +75,17 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.PhysicalNetworkServiceProviderVO; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.rules.FirewallRule; -import com.cloud.network.rules.FirewallRule.Purpose; import com.cloud.network.rules.PortForwardingRule; -import com.cloud.network.rules.StaticNatRule; +import com.cloud.network.rules.StaticNat; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.dao.NetworkOfferingDao; import com.cloud.resource.ResourceManager; +import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.ExternalFirewallResponse; +import org.apache.cloudstack.api.response.ExternalFirewallResponse; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.dao.AccountDao; @@ -133,6 +131,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Inject NetworkExternalFirewallDao _networkExternalFirewallDao; @Inject VpnUserDao _vpnUsersDao; @Inject HostDetailsDao _hostDetailDao; + @Inject FirewallRulesDao _fwRulesDao; private static final org.apache.log4j.Logger s_logger = Logger.getLogger(ExternalFirewallDeviceManagerImpl.class); private long _defaultFwCapacity; @@ -236,14 +235,26 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl throw new InvalidParameterValueException("Could not find an external firewall with ID: " + hostId); } + DetailVO fwHostDetails = _hostDetailDao.findDetail(hostId, ApiConstants.FIREWALL_DEVICE_ID); + long fwDeviceId = Long.parseLong(fwHostDetails.getValue()); + + // check if any networks are using this balancer device + List networks = _networkExternalFirewallDao.listByFirewallDeviceId(fwDeviceId); + if ((networks != null) && !networks.isEmpty()) { + throw new CloudRuntimeException("Delete can not be done as there are networks using the firewall device "); + } + try { - if (_resourceMgr.maintain(hostId) && _resourceMgr.deleteHost(hostId, false, false)) { + // put the host in maintenance state in order for it to be deleted + externalFirewall.setResourceState(ResourceState.Maintenance); + _hostDao.update(hostId, externalFirewall); + _resourceMgr.deleteHost(hostId, false, false); + + // delete the external load balancer entry + _externalFirewallDeviceDao.remove(fwDeviceId); return true; - } else { - return false; - } - } catch (AgentUnavailableException e) { - s_logger.debug(e); + } catch (Exception e) { + s_logger.debug("Failed to delete external firewall device due to " + e.getMessage()); return false; } } @@ -316,6 +327,32 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl " to implement the network", DataCenter.class, network.getDataCenterId()); } + @DB + protected boolean freeFirewallForNetwork(Network network) { + Transaction txn = Transaction.currentTxn(); + GlobalLock deviceMapLock = GlobalLock.getInternLock("NetworkFirewallDeviceMap"); + try { + if (deviceMapLock.lock(120)) { + try { + NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); + if (fwDeviceForNetwork != null) { + _networkExternalFirewallDao.remove(fwDeviceForNetwork.getId()); + } + } catch (Exception exception) { + txn.rollback(); + s_logger.error("Failed to release firewall device for the network" + network.getId() + " due to " + exception.getMessage()); + return false; + } finally { + deviceMapLock.unlock(); + } + } + } finally { + deviceMapLock.releaseRef(); + } + txn.commit(); + return true; + } + public String getExternalNetworkResourceGuid(long physicalNetworkId, String deviceName, String ip) { return physicalNetworkId + "-" + deviceName + "-" + ip; } @@ -323,7 +360,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl public ExternalFirewallResponse createExternalFirewallResponse(Host externalFirewall) { Map fwDetails = _hostDetailDao.findDetails(externalFirewall.getId()); ExternalFirewallResponse response = new ExternalFirewallResponse(); - response.setId(externalFirewall.getId()); + response.setId(externalFirewall.getUuid()); response.setIpAddress(externalFirewall.getPrivateIpAddress()); response.setUsername(fwDetails.get("username")); response.setPublicInterface(fwDetails.get("publicInterface")); @@ -422,15 +459,21 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl cmd.setAccessDetail(NetworkElementCommand.GUEST_VLAN_TAG, String.valueOf(guestVlanTag)); Answer answer = _agentMgr.easySend(externalFirewall.getId(), cmd); + List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId()); + if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; String answerDetails = (answer != null) ? answer.getDetails() : "answer was null"; String msg = "External firewall was unable to " + action + " the guest network on the external firewall in zone " + zone.getName() + " due to " + answerDetails; s_logger.error(msg); + if (!add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { + // If we failed the implementation as well, then just return, no complain + s_logger.error("Skip the shutdown of guest network on SRX because it seems we didn't implement it as well"); + return true; + } throw new ResourceUnavailableException(msg, DataCenter.class, zoneId); } - List reservedIpAddressesForGuestNetwork = _nicDao.listIpAddressInNetwork(network.getId()); if (add && (!reservedIpAddressesForGuestNetwork.contains(network.getGateway()))) { // Insert a new NIC for this guest network to reserve the gateway address savePlaceholderNic(network, network.getGateway()); @@ -447,6 +490,19 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } } + // on network shutdown, delete placeHolder nics used for the firewall device + if (!add) { + List guestIps = _nicDao.listByNetworkId(network.getId()); + for (NicVO guestIp : guestIps) { + // only external firewall and external load balancer will create NicVO with PlaceHolder reservation strategy + if (guestIp.getReservationStrategy().equals(ReservationStrategy.PlaceHolder) && guestIp.getIp4Address().equals(network.getGateway())) { + _nicDao.remove(guestIp.getId()); + } + } + + freeFirewallForNetwork(network); + } + String action = add ? "implemented" : "shut down"; s_logger.debug("External firewall has " + action + " the guest network for account " + account.getAccountName() + "(id = " + account.getAccountId() + ") with VLAN tag " + guestVlanTag); @@ -456,6 +512,37 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Override public boolean applyFirewallRules(Network network, List rules) throws ResourceUnavailableException { // Find the external firewall in this zone + long zoneId = network.getDataCenterId(); + DataCenterVO zone = _dcDao.findById(zoneId); + ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); + // During destroy, device reference may already been clean up, then we just return true + if (fwDeviceVO == null) { + return true; + } + HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); + + assert(externalFirewall != null); + + if (network.getState() == Network.State.Allocated) { + s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); + return true; + } + + List rulesTO = new ArrayList(); + + for (FirewallRule rule : rules) { + IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); + FirewallRuleTO ruleTO = new FirewallRuleTO(rule, null, sourceIp.getAddress().addr()); + rulesTO.add(ruleTO); + } + + //Firewall rules configured for staticNAT/PF + sendFirewallRules(rulesTO, zone, externalFirewall.getId()); + + return true; + } + + public boolean applyStaticNatRules(Network network, List rules) throws ResourceUnavailableException { long zoneId = network.getDataCenterId(); DataCenterVO zone = _dcDao.findById(zoneId); ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); @@ -469,32 +556,34 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } List staticNatRules = new ArrayList(); - List portForwardingRules = new ArrayList(); - - for (FirewallRule rule : rules) { + + for (StaticNat rule : rules) { IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); - if (rule.getPurpose() == Purpose.StaticNat) { - StaticNatRule staticNatRule = (StaticNatRule) rule; - StaticNatRuleTO ruleTO = new StaticNatRuleTO(staticNatRule, vlan.getVlanTag(), sourceIp.getAddress().addr(), staticNatRule.getDestIpAddress()); - staticNatRules.add(ruleTO); - } else if (rule.getPurpose() == Purpose.PortForwarding) { - PortForwardingRuleTO ruleTO = new PortForwardingRuleTO((PortForwardingRule) rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); - portForwardingRules.add(ruleTO); - } + StaticNatRuleTO ruleTO = new StaticNatRuleTO(0,vlan.getVlanTag(), sourceIp.getAddress().addr(), -1, -1, rule.getDestIpAddress(), -1, -1, "any", rule.isForRevoke(), false); + staticNatRules.add(ruleTO); } - // Apply static nat rules - applyStaticNatRules(staticNatRules, zone, externalFirewall.getId()); - - // apply port forwarding rules - applyPortForwardingRules(portForwardingRules, zone, externalFirewall.getId()); + sendStaticNatRules(staticNatRules, zone, externalFirewall.getId()); return true; } - protected void applyStaticNatRules(List staticNatRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + protected void sendFirewallRules(List firewallRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + if (!firewallRules.isEmpty()) { + SetFirewallRulesCommand cmd = new SetFirewallRulesCommand(firewallRules); + Answer answer = _agentMgr.easySend(externalFirewallId, cmd); + if (answer == null || !answer.getResult()) { + String details = (answer != null) ? answer.getDetails() : "details unavailable"; + String msg = "External firewall was unable to apply static nat rules to the SRX appliance in zone " + zone.getName() + " due to: " + details + "."; + s_logger.error(msg); + throw new ResourceUnavailableException(msg, DataCenter.class, zone.getId()); + } + } + } + + protected void sendStaticNatRules(List staticNatRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { if (!staticNatRules.isEmpty()) { SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(staticNatRules, null); Answer answer = _agentMgr.easySend(externalFirewallId, cmd); @@ -507,7 +596,7 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl } } - protected void applyPortForwardingRules(List portForwardingRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { + protected void sendPortForwardingRules(List portForwardingRules, DataCenter zone, long externalFirewallId) throws ResourceUnavailableException { if (!portForwardingRules.isEmpty()) { SetPortForwardingRulesCommand cmd = new SetPortForwardingRulesCommand(portForwardingRules); Answer answer = _agentMgr.easySend(externalFirewallId, cmd); @@ -648,7 +737,38 @@ public abstract class ExternalFirewallDeviceManagerImpl extends AdapterBase impl @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub + if (host.getType() != com.cloud.host.Host.Type.ExternalFirewall) { return null; } + return new DeleteHostAnswer(true); + } + + @Override + public boolean applyPortForwardingRules(Network network, List rules) throws ResourceUnavailableException { + // Find the external firewall in this zone + long zoneId = network.getDataCenterId(); + DataCenterVO zone = _dcDao.findById(zoneId); + ExternalFirewallDeviceVO fwDeviceVO = getExternalFirewallForNetwork(network); + HostVO externalFirewall = _hostDao.findById(fwDeviceVO.getHostId()); + + assert(externalFirewall != null); + + if (network.getState() == Network.State.Allocated) { + s_logger.debug("External firewall was asked to apply firewall rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); + return true; + } + + List pfRules = new ArrayList(); + + for (PortForwardingRule rule : rules) { + IpAddress sourceIp = _networkMgr.getIp(rule.getSourceIpAddressId()); + Vlan vlan = _vlanDao.findById(sourceIp.getVlanId()); + + PortForwardingRuleTO ruleTO = new PortForwardingRuleTO(rule, vlan.getVlanTag(), sourceIp.getAddress().addr()); + pfRules.add(ruleTO); + } + + sendPortForwardingRules(pfRules, zone, externalFirewall.getId()); + return true; + } } diff --git a/server/src/com/cloud/network/ExternalFirewallDeviceVO.java b/server/src/com/cloud/network/ExternalFirewallDeviceVO.java index 9b587776979..83be8c40b3d 100644 --- a/server/src/com/cloud/network/ExternalFirewallDeviceVO.java +++ b/server/src/com/cloud/network/ExternalFirewallDeviceVO.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.UUID; import javax.persistence.Column; @@ -33,7 +36,7 @@ import javax.persistence.Table; @Entity @Table(name="external_firewall_devices") -public class ExternalFirewallDeviceVO { +public class ExternalFirewallDeviceVO implements InternalIdentity, Identity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java index 7ad88b56397..ee082e089f0 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceManagerImpl.java @@ -37,11 +37,9 @@ import com.cloud.agent.api.routing.DestroyLoadBalancerApplianceCommand; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; -import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.LoadBalancerTO; -import com.cloud.agent.api.to.StaticNatRuleTO; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -49,7 +47,6 @@ import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.Pod; import com.cloud.dc.Vlan.VlanType; -import com.cloud.dc.VlanVO; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.VlanDao; @@ -64,7 +61,8 @@ import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceAllocationState; import com.cloud.network.ExternalLoadBalancerDeviceVO.LBDeviceState; -import com.cloud.network.ExternalNetworkDeviceManager.NetworkDevice; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager.NetworkDevice; +import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; @@ -80,15 +78,17 @@ 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.element.IpDeployer; +import com.cloud.network.element.NetworkElement; +import com.cloud.network.element.StaticNatServiceProvider; import com.cloud.network.lb.LoadBalancingRule; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.resource.CreateLoadBalancerApplianceAnswer; import com.cloud.network.resource.DestroyLoadBalancerApplianceAnswer; import com.cloud.network.rules.FirewallRule; import com.cloud.network.rules.FirewallRule.Purpose; -import com.cloud.network.rules.FirewallRuleVO; -import com.cloud.network.rules.StaticNatRule; -import com.cloud.network.rules.StaticNatRuleImpl; +import com.cloud.network.rules.StaticNat; +import com.cloud.network.rules.StaticNatImpl; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offerings.NetworkOfferingVO; import com.cloud.offerings.dao.NetworkOfferingDao; @@ -97,7 +97,7 @@ import com.cloud.resource.ResourceState; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.ExternalLoadBalancerResponse; +import org.apache.cloudstack.api.response.ExternalLoadBalancerResponse; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.dao.AccountDao; @@ -115,6 +115,7 @@ import com.cloud.vm.Nic.State; import com.cloud.vm.NicVO; import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.NicDao; + public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase implements ExternalLoadBalancerDeviceManager, ResourceStateAdapter { @Inject @@ -238,15 +239,14 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase if (host != null) { boolean dedicatedUse = (configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_DEDICATED)) : false; - boolean inline = (configParams.get(ApiConstants.INLINE) != null) ? Boolean.parseBoolean(configParams.get(ApiConstants.INLINE)) : false; - long capacity = NumbersUtil.parseLong((String) configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); + long capacity = NumbersUtil.parseLong(configParams.get(ApiConstants.LOAD_BALANCER_DEVICE_CAPACITY), 0); if (capacity == 0) { capacity = _defaultLbCapacity; } txn.start(); ExternalLoadBalancerDeviceVO lbDeviceVO = new ExternalLoadBalancerDeviceVO(host.getId(), pNetwork.getId(), ntwkSvcProvider.getProviderName(), - deviceName, capacity, dedicatedUse, inline); + deviceName, capacity, dedicatedUse); _externalLoadBalancerDeviceDao.persist(lbDeviceVO); DetailVO hostDetail = new DetailVO(host.getId(), ApiConstants.LOAD_BALANCER_DEVICE_ID, String.valueOf(lbDeviceVO.getId())); @@ -338,7 +338,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase public ExternalLoadBalancerResponse createExternalLoadBalancerResponse(Host externalLoadBalancer) { Map lbDetails = _hostDetailDao.findDetails(externalLoadBalancer.getId()); ExternalLoadBalancerResponse response = new ExternalLoadBalancerResponse(); - response.setId(externalLoadBalancer.getId()); + response.setId(externalLoadBalancer.getUuid()); response.setIpAddress(externalLoadBalancer.getPrivateIpAddress()); response.setUsername(lbDetails.get("username")); response.setPublicInterface(lbDetails.get("publicInterface")); @@ -688,30 +688,6 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return false; } - HostVO getFirewallProviderForNetwork(Network network) { - HostVO fwHost = null; - - // get the firewall provider (could be either virtual router or external firewall device) for the network - String fwProvider = _ntwkSrvcProviderDao.getProviderForServiceInNetwork(network.getId(), Service.Firewall); - - if (fwProvider.equalsIgnoreCase("VirtualRouter")) { - // FIXME: use network service provider container framework support to implement on virtual router - } else { - NetworkExternalFirewallVO fwDeviceForNetwork = _networkExternalFirewallDao.findByNetworkId(network.getId()); - assert (fwDeviceForNetwork != null) : "Why firewall provider is not ready for the network to apply static nat rules?"; - long fwDeviceId = fwDeviceForNetwork.getExternalFirewallDeviceId(); - ExternalFirewallDeviceVO fwDevice = _externalFirewallDeviceDao.findById(fwDeviceId); - fwHost = _hostDao.findById(fwDevice.getHostId()); - } - - return fwHost; - } - - private boolean externalLoadBalancerIsInline(HostVO externalLoadBalancer) { - DetailVO detail = _hostDetailDao.findDetail(externalLoadBalancer.getId(), "inline"); - return (detail != null && detail.getValue().equals("true")); - } - private NicVO savePlaceholderNic(Network network, String ipAddress) { NicVO nic = new NicVO(null, null, network.getId(), null); nic.setIp4Address(ipAddress); @@ -732,31 +708,115 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return null; } - private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, HostVO firewallHost, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { - List staticNatRules = new ArrayList(); + private void applyStaticNatRuleForInlineLBRule(DataCenterVO zone, Network network, boolean revoked, String publicIp, String privateIp) throws ResourceUnavailableException { + List staticNats = new ArrayList(); IPAddressVO ipVO = _ipAddressDao.listByDcIdIpAddress(zone.getId(), publicIp).get(0); - VlanVO vlan = _vlanDao.findById(ipVO.getVlanId()); - FirewallRuleVO fwRule = new FirewallRuleVO(null, ipVO.getId(), -1, -1, "any", network.getId(), network.getAccountId(), network.getDomainId(), Purpose.StaticNat, null, null, null, null, null); - FirewallRule.State state = !revoked ? FirewallRule.State.Add : FirewallRule.State.Revoke; - fwRule.setState(state); - StaticNatRule rule = new StaticNatRuleImpl(fwRule, privateIp); - StaticNatRuleTO ruleTO = new StaticNatRuleTO(rule, vlan.getVlanTag(), publicIp, privateIp); - staticNatRules.add(ruleTO); - - applyStaticNatRules(staticNatRules, network, firewallHost.getId()); + StaticNatImpl staticNat = new StaticNatImpl(ipVO.getAllocatedToAccountId(), ipVO.getAllocatedInDomainId(), + network.getId(), ipVO.getId(), privateIp, revoked); + staticNats.add(staticNat); + StaticNatServiceProvider element = _networkMgr.getStaticNatProviderForNetwork(network); + element.applyStaticNats(network, staticNats); } - protected void applyStaticNatRules(List staticNatRules, Network network, long firewallHostId) throws ResourceUnavailableException { - if (!staticNatRules.isEmpty()) { - SetStaticNatRulesCommand cmd = new SetStaticNatRulesCommand(staticNatRules, null); - Answer answer = _agentMgr.easySend(firewallHostId, cmd); - if (answer == null || !answer.getResult()) { - String details = (answer != null) ? answer.getDetails() : "details unavailable"; - String msg = "firewall provider for the network was unable to apply static nat rules due to: " + details + "."; + private enum MappingState { + Create, + Remove, + Unchanged, + }; + + private class MappingNic { + private NicVO nic; + private MappingState state; + + public NicVO getNic() { + return nic; + } + public void setNic(NicVO nic) { + this.nic = nic; + } + public MappingState getState() { + return state; + } + public void setState(MappingState state) { + this.state = state; + } + }; + + private MappingNic getLoadBalancingIpNic(DataCenterVO zone, Network network, long sourceIpId, boolean revoked, String existedGuestIp) throws ResourceUnavailableException { + String srcIp = _networkMgr.getIp(sourceIpId).getAddress().addr(); + InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); + NicVO loadBalancingIpNic = null; + MappingNic nic = new MappingNic(); + nic.setState(MappingState.Unchanged); + if (!revoked) { + if (mapping == null) { + // Acquire a new guest IP address and save it as the load balancing IP address + String loadBalancingIpAddress = existedGuestIp; + + if (loadBalancingIpAddress == null) { + loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); + } + + if (loadBalancingIpAddress == null) { + String msg = "Ran out of guest IP addresses."; s_logger.error(msg); - throw new ResourceUnavailableException(msg, Network.class, network.getId()); + throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); + } + + // If a NIC doesn't exist for the load balancing IP address, create one + loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); + if (loadBalancingIpNic == null) { + loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); + } + + // Save a mapping between the source IP address and the load balancing IP address NIC + mapping = new InlineLoadBalancerNicMapVO(srcIp, loadBalancingIpNic.getId()); + _inlineLoadBalancerNicMapDao.persist(mapping); + + // On the firewall provider for the network, create a static NAT rule between the source IP + // address and the load balancing IP address + try { + applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + } catch (ResourceUnavailableException ex) { + // Rollback db operation + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + _nicDao.expunge(loadBalancingIpNic.getId()); + throw ex; + } + + s_logger.debug("Created static nat rule for inline load balancer"); + nic.setState(MappingState.Create); + } else { + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + } + } else { + if (mapping != null) { + // Find the NIC that the mapping refers to + loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); + + int count = _networkMgr.getRuleCountForIp(sourceIpId, Purpose.LoadBalancing, FirewallRule.State.Active); + if (count == 0) { + // On the firewall provider for the network, delete the static NAT rule between the source IP + // address and the load balancing IP address + applyStaticNatRuleForInlineLBRule(zone, network, revoked, srcIp, loadBalancingIpNic.getIp4Address()); + + // Delete the mapping between the source IP address and the load balancing IP address + _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); + + // Delete the NIC + _nicDao.expunge(loadBalancingIpNic.getId()); + + s_logger.debug("Revoked static nat rule for inline load balancer"); + nic.setState(MappingState.Remove); + } + } else { + s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); + return null; } } + + nic.setNic(loadBalancingIpNic); + return nic; } @Override @@ -785,7 +845,7 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase HostVO externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); - boolean externalLoadBalancerIsInline = externalLoadBalancerIsInline(externalLoadBalancer); + boolean externalLoadBalancerIsInline = _networkMgr.isNetworkInlineMode(network); if (network.getState() == Network.State.Allocated) { s_logger.debug("External load balancer was asked to apply LB rules for network with ID " + network.getId() + "; this network is not implemented. Skipping backend commands."); @@ -793,83 +853,41 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase } List loadBalancersToApply = new ArrayList(); + List mappingStates = new ArrayList(); for (int i = 0; i < loadBalancingRules.size(); i++) { LoadBalancingRule rule = loadBalancingRules.get(i); boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); + String uuid = rule.getUuid(); String srcIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); - List sourceCidrs = rule.getSourceCidrList(); if (externalLoadBalancerIsInline) { - InlineLoadBalancerNicMapVO mapping = _inlineLoadBalancerNicMapDao.findByPublicIpAddress(srcIp); - NicVO loadBalancingIpNic = null; - HostVO firewallProviderHost = null; - - if (externalLoadBalancerIsInline) { - firewallProviderHost = getFirewallProviderForNetwork(network); - } - - if (!revoked) { - if (mapping == null) { - // Acquire a new guest IP address and save it as the load balancing IP address - String loadBalancingIpAddress = _networkMgr.acquireGuestIpAddress(network, null); - - if (loadBalancingIpAddress == null) { - String msg = "Ran out of guest IP addresses."; - s_logger.error(msg); - throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); - } - - // If a NIC doesn't exist for the load balancing IP address, create one - loadBalancingIpNic = _nicDao.findByIp4AddressAndNetworkId(loadBalancingIpAddress, network.getId()); + MappingNic nic = getLoadBalancingIpNic(zone, network, rule.getSourceIpAddressId(), revoked, null); + mappingStates.add(nic.getState()); + NicVO loadBalancingIpNic = nic.getNic(); if (loadBalancingIpNic == null) { - loadBalancingIpNic = savePlaceholderNic(network, loadBalancingIpAddress); - } - - // Save a mapping between the source IP address and the load balancing IP address NIC - mapping = new InlineLoadBalancerNicMapVO(rule.getId(), srcIp, loadBalancingIpNic.getId()); - _inlineLoadBalancerNicMapDao.persist(mapping); - - // On the firewall provider for the network, create a static NAT rule between the source IP -// address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - } else { - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - } - } else { - if (mapping != null) { - // Find the NIC that the mapping refers to - loadBalancingIpNic = _nicDao.findById(mapping.getNicId()); - - // On the firewall provider for the network, delete the static NAT rule between the source IP -// address and the load balancing IP address - applyStaticNatRuleForInlineLBRule(zone, network, firewallProviderHost, revoked, srcIp, loadBalancingIpNic.getIp4Address()); - - // Delete the mapping between the source IP address and the load balancing IP address - _inlineLoadBalancerNicMapDao.expunge(mapping.getId()); - - // Delete the NIC - _nicDao.expunge(loadBalancingIpNic.getId()); - } else { - s_logger.debug("Revoking a rule for an inline load balancer that has not been programmed yet."); continue; } - } // Change the source IP address for the load balancing rule to be the load balancing IP address srcIp = loadBalancingIpNic.getIp4Address(); } - if (destinations != null && !destinations.isEmpty()) { - LoadBalancerTO loadBalancer = new LoadBalancerTO(srcIp, srcPort, protocol, algorithm, revoked, false, destinations, rule.getStickinessPolicies()); + if ((destinations != null && !destinations.isEmpty()) || rule.isAutoScaleConfig()) { + boolean inline = _networkMgr.isNetworkInlineMode(network); + LoadBalancerTO loadBalancer = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, inline, destinations, rule.getStickinessPolicies()); + if (rule.isAutoScaleConfig()) { + loadBalancer.setAutoScaleVmGroup(rule.getAutoScaleVmGroup()); + } loadBalancersToApply.add(loadBalancer); } } + try { if (loadBalancersToApply.size() > 0) { int numLoadBalancersForCommand = loadBalancersToApply.size(); LoadBalancerTO[] loadBalancersForCommand = loadBalancersToApply.toArray(new LoadBalancerTO[numLoadBalancersForCommand]); @@ -884,6 +902,27 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase throw new ResourceUnavailableException(msg, DataCenter.class, network.getDataCenterId()); } } + } catch (Exception ex) { + if (externalLoadBalancerIsInline) { + s_logger.error("Rollbacking static nat operation of inline mode load balancing due to error on applying LB rules!"); + String existedGuestIp = loadBalancersToApply.get(0).getSrcIp(); + // Rollback static NAT operation in current session + for (int i = 0; i < loadBalancingRules.size(); i++) { + LoadBalancingRule rule = loadBalancingRules.get(i); + MappingState state = mappingStates.get(i); + boolean revoke; + if (state == MappingState.Create) { + revoke = true; + } else if (state == MappingState.Remove) { + revoke = false; + } else { + continue; + } + getLoadBalancingIpNic(zone, network, rule.getSourceIpAddressId(), revoke, existedGuestIp); + } + } + throw new ResourceUnavailableException(ex.getMessage(), DataCenter.class, network.getDataCenterId()); + } return true; } @@ -900,12 +939,18 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase HostVO externalLoadBalancer = null; if (add) { - ExternalLoadBalancerDeviceVO lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); + ExternalLoadBalancerDeviceVO lbDeviceVO = null; + // on restart network, device could have been allocated already, skip allocation if a device is assigned + lbDeviceVO = getExternalLoadBalancerForNetwork(guestConfig); + if (lbDeviceVO == null) { + // allocate a load balancer device for the network + lbDeviceVO = allocateLoadBalancerForNetwork(guestConfig); if (lbDeviceVO == null) { String msg = "failed to alloacate a external load balancer for the network " + guestConfig.getId(); s_logger.error(msg); throw new InsufficientNetworkCapacityException(msg, DataCenter.class, guestConfig.getDataCenterId()); } + } externalLoadBalancer = _hostDao.findById(lbDeviceVO.getHostId()); s_logger.debug("Allocated external load balancer device:" + lbDeviceVO.getId() + " for the network: " + guestConfig.getId()); } else { @@ -928,6 +973,12 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase Integer networkRate = _networkMgr.getNetworkRate(guestConfig.getId(), null); if (add) { + // on restart network, network could have already been implemented. If already implemented then return + NicVO selfipNic = getPlaceholderNic(guestConfig); + if (selfipNic != null) { + return true; + } + // Acquire a self-ip address from the guest network IP address range selfIp = _networkMgr.acquireGuestIpAddress(guestConfig, null); if (selfIp == null) { @@ -946,7 +997,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase selfIp = selfipNic.getIp4Address(); } - IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, String.valueOf(guestVlanTag), selfIp, guestVlanNetmask, null, networkRate, false); + // It's a hack, using isOneToOneNat field for indicate if it's inline or not + boolean inline = _networkMgr.isNetworkInlineMode(guestConfig); + IpAddressTO ip = new IpAddressTO(guestConfig.getAccountId(), null, add, false, true, String.valueOf(guestVlanTag), selfIp, guestVlanNetmask, null, networkRate, inline); IpAddressTO[] ips = new IpAddressTO[1]; ips[0] = ip; IpAssocCommand cmd = new IpAssocCommand(ips); @@ -954,8 +1007,9 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase if (answer == null || !answer.getResult()) { String action = add ? "implement" : "shutdown"; - String answerDetails = (answer != null) ? answer.getDetails() : "answer was null"; - String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + " due to " + answerDetails; + String answerDetails = (answer != null) ? answer.getDetails() : null; + answerDetails = (answerDetails != null) ? " due to " + answerDetails : ""; + String msg = "External load balancer was unable to " + action + " the guest network on the external load balancer in zone " + zone.getName() + answerDetails; s_logger.error(msg); throw new ResourceUnavailableException(msg, Network.class, guestConfig.getId()); } @@ -1027,4 +1081,25 @@ public abstract class ExternalLoadBalancerDeviceManagerImpl extends AdapterBase return new DeleteHostAnswer(true); } + protected IpDeployer getIpDeployerForInlineMode(Network network) { + //We won't deploy IP, instead the firewall in front of us would do it + List providers = _networkMgr.getProvidersForServiceInNetwork(network, Service.Firewall); + //Only support one provider now + if (providers == null) { + s_logger.error("Cannot find firewall provider for network " + network.getId()); + return null; + } + if (providers.size() != 1) { + s_logger.error("Found " + providers.size() + " firewall provider for network " + network.getId()); + return null; + } + + NetworkElement element = _networkMgr.getElementImplementingProvider(providers.get(0).getName()); + if (!(element instanceof IpDeployer)) { + s_logger.error("The firewall provider for network " + network.getName() + " don't have ability to deploy IP address!"); + return null; + } + s_logger.info("Let " + element.getName() + " handle ip association for " + getName() + " in network " + network.getId()); + return (IpDeployer)element; + } } diff --git a/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java b/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java index 190067b653b..d77352a9614 100644 --- a/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java +++ b/server/src/com/cloud/network/ExternalLoadBalancerDeviceVO.java @@ -16,6 +16,10 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.Identity; +import org.apache.cloudstack.api.InternalIdentity; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; + import java.util.UUID; import javax.persistence.Column; @@ -33,7 +37,7 @@ import javax.persistence.Table; @Entity @Table(name="external_load_balancer_devices") -public class ExternalLoadBalancerDeviceVO { +public class ExternalLoadBalancerDeviceVO implements InternalIdentity, Identity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -66,9 +70,6 @@ public class ExternalLoadBalancerDeviceVO { @Column(name="is_managed") private boolean isManagedDevice; - @Column(name="is_inline") - private boolean isInlineMode; - @Column(name="is_dedicated") private boolean isDedicatedDevice; @@ -92,7 +93,7 @@ public class ExternalLoadBalancerDeviceVO { } public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, - long capacity, boolean dedicated, boolean inline) { + long capacity, boolean dedicated) { this.physicalNetworkId = physicalNetworkId; this.providerName = provider_name; this.deviceName = device_name; @@ -101,7 +102,6 @@ public class ExternalLoadBalancerDeviceVO { this.allocationState = LBDeviceAllocationState.Free; this.capacity = capacity; this.isDedicatedDevice = dedicated; - this.isInlineMode = inline; this.isManagedDevice = false; this.state = LBDeviceState.Enabled; this.uuid = UUID.randomUUID().toString(); @@ -112,8 +112,8 @@ public class ExternalLoadBalancerDeviceVO { } public ExternalLoadBalancerDeviceVO(long hostId, long physicalNetworkId, String provider_name, String device_name, - long capacity, boolean dedicated, boolean inline, boolean managed, long parentHostId) { - this(hostId, physicalNetworkId, provider_name, device_name, capacity, dedicated, inline); + long capacity, boolean dedicated, boolean managed, long parentHostId) { + this(hostId, physicalNetworkId, provider_name, device_name, capacity, dedicated); this.isManagedDevice = managed; this.parentHostId = parentHostId; } @@ -182,14 +182,6 @@ public class ExternalLoadBalancerDeviceVO { this.isManagedDevice = managed; } - public boolean getIsInLineMode () { - return isInlineMode; - } - - public void setIsInlineMode(boolean inline) { - this.isInlineMode = inline; - } - public boolean getIsDedicatedDevice() { return isDedicatedDevice; } diff --git a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java index 44c2af81066..93e0ef6d01d 100755 --- a/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java +++ b/server/src/com/cloud/network/ExternalNetworkDeviceManagerImpl.java @@ -27,28 +27,30 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.network.AddNetworkDeviceCmd; +import org.apache.cloudstack.api.command.admin.network.ListNetworkDeviceCmd; +import org.apache.cloudstack.network.ExternalNetworkDeviceManager; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; -import com.cloud.api.ApiConstants; -import com.cloud.api.IdentityService; -import com.cloud.api.PlugService; -import com.cloud.api.commands.AddNetworkDeviceCmd; -import com.cloud.api.commands.DeleteNetworkDeviceCmd; -import com.cloud.api.commands.ListNetworkDeviceCmd; +import com.cloud.api.ApiDBUtils; + +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.IdentityService; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkDeviceCmd; import com.cloud.baremetal.ExternalDhcpManager; import com.cloud.baremetal.PxeServerManager; import com.cloud.baremetal.PxeServerProfile; import com.cloud.baremetal.PxeServerManager.PxeServerType; import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenter; +import com.cloud.dc.Pod; import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; import com.cloud.host.Host; import com.cloud.host.HostVO; -import com.cloud.host.Host.Type; import com.cloud.host.dao.HostDao; -import com.cloud.host.dao.HostDetailsDao; import com.cloud.network.dao.ExternalFirewallDeviceDao; import com.cloud.network.dao.ExternalLoadBalancerDeviceDao; import com.cloud.network.dao.IPAddressDao; @@ -62,9 +64,8 @@ import com.cloud.network.dao.PhysicalNetworkServiceProviderDao; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.offerings.dao.NetworkOfferingDao; -import com.cloud.resource.ServerResource; import com.cloud.server.ManagementServer; -import com.cloud.server.api.response.NetworkDeviceResponse; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; import com.cloud.server.api.response.NwDeviceDhcpResponse; import com.cloud.server.api.response.PxePingResponse; import com.cloud.user.AccountManager; @@ -194,8 +195,16 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa String pxeType = host.getDetail("type"); if (pxeType.equalsIgnoreCase(PxeServerType.PING.getName())) { PxePingResponse r = new PxePingResponse(); - r.setZoneId(host.getDataCenterId()); - r.setPodId(host.getPodId()); + DataCenter zone = ApiDBUtils.findZoneById(host.getDataCenterId()); + if (zone != null) { + r.setZoneId(zone.getUuid()); + } + if (host.getPodId() != null) { + Pod pod = ApiDBUtils.findPodById(host.getPodId()); + if (pod != null) { + r.setPodId(pod.getUuid()); + } + } r.setUrl(host.getPrivateIpAddress()); r.setType(pxeType); r.setStorageServerIp(host.getDetail("storageServer")); @@ -209,7 +218,7 @@ public class ExternalNetworkDeviceManagerImpl implements ExternalNetworkDeviceMa throw new CloudRuntimeException("Unsupported network device type:" + host.getType()); } - response.setId(device.getId()); + response.setId(device.getUuid()); return response; } diff --git a/server/src/com/cloud/network/FirewallRulesCidrsVO.java b/server/src/com/cloud/network/FirewallRulesCidrsVO.java index a123aeeb840..0048dce8dab 100644 --- a/server/src/com/cloud/network/FirewallRulesCidrsVO.java +++ b/server/src/com/cloud/network/FirewallRulesCidrsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("firewall_rules_cidrs")) -public class FirewallRulesCidrsVO { +public class FirewallRulesCidrsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -44,7 +46,7 @@ public class FirewallRulesCidrsVO { this.sourceCidrList = sourceCidrList; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/network/IPAddressVO.java b/server/src/com/cloud/network/IPAddressVO.java index 9be624e6554..c17d68f0787 100644 --- a/server/src/com/cloud/network/IPAddressVO.java +++ b/server/src/com/cloud/network/IPAddressVO.java @@ -5,7 +5,7 @@ // 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, @@ -31,8 +31,9 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.net.Ip; +import org.apache.cloudstack.api.InternalIdentity; /** * A bean representing a public IP Address @@ -40,12 +41,12 @@ import com.cloud.utils.net.Ip; */ @Entity @Table(name=("user_ip_address")) -public class IPAddressVO implements IpAddress, Identity { +public class IPAddressVO implements IpAddress { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="account_id") private Long allocatedToAccountId = null; @@ -59,59 +60,59 @@ public class IPAddressVO implements IpAddress, Identity { @Column(name="data_center_id", updatable=false) private long dataCenterId; - + @Column(name="source_nat") private boolean sourceNat; @Column(name="allocated") @Temporal(value=TemporalType.TIMESTAMP) private Date allocatedTime; - + @Column(name="vlan_db_id") private long vlanId; @Column(name="one_to_one_nat") private boolean oneToOneNat; - + @Column(name="vm_id") private Long associatedWithVmId; - + @Column(name="state") private State state; - + @Column(name="mac_address") private long macAddress; - + @Column(name="source_network_id") private Long sourceNetworkId; - + @Column(name="network_id") private Long associatedWithNetworkId; - + @Column(name="uuid") private String uuid; - + @Column(name="physical_network_id") private Long physicalNetworkId; - + @Column(name="is_system") private boolean system; - + @Column(name="account_id") @Transient private Long accountId = null; - + @Transient @Column(name="domain_id") private Long domainId = null; - + @Column(name="vpc_id") private Long vpcId; - + protected IPAddressVO() { this.uuid = UUID.randomUUID().toString(); } - + @Override public boolean readyToUse() { return state == State.Allocated; @@ -129,36 +130,36 @@ public class IPAddressVO implements IpAddress, Identity { this.macAddress = macAddress; this.uuid = UUID.randomUUID().toString(); } - + public long getMacAddress() { return macAddress; } - + @Override public long getDataCenterId() { - return dataCenterId; + return dataCenterId; } @Override public Ip getAddress() { return address; } - + @Override public Long getAllocatedToAccountId() { return allocatedToAccountId; } - + @Override public Long getAllocatedInDomainId() { return allocatedInDomainId; } - + @Override public Long getAssociatedWithNetworkId() { return associatedWithNetworkId; } - + public void setAssociatedWithNetworkId(Long networkId) { this.associatedWithNetworkId = networkId; } @@ -171,7 +172,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setAssociatedWithVmId(Long associatedWithVmId) { this.associatedWithVmId = associatedWithVmId; } - + @Override public Date getAllocatedTime() { return allocatedTime; @@ -188,7 +189,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setSourceNat(boolean sourceNat) { this.sourceNat = sourceNat; } - + @Override public boolean isSourceNat() { return sourceNat; @@ -197,12 +198,12 @@ public class IPAddressVO implements IpAddress, Identity { public void setAllocatedTime(Date allocated) { this.allocatedTime = allocated; } - + @Override public long getVlanId() { return this.vlanId; } - + public void setVlanId(long vlanDbId) { this.vlanId = vlanDbId; } @@ -215,31 +216,31 @@ public class IPAddressVO implements IpAddress, Identity { public void setOneToOneNat(boolean oneToOneNat) { this.oneToOneNat = oneToOneNat; } - + @Override public long getDomainId() { return allocatedInDomainId == null ? -1 : allocatedInDomainId; } - + @Override public long getAccountId() { return allocatedToAccountId == null ? -1 : allocatedToAccountId; } - + @Override public State getState() { return state; } - + public void setState(State state) { this.state = state; } - + @Override public String toString() { return new StringBuilder("Ip[").append(address).append("-").append(dataCenterId).append("]").toString(); } - + @Override public long getId() { return id; @@ -252,12 +253,12 @@ public class IPAddressVO implements IpAddress, Identity { public void setSourceNetworkId(Long sourceNetworkId) { this.sourceNetworkId = sourceNetworkId; } - + @Override public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -269,7 +270,7 @@ public class IPAddressVO implements IpAddress, Identity { public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; } - + @Override public boolean getSystem() { return system; @@ -288,4 +289,4 @@ public class IPAddressVO implements IpAddress, Identity { public void setVpcId(Long vpcId) { this.vpcId = vpcId; } -} +} diff --git a/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java b/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java index ade6dae9bb6..297aa2d26e4 100644 --- a/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java +++ b/server/src/com/cloud/network/InlineLoadBalancerNicMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,15 +27,12 @@ import javax.persistence.Table; @Entity @Table(name=("inline_load_balancer_nic_map")) -public class InlineLoadBalancerNicMapVO { +public class InlineLoadBalancerNicMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") private long id; - @Column(name="load_balancer_id") - private long loadBalancerId; - @Column(name="public_ip_address") private String publicIpAddress; @@ -42,8 +41,7 @@ public class InlineLoadBalancerNicMapVO { public InlineLoadBalancerNicMapVO() { } - public InlineLoadBalancerNicMapVO(long loadBalancerId, String publicIpAddress, long nicId) { - this.loadBalancerId = loadBalancerId; + public InlineLoadBalancerNicMapVO(String publicIpAddress, long nicId) { this.publicIpAddress = publicIpAddress; this.nicId = nicId; } @@ -52,10 +50,6 @@ public class InlineLoadBalancerNicMapVO { return id; } - public long getLoadBalancerId() { - return loadBalancerId; - } - public String getPublicIpAddress() { return publicIpAddress; } diff --git a/server/src/com/cloud/network/LBStickinessPolicyVO.java b/server/src/com/cloud/network/LBStickinessPolicyVO.java index 30590cdfbfa..9a629ce017c 100644 --- a/server/src/com/cloud/network/LBStickinessPolicyVO.java +++ b/server/src/com/cloud/network/LBStickinessPolicyVO.java @@ -32,6 +32,7 @@ import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import com.cloud.network.rules.StickinessPolicy; import com.cloud.utils.Pair; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = ("load_balancer_stickiness_policies")) diff --git a/server/src/com/cloud/network/LoadBalancerVMMapVO.java b/server/src/com/cloud/network/LoadBalancerVMMapVO.java index e64085d027a..3cc66dc9011 100644 --- a/server/src/com/cloud/network/LoadBalancerVMMapVO.java +++ b/server/src/com/cloud/network/LoadBalancerVMMapVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -25,7 +27,7 @@ import javax.persistence.Table; @Entity @Table(name=("load_balancer_vm_map")) -public class LoadBalancerVMMapVO { +public class LoadBalancerVMMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/NetworkAccountVO.java b/server/src/com/cloud/network/NetworkAccountVO.java index b04da8d1c84..b51e78cce4c 100644 --- a/server/src/com/cloud/network/NetworkAccountVO.java +++ b/server/src/com/cloud/network/NetworkAccountVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.user.OwnedBy; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_network_ref") -public class NetworkAccountVO implements OwnedBy { +public class NetworkAccountVO implements OwnedBy, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; @@ -49,7 +50,12 @@ public class NetworkAccountVO implements OwnedBy { this.accountId = accountId; this.owner = owner; } - + + @Override + public long getId() { + return id; + } + @Override public long getAccountId() { return accountId; diff --git a/server/src/com/cloud/network/NetworkDomainVO.java b/server/src/com/cloud/network/NetworkDomainVO.java index bf32d1a8539..9b79887f7a7 100644 --- a/server/src/com/cloud/network/NetworkDomainVO.java +++ b/server/src/com/cloud/network/NetworkDomainVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.domain.PartOf; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="domain_network_ref") -public class NetworkDomainVO implements PartOf { +public class NetworkDomainVO implements PartOf, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; @@ -49,7 +50,12 @@ public class NetworkDomainVO implements PartOf { this.domainId = domainId; this.subdomainAccess = subdomainAccess; } - + + @Override + public long getId() { + return id; + } + @Override public long getDomainId() { return domainId; diff --git a/server/src/com/cloud/network/NetworkExternalFirewallVO.java b/server/src/com/cloud/network/NetworkExternalFirewallVO.java index 37441174f29..800e737137d 100644 --- a/server/src/com/cloud/network/NetworkExternalFirewallVO.java +++ b/server/src/com/cloud/network/NetworkExternalFirewallVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkExternalFirewallVO contains information on the networks that are using external firewall @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name="network_external_firewall_device_map") -public class NetworkExternalFirewallVO { +public class NetworkExternalFirewallVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java b/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java index f3ff1c06f49..17f9ffd2fee 100644 --- a/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java +++ b/server/src/com/cloud/network/NetworkExternalLoadBalancerVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkExternalLoadBalancerVO contains mapping of a network and the external load balancer device id assigned to the network @@ -34,7 +35,7 @@ import com.cloud.utils.db.GenericDao; @Entity @Table(name="network_external_lb_device_map") -public class NetworkExternalLoadBalancerVO { +public class NetworkExternalLoadBalancerVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/NetworkManager.java b/server/src/com/cloud/network/NetworkManager.java index 4124b19d84b..0ca28f889ba 100755 --- a/server/src/com/cloud/network/NetworkManager.java +++ b/server/src/com/cloud/network/NetworkManager.java @@ -21,7 +21,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan; import com.cloud.dc.Vlan.VlanType; @@ -40,9 +40,11 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; 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.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; @@ -189,6 +191,8 @@ public interface NetworkManager extends NetworkService { UserDataServiceProvider getPasswordResetProvider(Network network); + UserDataServiceProvider getUserDataUpdateProvider(Network network); + boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId); Map getNetworkServiceCapabilities(long networkId, Service service); @@ -480,4 +484,12 @@ public interface NetworkManager extends NetworkService { */ int getNetworkLockTimeout(); + List getProvidersForServiceInNetwork(Network network, Service service); + + StaticNatServiceProvider getStaticNatProviderForNetwork(Network network); + boolean isNetworkInlineMode(Network network); + + int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state); + + LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network); } diff --git a/server/src/com/cloud/network/NetworkManagerImpl.java b/server/src/com/cloud/network/NetworkManagerImpl.java index 085b1c9356d..5b8109ff6db 100755 --- a/server/src/com/cloud/network/NetworkManagerImpl.java +++ b/server/src/com/cloud/network/NetworkManagerImpl.java @@ -41,33 +41,28 @@ import javax.ejb.Local; import javax.inject.Inject; 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; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.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.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import com.cloud.api.ApiDBUtils; + +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; 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 +85,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 +103,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 +137,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; @@ -192,14 +146,8 @@ import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; 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 +169,8 @@ import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.VMInstanceDao; import edu.emory.mathcs.backport.java.util.Collections; +import java.util.*; + /** * NetworkManagerImpl implements NetworkManager. */ @@ -430,13 +380,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", Pod.class, podId); // for now, we hardcode the table names, but we should ideally do a lookup for the tablename from the VO object. - ex.addProxyObject("Pod", podId, "podId"); + ex.addProxyObject(ApiDBUtils.findPodById(podId).getUuid()); throw ex; } s_logger.warn(errorMessage.toString()); InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Insufficient address capacity", DataCenter.class, dcId); - ex.addProxyObject("data_center", dcId, "dcId"); + ex.addProxyObject(ApiDBUtils.findZoneById(dcId).getUuid()); throw ex; } @@ -828,6 +778,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean canIpsUseOffering(List publicIps, long offeringId) { Map> ipToServices = getIpToServices(publicIps, false, true); Map> serviceToProviders = getNetworkOfferingServiceProvidersMap(offeringId); + NetworkOfferingVO offering = _networkOfferingDao.findById(offeringId); + //For inline mode checking, using firewall provider for LB instead, because public ip would apply on firewall provider + if (offering.isInline()) { + Provider firewallProvider = null; + if (serviceToProviders.containsKey(Service.Firewall)) { + firewallProvider = (Provider)serviceToProviders.get(Service.Firewall).toArray()[0]; + } + Set p = new HashSet(); + p.add(firewallProvider); + serviceToProviders.remove(Service.Lb); + serviceToProviders.put(Service.Lb, p); + } for (PublicIp ip : ipToServices.keySet()) { Set services = ipToServices.get(ip); Provider provider = null; @@ -873,9 +835,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterException("There is no new provider for IP " + publicIp.getAddress() + " of service " + service.getName() + "!"); } Provider newProvider = (Provider) newProviders.toArray()[0]; - if (!oldProvider.equals(newProvider)) { + Network network = _networksDao.findById(networkId); + NetworkElement oldElement = getElementImplementingProvider(oldProvider.getName()); + NetworkElement newElement = getElementImplementingProvider(newProvider.getName()); + if (oldElement instanceof IpDeployingRequester && newElement instanceof IpDeployingRequester) { + IpDeployer oldIpDeployer = ((IpDeployingRequester)oldElement).getIpDeployer(network); + IpDeployer newIpDeployer = ((IpDeployingRequester)newElement).getIpDeployer(network); + if (!oldIpDeployer.getProvider().getName().equals(newIpDeployer.getProvider().getName())) { throw new InvalidParameterException("There would be multiple providers for IP " + publicIp.getAddress() + "!"); } + } else { + throw new InvalidParameterException("Ip cannot be applied for new provider!"); + } return true; } @@ -946,21 +917,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } IpDeployer deployer = null; NetworkElement element = getElementImplementingProvider(provider.getName()); - if (element instanceof SourceNatServiceProvider) { - deployer = ((SourceNatServiceProvider) element).getIpDeployer(network); - } else if (element instanceof StaticNatServiceProvider) { - deployer = ((StaticNatServiceProvider) element).getIpDeployer(network); - } else if (element instanceof LoadBalancingServiceProvider) { - deployer = ((LoadBalancingServiceProvider) element).getIpDeployer(network); - } else if (element instanceof PortForwardingServiceProvider) { - deployer = ((PortForwardingServiceProvider) element).getIpDeployer(network); - } else if (element instanceof RemoteAccessVPNServiceProvider) { - deployer = ((RemoteAccessVPNServiceProvider) element).getIpDeployer(network); - } else if (element instanceof ConnectivityProvider) { + if (element instanceof ConnectivityProvider) { // Nothing to do s_logger.debug("ConnectivityProvider " + element.getClass().getSimpleName() + " has no ip associations"); continue; - } else { + } + + if (!(element instanceof IpDeployingRequester)) { + throw new CloudRuntimeException("Element " + element + " is not a IpDeployingRequester!"); + } + deployer = ((IpDeployingRequester)element).getIpDeployer(network); + if (deployer == null) { throw new CloudRuntimeException("Fail to get ip deployer for element: " + element); } Set services = new HashSet(); @@ -1020,6 +987,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 { @@ -1030,11 +1029,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag 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 { @@ -1055,7 +1054,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) { @@ -1080,7 +1079,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag InsufficientAddressCapacityException ex = new InsufficientAddressCapacityException ("Unable to find available public IP addresses", DataCenter.class, zone.getId()); - ex.addProxyObject("data_center", zone.getId(), "zoneId"); + ex.addProxyObject(ApiDBUtils.findZoneById(zone.getId()).getUuid()); throw ex; } UserContext.current().setEventDetails("Ip Id: " + ip.getId()); @@ -1135,7 +1134,22 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag IPAddressVO ipToAssoc = _ipAddressDao.findById(ipId); if (ipToAssoc != null) { + 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); @@ -1149,7 +1163,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag Network network = _networksDao.findById(networkId); if (network != null) { - _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); + _accountMgr.checkAccess(owner, AccessType.UseNetwork, false, network); } else { s_logger.debug("Unable to find ip address by id: " + ipId); return null; @@ -1159,20 +1173,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()) { + // 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"); @@ -1932,7 +1949,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag if (network == null) { // see NetworkVO.java ConcurrentOperationException ex = new ConcurrentOperationException("Unable to acquire network configuration"); - ex.addProxyObject("networks", networkId, "networkId"); + ex.addProxyObject(ApiDBUtils.findNetworkById(networkId).getUuid()); throw ex; } @@ -1943,12 +1960,21 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag try { NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, 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); } @@ -1992,18 +2018,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) 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) { @@ -2034,9 +2067,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"); @@ -2051,7 +2086,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Failed to re-program the network as a part of network " + network + " implement"); // see DataCenterVO.java ResourceUnavailableException ex = new ResourceUnavailableException("Unable to apply network rules as a part of network " + network + " implement", DataCenter.class, network.getDataCenterId()); - ex.addProxyObject("data_center", network.getDataCenterId(), "dataCenterId"); + ex.addProxyObject(ApiDBUtils.findZoneById(network.getDataCenterId()).getUuid()); throw ex; } } @@ -2101,7 +2136,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag List nics = _nicDao.listByVmId(vmProfile.getId()); // we have to implement default nics first - to ensure that default network elements start up first in multiple - // nics case)(need for setting DNS on Dhcp to domR's Ip4 address) + //nics case + // (need for setting DNS on Dhcp to domR's Ip4 address) Collections.sort(nics, new Comparator() { @Override @@ -2200,6 +2236,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override + @DB public void release(VirtualMachineProfile vmProfile, boolean forced) throws ConcurrentOperationException, ResourceUnavailableException { List nics = _nicDao.listByVmId(vmProfile.getId()); @@ -2207,19 +2244,32 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag releaseNic(vmProfile, nic); } } + + @Override + @DB public void releaseNic(VirtualMachineProfile vmProfile, Nic nic) throws ConcurrentOperationException, ResourceUnavailableException { NicVO nicVO = _nicDao.findById(nic.getId()); releaseNic(vmProfile, nicVO); } - - protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nic) + @DB + protected void releaseNic(VirtualMachineProfile vmProfile, NicVO nicVO) throws ConcurrentOperationException, ResourceUnavailableException { - NetworkVO network = _networksDao.findById(nic.getNetworkId()); - if (nic.getState() == Nic.State.Reserved || nic.getState() == Nic.State.Reserving) { + //lock the nic + Transaction txn = Transaction.currentTxn(); + txn.start(); + + NicVO nic = _nicDao.lockRow(nicVO.getId(), true); + if (nic == null) { + throw new ConcurrentOperationException("Unable to acquire lock on nic " + nic); + } + Nic.State originalState = nic.getState(); + NetworkVO network = _networksDao.findById(nicVO.getNetworkId()); + + if (originalState == Nic.State.Reserved || originalState == Nic.State.Reserving) { if (nic.getReservationStrategy() == Nic.ReservationStrategy.Start) { NetworkGuru guru = Adapters.getAdapterByName(_networkGurus, network.getGuruName()); nic.setState(Nic.State.Releasing); @@ -2235,6 +2285,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag _nicDao.update(nic.getId(), nic); } } + //commit the transaction before proceeding releasing nic profile on the network elements + txn.commit(); + // Perform release on network elements for (NetworkElement element : _networkElements) { if (s_logger.isDebugEnabled()) { @@ -2248,6 +2301,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } else { nic.setState(Nic.State.Allocated); updateNic(nic, network.getId(), -1); + txn.commit(); } } } @@ -2457,6 +2511,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") @@ -2650,9 +2780,17 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if (cidr != null && networkOfferingIsConfiguredForExternalNetworking(networkOfferingId)) { + 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 @@ -2734,7 +2872,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return null; } - boolean updateResourceCount = (!ntwkOff.getSpecifyVlan() && aclType == ACLType.Account); + boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, aclType); //check resource limits if (updateResourceCount) { _resourceLimitMgr.checkResourceLimit(owner, ResourceType.network); @@ -2836,10 +2974,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); } } } @@ -3018,7 +3157,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - if (!_accountMgr.isAdmin(caller.getType()) || (!listAll && (projectId != null && projectId != -1 && domainId == null))) { + if (!_accountMgr.isAdmin(caller.getType()) || (!listAll && (projectId != null && projectId.longValue() != -1 && domainId == null))) { permittedAccounts.add(caller.getId()); domainId = caller.getDomainId(); } @@ -3026,8 +3165,10 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // set project information boolean skipProjectNetworks = true; if (projectId != null) { - if (projectId == -1) { + if (projectId.longValue() == -1) { + if (!_accountMgr.isAdmin(caller.getType())) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); + } } else { permittedAccounts.clear(); Project project = _projectMgr.getProject(projectId); @@ -3425,7 +3566,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag applyProfileToNetwork(network, profile); + 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); @@ -3558,7 +3705,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.debug("Sending destroy to " + element); } - if (!element.destroy(network)) { + if (!element.destroy(network, context)) { success = false; s_logger.warn("Unable to complete destroy of the network: failed to destroy network element " + element.getName()); } @@ -3594,6 +3741,12 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag network.setState(Network.State.Destroy); _networksDao.update(network.getId(), network); _networksDao.remove(network.getId()); + + NetworkOffering ntwkOff = _configMgr.getNetworkOffering(network.getNetworkOfferingId()); + boolean updateResourceCount = resourceCountNeedsUpdate(ntwkOff, network.getAclType()); + if (updateResourceCount) { + _resourceLimitMgr.decrementResourceCount(owner.getId(), ResourceType.network); + } txn.commit(); } } @@ -3601,6 +3754,11 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return success; } + private boolean resourceCountNeedsUpdate(NetworkOffering ntwkOff, ACLType aclType) { + boolean updateResourceCount = (!ntwkOff.getSpecifyVlan() && aclType == ACLType.Account); + return updateResourceCount; + } + protected boolean deleteVlansInNetwork(long networkId, long userId, Account callerAccount) { //cleanup Public vlans @@ -3629,25 +3787,23 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag public boolean validateRule(FirewallRule rule) { Network network = _networksDao.findById(rule.getNetworkId()); Purpose purpose = rule.getPurpose(); - for (NetworkElement ne : _networkElements) { - boolean validated; switch (purpose) { case LoadBalancing: - if (!(ne instanceof LoadBalancingServiceProvider)) { - continue; - } - validated = ((LoadBalancingServiceProvider) ne).validateLBRule(network, (LoadBalancingRule) rule); - if (!validated) + LoadBalancingServiceProvider ne = getLoadBalancingProviderForNetwork(network); + if (!ne.validateLBRule(network, (LoadBalancingRule) rule)) { return false; + } break; default: s_logger.debug("Unable to validate network rules for purpose: " + purpose.toString()); - validated = false; - } } return true; } + protected boolean applyLbRules(Network network, List rules, LoadBalancingServiceProvider element) throws ResourceUnavailableException { + return element.applyLBRules(network, rules); + } + @Override /* The rules here is only the same kind of rule, e.g. all load balancing rules or all port forwarding rules */ public boolean applyRules(List rules, boolean continueOnError) throws ResourceUnavailableException { @@ -3674,47 +3830,55 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // the network so as to ensure IP is associated before applying rules (in add state) applyIpAssociations(network, false, continueOnError, publicIps); - for (NetworkElement ne : _networkElements) { - Provider provider = Network.Provider.getProvider(ne.getName()); - if (provider == null) { - if (ne.getName().equalsIgnoreCase("Ovs") || ne.getName().equalsIgnoreCase("BareMetal") - || ne.getName().equalsIgnoreCase("CiscoNexus1000vVSM")) { - continue; - } - throw new CloudRuntimeException("Unable to identify the provider by name " + ne.getName()); + Service service = null; + switch (purpose) { + case LoadBalancing: + service = Service.Lb; + break; + case PortForwarding: + service = Service.PortForwarding; + break; + case StaticNat: + case Firewall: + service = Service.Firewall; + break; + case NetworkACL: + service = Service.NetworkACL; + break; + default: + break; } + + if (service != null) { + List providers = getProvidersForServiceInNetwork(network, service); + if (providers == null || providers.size() != 1) { + // FIXME: If there is a service not made available by network offering, then rule should not get created + // in first place. For now error out during the apply rules. + String msg = "Cannot find the " + service.getName() + " provider for network " + network.getId(); + s_logger.error(msg); + throw new CloudRuntimeException(msg); + } + NetworkElement ne = getElementImplementingProvider(providers.get(0).getName()); try { boolean handled; switch (purpose) { case LoadBalancing: - boolean isLbProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Lb, provider); - if (!(ne instanceof LoadBalancingServiceProvider && isLbProvider)) { - continue; - } - handled = ((LoadBalancingServiceProvider) ne).applyLBRules(network, (List) rules); + assert ne instanceof LoadBalancingServiceProvider; + handled = applyLbRules(network, (List)rules, (LoadBalancingServiceProvider) ne); break; case PortForwarding: - boolean isPfProvider = isProviderSupportServiceInNetwork(network.getId(), Service.PortForwarding, provider); - if (!(ne instanceof PortForwardingServiceProvider && isPfProvider)) { - continue; - } + assert ne instanceof PortForwardingServiceProvider; handled = ((PortForwardingServiceProvider) ne).applyPFRules(network, (List) rules); break; case StaticNat: /* It's firewall rule for static nat, not static nat rule */ /* Fall through */ case Firewall: - boolean isFirewallProvider = isProviderSupportServiceInNetwork(network.getId(), Service.Firewall, provider); - if (!(ne instanceof FirewallServiceProvider && isFirewallProvider)) { - continue; - } + assert ne instanceof FirewallServiceProvider; handled = ((FirewallServiceProvider) ne).applyFWRules(network, rules); break; case NetworkACL: - boolean isNetworkACLProvider = isProviderSupportServiceInNetwork(network.getId(), Service.NetworkACL, provider); - if (!(ne instanceof NetworkACLServiceProvider && isNetworkACLProvider)) { - continue; - } + assert ne instanceof NetworkACLServiceProvider; handled = ((NetworkACLServiceProvider) ne).applyNetworkACLs(network, rules); break; default: @@ -3729,6 +3893,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag s_logger.warn("Problems with " + ne.getName() + " but pushing on", e); success = false; } + } else { + s_logger.debug("Unable to handle network rules for purpose: " + purpose.toString()); + success = false; } // if all the rules configured on public IP are revoked then dis-associate IP with network service provider @@ -3814,10 +3981,13 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw new InvalidParameterValueException("Network is not in the right state to be restarted. Correct states are: " + Network.State.Implemented + ", " + Network.State.Setup); } - // don't allow clenaup=true for the network in Basic zone - DataCenter zone = _configMgr.getZone(network.getDataCenterId()); - if (zone.getNetworkType() == NetworkType.Basic && cleanup) { - throw new InvalidParameterValueException("Cleanup can't be true when restart network in Basic zone"); + if (network.getBroadcastDomainType() == BroadcastDomainType.Lswitch ) { + /** + * Unable to restart these networks now. + * TODO Restarting a SDN based network requires updating the nics and the configuration + * in the controller. This requires a non-trivial rewrite of the restart procedure. + */ + throw new InvalidParameterException("Unable to restart a running SDN network."); } _accountMgr.checkAccess(callerAccount, null, true, network); @@ -3864,10 +4034,6 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag ReservationContext context = new ReservationContextImpl(null, null, callerUser, callerAccount); if (cleanup) { - if (network.getGuestType() != GuestType.Isolated) { - s_logger.warn("Only support clean up network for isolated network!"); - return false; - } // shutdown the network s_logger.debug("Shutting down the network id=" + networkId + " as a part of network restart"); @@ -4304,6 +4470,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } + @Override public UserDataServiceProvider getPasswordResetProvider(Network network) { String passwordProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.UserData); @@ -4316,6 +4483,18 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return (UserDataServiceProvider)getElementImplementingProvider(passwordProvider); } + @Override + public UserDataServiceProvider getUserDataUpdateProvider(Network network) { + String userDataProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.UserData); + + if (userDataProvider == null) { + s_logger.debug("Network " + network + " doesn't support service " + Service.UserData.getName()); + return null; + } + + return (UserDataServiceProvider)getElementImplementingProvider(userDataProvider); + } + @Override public boolean networkIsConfiguredForExternalNetworking(long zoneId, long networkId) { boolean netscalerInNetwork = isProviderForNetwork(Network.Provider.Netscaler, networkId); @@ -4329,16 +4508,27 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } } - 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) { + public boolean providersConfiguredForExternalNetworking(Collection providers) { + for(String providerStr : providers){ + Provider provider = Network.Provider.getProvider(providerStr); + if(provider.isExternal()){ return true; - } else { + } + } 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 @@ -4390,7 +4580,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // the code would be triggered s_logger.debug("Cleaning up remote access vpns as a part of public IP id=" + ipId + " release..."); try { - _vpnMgr.destroyRemoteAccessVpn(ipId); + _vpnMgr.destroyRemoteAccessVpn(ipId, caller); } catch (ResourceUnavailableException e) { s_logger.warn("Unable to destroy remote access vpn for ip id=" + ipId + " as a part of ip release", e); success = false; @@ -4423,18 +4613,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; } @@ -4613,9 +4792,13 @@ 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("Can't guarantee guest network CIDR is unchanged after updating network!"); + throw new InvalidParameterValueException("Updating network failed since guest CIDR needs to be changed!"); } if (changeCidr) { if (!checkForNonStoppedVmInNetwork(network.getId())) { @@ -4717,6 +4900,9 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag // log assign usage events for new offering List nics = _nicDao.listByNetworkId(networkId); for (NicVO nic : nics) { + if (nic.getReservationStrategy() == Nic.ReservationStrategy.PlaceHolder) { + continue; + } long vmId = nic.getInstanceId(); VMInstanceVO vm = _vmDao.findById(vmId); if (vm == null) { @@ -4933,24 +5119,16 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag applyIpAssociations(network, false, continueOnError, publicIps); // get provider - String staticNatProvider = _ntwkSrvcDao.getProviderForServiceInNetwork(network.getId(), Service.StaticNat); - - for (NetworkElement ne : _networkElements) { + StaticNatServiceProvider element = getStaticNatProviderForNetwork(network); try { - if (!(ne instanceof StaticNatServiceProvider && ne.getName().equalsIgnoreCase(staticNatProvider))) { - continue; - } - - boolean handled = ((StaticNatServiceProvider) ne).applyStaticNats(network, staticNats); - s_logger.debug("Static Nat for network " + network.getId() + " were " + (handled ? "" : " not") + " handled by " + ne.getName()); + success = element.applyStaticNats(network, staticNats); } catch (ResourceUnavailableException e) { if (!continueOnError) { throw e; } - s_logger.warn("Problems with " + ne.getName() + " but pushing on", e); + s_logger.warn("Problems with " + element.getName() + " but pushing on", e); success = false; } - } // For revoked static nat IP, set the vm_id to null, indicate it should be revoked for (StaticNat staticNat : staticNats) { @@ -5267,7 +5445,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { + public Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { Filter searchFilter = new Filter(PhysicalNetworkVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchCriteria sc = _physicalNetworkDao.createSearchCriteria(); @@ -5283,7 +5461,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); } - return _physicalNetworkDao.search(sc, searchFilter); + Pair, Integer> result = _physicalNetworkDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -5733,7 +5912,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { + public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, + String name, String state, Long startIndex, Long pageSize) { Filter searchFilter = new Filter(PhysicalNetworkServiceProviderVO.class, "id", false, startIndex, pageSize); SearchBuilder sb = _pNSPDao.createSearchBuilder(); @@ -5751,7 +5931,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag sc.addAnd("state", Op.EQ, state); } - return _pNSPDao.search(sc, searchFilter); + Pair, Integer> result = _pNSPDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -6345,7 +6526,7 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag } @Override - public List listTrafficTypes(Long physicalNetworkId) { + public Pair, Integer> listTrafficTypes(Long physicalNetworkId) { PhysicalNetworkVO network = _physicalNetworkDao.findById(physicalNetworkId); if (network == null) { InvalidParameterValueException ex = new InvalidParameterValueException("Physical Network with specified id doesn't exist in the system"); @@ -6353,7 +6534,8 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag throw ex; } - return _pNTrafficTypeDao.listBy(physicalNetworkId); + Pair, Integer> result = _pNTrafficTypeDao.listAndCountBy(physicalNetworkId); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -7370,4 +7552,56 @@ public class NetworkManagerImpl implements NetworkManager, NetworkService, Manag return _networkLockTimeout; } + @Override + public List getProvidersForServiceInNetwork(Network network, Service service) { + Map> service2ProviderMap = getServiceProvidersMap(network.getId()); + if (service2ProviderMap.get(service) != null) { + List providers = new ArrayList(service2ProviderMap.get(service)); + return providers; + } + return null; + } + + protected NetworkElement getElementForServiceInNetwork(Network network, Service service) { + List providers = getProvidersForServiceInNetwork(network, service); + //Only support one provider now + if (providers == null) { + s_logger.error("Cannot find " + service.getName() + " provider for network " + network.getId()); + return null; + } + if (providers.size() != 1) { + s_logger.error("Found " + providers.size() + " " + service.getName() + " providers for network!" + network.getId()); + return null; + } + NetworkElement element = getElementImplementingProvider(providers.get(0).getName()); + s_logger.info("Let " + element.getName() + " handle " + service.getName() + " in network " + network.getId()); + return element; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + NetworkElement element = getElementForServiceInNetwork(network, Service.StaticNat); + assert element instanceof StaticNatServiceProvider; + return (StaticNatServiceProvider)element; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + NetworkElement element = getElementForServiceInNetwork(network, Service.Lb); + assert element instanceof LoadBalancingServiceProvider; + return ( LoadBalancingServiceProvider)element; + } + public boolean isNetworkInlineMode(Network network) { + NetworkOfferingVO offering = _networkOfferingDao.findById(network.getNetworkOfferingId()); + return offering.isInline(); + } + + @Override + public int getRuleCountForIp(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state) { + List rules = _firewallDao.listByIpAndPurposeWithState(addressId, purpose, state); + if (rules == null) { + return 0; + } + return rules.size(); + } } diff --git a/server/src/com/cloud/network/NetworkRuleConfigVO.java b/server/src/com/cloud/network/NetworkRuleConfigVO.java index 5a92f4f4d63..bbfae43b222 100644 --- a/server/src/com/cloud/network/NetworkRuleConfigVO.java +++ b/server/src/com/cloud/network/NetworkRuleConfigVO.java @@ -27,10 +27,11 @@ import javax.persistence.Table; import com.cloud.async.AsyncInstanceCreateStatus; import com.google.gson.annotations.Expose; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("network_rule_config")) -public class NetworkRuleConfigVO { +public class NetworkRuleConfigVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -62,7 +63,7 @@ public class NetworkRuleConfigVO { this.protocol = protocol; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/network/NetworkServiceMapVO.java b/server/src/com/cloud/network/NetworkServiceMapVO.java index 6cd9ba6c565..592522d614d 100644 --- a/server/src/com/cloud/network/NetworkServiceMapVO.java +++ b/server/src/com/cloud/network/NetworkServiceMapVO.java @@ -28,10 +28,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="ntwk_service_map") -public class NetworkServiceMapVO { +public class NetworkServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/NetworkUsageManager.java b/server/src/com/cloud/network/NetworkUsageManager.java index 10264b8ba42..3d4577b8199 100644 --- a/server/src/com/cloud/network/NetworkUsageManager.java +++ b/server/src/com/cloud/network/NetworkUsageManager.java @@ -23,7 +23,7 @@ import com.cloud.api.commands.DeleteTrafficMonitorCmd; import com.cloud.api.commands.ListTrafficMonitorsCmd; import com.cloud.host.Host; import com.cloud.host.HostVO; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.utils.component.Manager; public interface NetworkUsageManager extends Manager { diff --git a/server/src/com/cloud/network/NetworkUsageManagerImpl.java b/server/src/com/cloud/network/NetworkUsageManagerImpl.java index d2e5f6c22ce..f129b687a5e 100755 --- a/server/src/com/cloud/network/NetworkUsageManagerImpl.java +++ b/server/src/com/cloud/network/NetworkUsageManagerImpl.java @@ -69,7 +69,7 @@ import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceStateAdapter; import com.cloud.resource.ServerResource; import com.cloud.resource.UnableDeleteHostException; -import com.cloud.server.api.response.TrafficMonitorResponse; +import org.apache.cloudstack.api.response.TrafficMonitorResponse; import com.cloud.usage.UsageIPAddressVO; import com.cloud.user.AccountManager; import com.cloud.user.AccountVO; @@ -110,6 +110,8 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Inject ResourceManager _resourceMgr; ScheduledExecutorService _executor; int _networkStatsInterval; + String _TSinclZones; + String _TSexclZones; protected SearchBuilder AllocatedIpSearch; @Override @@ -150,8 +152,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); @@ -164,6 +166,13 @@ 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; @@ -204,7 +213,7 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta public TrafficMonitorResponse getApiResponse(Host trafficMonitor) { Map tmDetails = _detailsDao.findDetails(trafficMonitor.getId()); TrafficMonitorResponse response = new TrafficMonitorResponse(); - response.setId(trafficMonitor.getId()); + response.setId(trafficMonitor.getUuid()); response.setIpAddress(trafficMonitor.getPrivateIpAddress()); response.setNumRetries(tmDetails.get("numRetries")); response.setTimeout(tmDetails.get("timeout")); @@ -224,6 +233,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; @@ -374,7 +385,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"; @@ -407,7 +418,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"; @@ -534,8 +545,11 @@ public class NetworkUsageManagerImpl implements NetworkUsageManager, ResourceSta @Override public DeleteHostAnswer deleteHost(HostVO host, boolean isForced, boolean isForceDeleteStorage) throws UnableDeleteHostException { - // TODO Auto-generated method stub + if(host.getType() != Host.Type.TrafficMonitor){ return null; } + return new DeleteHostAnswer(true); + } + } diff --git a/server/src/com/cloud/network/NetworkVO.java b/server/src/com/cloud/network/NetworkVO.java index 39dd66e77b0..14b643b29b7 100644 --- a/server/src/com/cloud/network/NetworkVO.java +++ b/server/src/com/cloud/network/NetworkVO.java @@ -5,7 +5,7 @@ // 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, @@ -29,8 +29,7 @@ import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Transient; -import com.cloud.acl.ControlledEntity; -import com.cloud.api.Identity; +import org.apache.cloudstack.acl.ControlledEntity; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.Mode; import com.cloud.network.Networks.TrafficType; @@ -44,7 +43,7 @@ import com.cloud.utils.net.NetUtils; */ @Entity @Table(name="networks") -public class NetworkVO implements Network, Identity { +public class NetworkVO implements Network { @Id @TableGenerator(name="networks_sq", table="sequence", pkColumnName="name", valueColumnName="value", pkColumnValue="networks_seq", allocationSize=1) @Column(name="id") @@ -79,13 +78,13 @@ public class NetworkVO implements Network, Identity { @Column(name="network_offering_id") long networkOfferingId; - + @Column(name="vpc_id") Long vpcId; @Column(name="physical_network_id") Long physicalNetworkId; - + @Column(name="data_center_id") long dataCenterId; @@ -132,24 +131,24 @@ public class NetworkVO implements Network, Identity { @Column(name="reservation_id") String reservationId; - + @Column(name="uuid") String uuid; - + @Column(name="guest_type") @Enumerated(value=EnumType.STRING) Network.GuestType guestType; - + @Column(name="acl_type") @Enumerated(value=EnumType.STRING) ControlledEntity.ACLType aclType; @Column(name="restart_required") boolean restartRequired = false; - + @Column(name="specify_ip_ranges") boolean specifyIpRanges = false; - + public NetworkVO() { this.uuid = UUID.randomUUID().toString(); } @@ -181,8 +180,8 @@ public class NetworkVO implements Network, Identity { this.uuid = UUID.randomUUID().toString(); } - public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, - long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, + public NetworkVO(long id, Network that, long offeringId, String guruName, long domainId, long accountId, + long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, Long physicalNetworkId, ACLType aclType, boolean specifyIpRanges, Long vpcId) { this(id, that.getTrafficType(), that.getMode(), that.getBroadcastDomainType(), offeringId, domainId, accountId, related, name, displayText, networkDomain, guestType, dcId, physicalNetworkId, aclType, specifyIpRanges, vpcId); @@ -215,8 +214,8 @@ public class NetworkVO implements Network, Identity { * @param vpcId TODO * @param dataCenterId */ - public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, - long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, + public NetworkVO(long id, TrafficType trafficType, Mode mode, BroadcastDomainType broadcastDomainType, + long networkOfferingId, long domainId, long accountId, long related, String name, String displayText, String networkDomain, GuestType guestType, long dcId, Long physicalNetworkId, ACLType aclType, boolean specifyIpRanges, Long vpcId) { this(trafficType, mode, broadcastDomainType, networkOfferingId, State.Allocated, dcId, physicalNetworkId); this.domainId = domainId; @@ -368,7 +367,7 @@ public class NetworkVO implements Network, Identity { public Long getPhysicalNetworkId() { return physicalNetworkId; } - + @Override public void setPhysicalNetworkId(Long physicalNetworkId) { this.physicalNetworkId = physicalNetworkId; @@ -428,7 +427,7 @@ public class NetworkVO implements Network, Identity { public void setCreated(Date created) { this.created = created; } - + @Override public Network.GuestType getGuestType() { return guestType; @@ -465,7 +464,7 @@ public class NetworkVO implements Network, Identity { public String getUuid() { return this.uuid; } - + public void setUuid(String uuid) { this.uuid = uuid; } @@ -482,7 +481,7 @@ public class NetworkVO implements Network, Identity { public boolean isRestartRequired() { return restartRequired; } - + @Override public boolean getSpecifyIpRanges() { return specifyIpRanges; diff --git a/server/src/com/cloud/network/PhysicalNetworkVO.java b/server/src/com/cloud/network/PhysicalNetworkVO.java index 84371fb0be5..9bf8601c503 100644 --- a/server/src/com/cloud/network/PhysicalNetworkVO.java +++ b/server/src/com/cloud/network/PhysicalNetworkVO.java @@ -35,6 +35,7 @@ import javax.persistence.TableGenerator; import com.cloud.utils.NumbersUtil; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; /** * NetworkConfigurationVO contains information about a specific physical network. diff --git a/server/src/com/cloud/network/PortProfileVO.java b/server/src/com/cloud/network/PortProfileVO.java index c9b2a3f2830..8a7b9d88fe4 100644 --- a/server/src/com/cloud/network/PortProfileVO.java +++ b/server/src/com/cloud/network/PortProfileVO.java @@ -27,6 +27,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.cloud.exception.InvalidParameterValueException; +import org.apache.cloudstack.api.InternalIdentity; /** * PortProfileVO contains information on portprofiles that are created on a Cisco Nexus 1000v VSM associated @@ -35,7 +36,7 @@ import com.cloud.exception.InvalidParameterValueException; @Entity @Table(name="port_profile") -public class PortProfileVO { +public class PortProfileVO implements InternalIdentity { // We need to know what properties a VSM has. Put them here. diff --git a/server/src/com/cloud/network/RouterNetworkVO.java b/server/src/com/cloud/network/RouterNetworkVO.java index 0ff3a4461da..ee58521e2a2 100644 --- a/server/src/com/cloud/network/RouterNetworkVO.java +++ b/server/src/com/cloud/network/RouterNetworkVO.java @@ -26,11 +26,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.network.Network.GuestType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="router_network_ref") -public class RouterNetworkVO{ +public class RouterNetworkVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) long id; diff --git a/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java b/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java index b51e83cea87..c327b1e33e5 100644 --- a/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java +++ b/server/src/com/cloud/network/Site2SiteCustomerGatewayVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_customer_gateway")) diff --git a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java index 4424f218911..99f807f06b2 100644 --- a/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java +++ b/server/src/com/cloud/network/Site2SiteVpnConnectionVO.java @@ -29,10 +29,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_vpn_connection")) -public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection { +public class Site2SiteVpnConnectionVO implements Site2SiteVpnConnection, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java b/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java index 29d174b5afc..ada50c40869 100644 --- a/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java +++ b/server/src/com/cloud/network/Site2SiteVpnGatewayVO.java @@ -27,6 +27,7 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("s2s_vpn_gateway")) diff --git a/server/src/com/cloud/network/StorageNetworkManagerImpl.java b/server/src/com/cloud/network/StorageNetworkManagerImpl.java index da7553bc9af..6c2411cb7d4 100755 --- a/server/src/com/cloud/network/StorageNetworkManagerImpl.java +++ b/server/src/com/cloud/network/StorageNetworkManagerImpl.java @@ -26,13 +26,13 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.network.CreateStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.ListStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateStorageNetworkIpRangeCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.CreateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.DeleteStorageNetworkIpRangeCmd; -import com.cloud.api.commands.UpdateStorageNetworkIpRangeCmd; -import com.cloud.api.commands.listStorageNetworkIpRangeCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteStorageNetworkIpRangeCmd; import com.cloud.dc.HostPodVO; import com.cloud.dc.StorageNetworkIpRange; import com.cloud.dc.StorageNetworkIpAddressVO; @@ -40,12 +40,10 @@ import com.cloud.dc.StorageNetworkIpRangeVO; import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.StorageNetworkIpAddressDao; import com.cloud.dc.dao.StorageNetworkIpRangeDao; -import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InvalidParameterValueException; -import com.cloud.host.HostVO; import com.cloud.network.Networks.TrafficType; import com.cloud.network.dao.NetworkDao; -import com.cloud.utils.Pair; +import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.SearchCriteria2; import com.cloud.utils.db.SearchCriteriaService; @@ -56,7 +54,6 @@ import com.cloud.utils.net.NetUtils; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VirtualMachine; import com.cloud.vm.dao.SecondaryStorageVmDao; -import com.cloud.vm.dao.VMInstanceDao; @Component @Local(value = {StorageNetworkManager.class, StorageNetworkService.class}) @@ -310,7 +307,7 @@ public class StorageNetworkManagerImpl implements StorageNetworkManager, Storage } @Override - public List listIpRange(listStorageNetworkIpRangeCmd cmd) { + public List listIpRange(ListStorageNetworkIpRangeCmd cmd) { Long rangeId = cmd.getRangeId(); Long podId = cmd.getPodId(); Long zoneId = cmd.getZoneId(); diff --git a/server/src/com/cloud/network/addr/PublicIp.java b/server/src/com/cloud/network/addr/PublicIp.java index e1f77be6ca7..8ad716fd631 100644 --- a/server/src/com/cloud/network/addr/PublicIp.java +++ b/server/src/com/cloud/network/addr/PublicIp.java @@ -5,7 +5,7 @@ // 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, @@ -36,52 +36,52 @@ public class PublicIp implements PublicIpAddress { _vlan = vlan; this.macAddress = NetUtils.long2Mac(macAddress); } - + @Override public Ip getAddress() { return _addr.getAddress(); } - + @Override public String getNetmask() { return _vlan.getVlanNetmask(); } - + @Override public String getGateway() { return _vlan.getVlanGateway(); } - + @Override public String getVlanTag() { return _vlan.getVlanTag(); } - + @Override public long getDataCenterId() { return _addr.getDataCenterId(); } - + @Override public boolean readyToUse() { return _addr.getAllocatedTime() != null && _addr.getState() == State.Allocated; } - + @Override public boolean isSourceNat() { return _addr.isSourceNat(); } - + @Override public boolean isOneToOneNat() { return _addr.isOneToOneNat(); } - + @Override public Long getAssociatedWithVmId() { return _addr.getAssociatedWithVmId(); } - + @Override public Date getAllocatedTime() { return _addr.getAllocatedTime(); @@ -106,25 +106,25 @@ public class PublicIp implements PublicIpAddress { public State getState() { return _addr.getState(); } - + public IPAddressVO ip() { return _addr; } - + public VlanVO vlan() { return _vlan; } - + @Override public String getMacAddress() { return macAddress; } - + @Override public Long getAssociatedWithNetworkId() { return _addr.getAssociatedWithNetworkId(); } - + @Override public Long getNetworkId() { return _vlan.getNetworkId(); @@ -149,12 +149,18 @@ public class PublicIp implements PublicIpAddress { public VlanType getVlanType() { return _vlan.getVlanType(); } - + @Override public long getId() { return _addr.getId(); } - + + + @Override + public String getUuid() { + return _addr.getUuid(); + } + @Override public String toString() { return _addr.getAddress().toString(); @@ -179,7 +185,7 @@ public class PublicIp implements PublicIpAddress { public Long getAllocatedInDomainId() { return _addr.getAllocatedInDomainId(); } - + @Override public boolean getSystem() { return _addr.getSystem(); diff --git a/server/src/com/cloud/network/as/AutoScaleManager.java b/server/src/com/cloud/network/as/AutoScaleManager.java new file mode 100644 index 00000000000..ac822dca945 --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScaleManager.java @@ -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 permissions and limitations +// under the License. +package com.cloud.network.as; + +public interface AutoScaleManager extends AutoScaleService { + + void cleanUpAutoScaleResources(Long accountId); +} diff --git a/server/src/com/cloud/network/as/AutoScaleManagerImpl.java b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java new file mode 100644 index 00000000000..4c49914f11c --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScaleManagerImpl.java @@ -0,0 +1,1180 @@ +// 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.as; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.ejb.Local; +import javax.naming.ConfigurationException; + +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.api.command.admin.autoscale.CreateCounterCmd; +import org.apache.cloudstack.api.command.user.autoscale.*; +import org.apache.log4j.Logger; + +import org.apache.cloudstack.api.ApiConstants; +import com.cloud.api.ApiDBUtils; +import com.cloud.api.ApiDispatcher; +import org.apache.cloudstack.api.BaseListAccountResourcesCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateAutoScaleVmGroupCmd; +import org.apache.cloudstack.api.command.user.autoscale.CreateConditionCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListAutoScaleVmGroupsCmd; +import org.apache.cloudstack.api.command.user.autoscale.ListConditionsCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScalePolicyCmd; +import org.apache.cloudstack.api.command.user.autoscale.UpdateAutoScaleVmProfileCmd; +import com.cloud.configuration.Config; +import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenter; +import com.cloud.dc.dao.DataCenterDao; +import com.cloud.event.ActionEvent; +import com.cloud.event.EventTypes; +import com.cloud.exception.InvalidParameterValueException; +import com.cloud.exception.ResourceInUseException; +import com.cloud.exception.ResourceUnavailableException; +import com.cloud.network.LoadBalancerVO; +import com.cloud.network.Network.Capability; +import com.cloud.network.as.AutoScaleCounter.AutoScaleCounterParam; +import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; +import com.cloud.network.as.dao.AutoScalePolicyDao; +import com.cloud.network.as.dao.AutoScaleVmGroupDao; +import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; +import com.cloud.network.as.dao.AutoScaleVmProfileDao; +import com.cloud.network.as.dao.ConditionDao; +import com.cloud.network.as.dao.CounterDao; +import com.cloud.network.dao.IPAddressDao; +import com.cloud.network.dao.LoadBalancerDao; +import com.cloud.network.dao.LoadBalancerVMMapDao; +import com.cloud.network.dao.NetworkDao; +import com.cloud.network.lb.LoadBalancingRulesManager; +import com.cloud.offering.ServiceOffering; +import com.cloud.projects.Project.ListProjectResourcesCriteria; +import com.cloud.template.TemplateManager; +import com.cloud.template.VirtualMachineTemplate; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import com.cloud.user.UserContext; +import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserDao; +import com.cloud.utils.Pair; +import com.cloud.utils.Ternary; +import com.cloud.utils.component.Inject; +import com.cloud.utils.component.Manager; +import com.cloud.utils.db.DB; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.db.JoinBuilder; +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.net.NetUtils; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +@Local(value = { AutoScaleService.class, AutoScaleManager.class }) +public class AutoScaleManagerImpl implements AutoScaleManager, AutoScaleService, Manager { + private static final Logger s_logger = Logger.getLogger(AutoScaleManagerImpl.class); + + String _name; + @Inject + AccountDao _accountDao; + @Inject + AccountManager _accountMgr; + @Inject + ConfigurationManager _configMgr; + @Inject + TemplateManager _templateMgr; + @Inject + LoadBalancingRulesManager _lbRulesMgr; + @Inject + NetworkDao _networkDao; + @Inject + CounterDao _counterDao; + @Inject + ConditionDao _conditionDao; + @Inject + LoadBalancerVMMapDao _lb2VmMapDao; + @Inject + LoadBalancerDao _lbDao; + @Inject + AutoScaleVmProfileDao _autoScaleVmProfileDao; + @Inject + AutoScalePolicyDao _autoScalePolicyDao; + @Inject + AutoScalePolicyConditionMapDao _autoScalePolicyConditionMapDao; + @Inject + AutoScaleVmGroupDao _autoScaleVmGroupDao; + @Inject + AutoScaleVmGroupPolicyMapDao _autoScaleVmGroupPolicyMapDao; + @Inject + DataCenterDao _dcDao = null; + @Inject + UserDao _userDao; + @Inject + ConfigurationDao _configDao; + @Inject + IPAddressDao _ipAddressDao; + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + return true; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } + + @Override + public String getName() { + return _name; + } + + public List getSupportedAutoScaleCounters(long networkid) + { + String capability = _lbRulesMgr.getLBCapability(networkid, Capability.AutoScaleCounters.getName()); + if (capability == null) { + return null; + } + Gson gson = new Gson(); + java.lang.reflect.Type listType = new TypeToken>() { + }.getType(); + List result = gson.fromJson(capability, listType); + return result; + } + + public void validateAutoScaleCounters(long networkid, List counters, List> counterParamPassed) { + List supportedCounters = getSupportedAutoScaleCounters(networkid); + if (supportedCounters == null) { + throw new InvalidParameterException("AutoScale is not supported in the network"); + } + for (Counter counter : counters) { + String counterName = counter.getSource().name().toString(); + boolean isCounterSupported = false; + for (AutoScaleCounter autoScaleCounter : supportedCounters) { + if (autoScaleCounter.getName().equals(counterName)) { + isCounterSupported = true; + List counterParams = autoScaleCounter.getParamList(); + for (AutoScaleCounterParam autoScaleCounterParam : counterParams) { + boolean isRequiredParameter = autoScaleCounterParam.getRequired(); + if (isRequiredParameter) { + boolean isRequiredParamPresent = false; + for (Pair pair : counterParamPassed) { + if (pair.first().equals(autoScaleCounterParam.getParamName())) + isRequiredParamPresent = true; + + } + if (!isRequiredParamPresent) { + throw new InvalidParameterException("Parameter " + autoScaleCounterParam.getParamName() + " has to be set in AutoScaleVmProfile's " + + ApiConstants.COUNTERPARAM_LIST); + } + } + } + break; + } + } + if (!isCounterSupported) { + throw new InvalidParameterException("AutoScale counter with source='" + counter.getSource().name() + "' is not supported " + + "in the network"); + } + } + } + + private VO getEntityInDatabase(Account caller, String paramName, Long id, GenericDao dao) + { + + VO vo = dao.findById(id); + + if (vo == null) { + throw new InvalidParameterValueException("Unable to find " + paramName); + } + + _accountMgr.checkAccess(caller, null, false, (ControlledEntity) vo); + + return vo; + } + + private boolean isAutoScaleScaleUpPolicy(AutoScalePolicy policyVO) + { + return policyVO.getAction().equals("scaleup"); + } + + private List getAutoScalePolicies(String paramName, List policyIds, List counters, int interval, boolean scaleUpPolicies) + { + SearchBuilder policySearch = _autoScalePolicyDao.createSearchBuilder(); + policySearch.and("ids", policySearch.entity().getId(), Op.IN); + policySearch.done(); + SearchCriteria sc = policySearch.create(); + + sc.setParameters("ids", policyIds.toArray(new Object[0])); + List policies = _autoScalePolicyDao.search(sc, null); + + int prevQuietTime = 0; + + for (AutoScalePolicyVO policy : policies) { + int quietTime = policy.getQuietTime(); + if (prevQuietTime == 0) { + prevQuietTime = quietTime; + } + int duration = policy.getDuration(); + if (duration < interval) { + throw new InvalidParameterValueException("duration : " + duration + " specified in a policy cannot be less than vm group's interval : " + interval); + } + + if (quietTime != prevQuietTime) { + throw new InvalidParameterValueException("quietTime should be same for all the policies specified in " + paramName); + } + + if (scaleUpPolicies) { + if (!isAutoScaleScaleUpPolicy(policy)) { + throw new InvalidParameterValueException("Only scaleup policies can be specified in scaleuppolicyids"); + } + } + else { + if (isAutoScaleScaleUpPolicy(policy)) { + throw new InvalidParameterValueException("Only scaledown policies can be specified in scaledownpolicyids"); + } + } + List policyConditionMapVOs = _autoScalePolicyConditionMapDao.listByAll(policy.getId(), null); + for (AutoScalePolicyConditionMapVO policyConditionMapVO : policyConditionMapVOs) { + long conditionid = policyConditionMapVO.getConditionId(); + Condition condition = _conditionDao.findById(conditionid); + Counter counter = _counterDao.findById(condition.getCounterid()); + counters.add(counter); + } + } + return policies; + } + + @DB + protected AutoScaleVmProfileVO checkValidityAndPersist(AutoScaleVmProfileVO vmProfile) { + long templateId = vmProfile.getTemplateId(); + long autoscaleUserId = vmProfile.getAutoScaleUserId(); + int destroyVmGraceperiod = vmProfile.getDestroyVmGraceperiod(); + + VirtualMachineTemplate template = _templateMgr.getTemplate(templateId); + // Make sure a valid template ID was specified + if (template == null) { + throw new InvalidParameterValueException("Unable to use the given template."); + } + + if (destroyVmGraceperiod < 0) { + throw new InvalidParameterValueException("Destroy Vm Grace Period cannot be less than 0."); + } + + User user = _userDao.findById(autoscaleUserId); + if (user.getAccountId() != vmProfile.getAccountId()) { + throw new InvalidParameterValueException("AutoScale User id does not belong to the same account"); + } + + String apiKey = user.getApiKey(); + String secretKey = user.getSecretKey(); + String csUrl = _configDao.getValue(Config.EndpointeUrl.key()); + + if (apiKey == null) { + throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it"); + } + + if (secretKey == null) { + throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it"); + } + + if (csUrl == null || csUrl.contains("localhost")) { + throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point"); + } + + vmProfile = _autoScaleVmProfileDao.persist(vmProfile); + + return vmProfile; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_CREATE, eventDescription = "creating autoscale vm profile", create = true) + public AutoScaleVmProfile createAutoScaleVmProfile(CreateAutoScaleVmProfileCmd cmd) { + + Account owner = _accountDao.findById(cmd.getAccountId()); + Account caller = UserContext.current().getCaller(); + _accountMgr.checkAccess(caller, null, true, owner); + + long zoneId = cmd.getZoneId(); + long serviceOfferingId = cmd.getServiceOfferingId(); + Long autoscaleUserId = cmd.getAutoscaleUserId(); + + DataCenter zone = _configMgr.getZone(zoneId); + + if (zone == null) { + throw new InvalidParameterValueException("Unable to find zone by id"); + } + + ServiceOffering serviceOffering = _configMgr.getServiceOffering(serviceOfferingId); + if (serviceOffering == null) { + throw new InvalidParameterValueException("Unable to find service offering by id"); + } + + // validations + HashMap deployParams = cmd.getDeployParamMap(); + if (deployParams.containsKey("networks") && deployParams.get("networks").length() > 0) { + throw new InvalidParameterValueException("'networks' is not a valid parameter, network for an AutoScaled VM is chosen automatically. An autoscaled VM is deployed in the loadbalancer's network"); + } + /* + * Just for making sure the values are right in other deploy params. + * For ex. if projectId is given as a string instead of an long value, this + * will be throwing an error. + */ + ApiDispatcher.processParameters(new DeployVMCmd(), deployParams); + + if (autoscaleUserId == null) { + autoscaleUserId = UserContext.current().getCallerUserId(); + } + + AutoScaleVmProfileVO profileVO = new AutoScaleVmProfileVO(cmd.getZoneId(), cmd.getDomainId(), cmd.getAccountId(), cmd.getServiceOfferingId(), cmd.getTemplateId(), cmd.getOtherDeployParams(), + cmd.getCounterParamList(), cmd.getDestroyVmGraceperiod(), autoscaleUserId); + profileVO = checkValidityAndPersist(profileVO); + s_logger.info("Successfully create AutoScale Vm Profile with Id: " + profileVO.getId()); + + return profileVO; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_UPDATE, eventDescription = "updating autoscale vm profile") + public AutoScaleVmProfile updateAutoScaleVmProfile(UpdateAutoScaleVmProfileCmd cmd) { + Long profileId = cmd.getId(); + Long templateId = cmd.getTemplateId(); + Long autoscaleUserId = cmd.getAutoscaleUserId(); + Map counterParamList = cmd.getCounterParamList(); + + Integer destroyVmGraceperiod = cmd.getDestroyVmGraceperiod(); + + AutoScaleVmProfileVO vmProfile = getEntityInDatabase(UserContext.current().getCaller(), "Auto Scale Vm Profile", profileId, _autoScaleVmProfileDao); + + if (templateId != null) { + vmProfile.setTemplateId(templateId); + } + + if (autoscaleUserId != null) { + vmProfile.setAutoscaleUserId(autoscaleUserId); + } + + if (counterParamList != null) { + vmProfile.setCounterParamsForUpdate(counterParamList); + } + + if (destroyVmGraceperiod != null) { + vmProfile.setDestroyVmGraceperiod(destroyVmGraceperiod); + } + + List vmGroupList = _autoScaleVmGroupDao.listByAll(null, profileId); + for (AutoScaleVmGroupVO vmGroupVO : vmGroupList) { + if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { + throw new InvalidParameterValueException("The AutoScale Vm Profile can be updated only if the Vm Group it is associated with is disabled in state"); + } + } + + vmProfile = checkValidityAndPersist(vmProfile); + s_logger.info("Updated Auto Scale Vm Profile id:" + vmProfile.getId()); + + return vmProfile; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMPROFILE_DELETE, eventDescription = "deleting autoscale vm profile") + public boolean deleteAutoScaleVmProfile(long id) { + /* Check if entity is in database */ + getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Profile", id, _autoScaleVmProfileDao); + if (_autoScaleVmGroupDao.isProfileInUse(id)) { + throw new InvalidParameterValueException("Cannot delete AutoScale Vm Profile when it is in use by one more vm groups"); + } + boolean success = _autoScaleVmProfileDao.remove(id); + if (success) { + s_logger.info("Successfully deleted AutoScale Vm Profile with Id: " + id); + } + return success; + } + + @Override + public List listAutoScaleVmProfiles(ListAutoScaleVmProfilesCmd cmd) { + Long id = cmd.getId(); + Long templateId = cmd.getTemplateId(); + String otherDeployParams = cmd.getOtherDeployParams(); + + SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmProfileDao, AutoScaleVmProfileVO.class, cmd, cmd.getId()); + SearchBuilder sb = searchWrapper.getSearchBuilder(); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("otherDeployParams", sb.entity().getOtherDeployParams(), SearchCriteria.Op.LIKE); + SearchCriteria sc = searchWrapper.buildSearchCriteria(); + + if (id != null) { + sc.setParameters("id", id); + } + if (templateId != null) { + sc.setParameters("templateId", templateId); + } + if (otherDeployParams != null) { + sc.addAnd("otherDeployParams", SearchCriteria.Op.LIKE, "%" + otherDeployParams + "%"); + } + return searchWrapper.search(); + } + + @DB + protected AutoScalePolicyVO checkValidityAndPersist(AutoScalePolicyVO autoScalePolicyVO, List conditionIds) { + int duration = autoScalePolicyVO.getDuration(); + int quietTime = autoScalePolicyVO.getQuietTime(); + + if (duration < 0) { + throw new InvalidParameterValueException("duration is an invalid value: " + duration); + } + + if (quietTime < 0) { + throw new InvalidParameterValueException("quiettime is an invalid value: " + quietTime); + } + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + + autoScalePolicyVO = _autoScalePolicyDao.persist(autoScalePolicyVO); + + if (conditionIds != null) { + SearchBuilder conditionsSearch = _conditionDao.createSearchBuilder(); + conditionsSearch.and("ids", conditionsSearch.entity().getId(), Op.IN); + conditionsSearch.done(); + SearchCriteria sc = conditionsSearch.create(); + + sc.setParameters("ids", conditionIds.toArray(new Object[0])); + List conditions = _conditionDao.search(sc, null); + + ControlledEntity[] sameOwnerEntities = conditions.toArray(new ControlledEntity[conditions.size() + 1]); + sameOwnerEntities[sameOwnerEntities.length - 1] = autoScalePolicyVO; + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, sameOwnerEntities); + + if (conditionIds.size() != conditions.size()) { + // TODO report the condition id which could not be found + throw new InvalidParameterValueException("Unable to find the condition specified"); + } + + ArrayList counterIds = new ArrayList(); + for (ConditionVO condition : conditions) { + if (counterIds.contains(condition.getCounterid())) { + throw new InvalidParameterValueException("atleast two conditions in the conditionids have the same counter. It is not right to apply two different conditions for the same counter"); + } + counterIds.add(condition.getCounterid()); + } + + /* For update case remove the existing mappings and create fresh ones */ + _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(autoScalePolicyVO.getId()); + + for (Long conditionId : conditionIds) { + AutoScalePolicyConditionMapVO policyConditionMapVO = new AutoScalePolicyConditionMapVO(autoScalePolicyVO.getId(), conditionId); + _autoScalePolicyConditionMapDao.persist(policyConditionMapVO); + } + } + + txn.commit(); + return autoScalePolicyVO; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_CREATE, eventDescription = "creating autoscale policy", create = true) + public AutoScalePolicy createAutoScalePolicy(CreateAutoScalePolicyCmd cmd) { + + int duration = cmd.getDuration(); + Integer quietTime = cmd.getQuietTime(); + String action = cmd.getAction(); + + if (quietTime == null) { + quietTime = NetUtils.DEFAULT_AUTOSCALE_POLICY_QUIET_TIME; + } + + action = action.toLowerCase(); + if (!NetUtils.isValidAutoScaleAction(action)) { + throw new InvalidParameterValueException("action is invalid, only 'scaleup' and 'scaledown' is supported"); + } + + AutoScalePolicyVO policyVO = new AutoScalePolicyVO(cmd.getDomainId(), cmd.getAccountId(), duration, quietTime, action); + + policyVO = checkValidityAndPersist(policyVO, cmd.getConditionIds()); + s_logger.info("Successfully created AutoScale Policy with Id: " + policyVO.getId()); + return policyVO; + } + + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_DELETE, eventDescription = "deleting autoscale policy") + public boolean deleteAutoScalePolicy(long id) { + /* Check if entity is in database */ + getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Policy", id, _autoScalePolicyDao); + + if (_autoScaleVmGroupPolicyMapDao.isAutoScalePolicyInUse(id)) { + throw new InvalidParameterValueException("Cannot delete AutoScale Policy when it is in use by one or more AutoScale Vm Groups"); + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + + boolean success = true; + success = _autoScalePolicyDao.remove(id); + if (!success) { + s_logger.warn("Failed to remove AutoScale Policy db object"); + return false; + } + success = _autoScalePolicyConditionMapDao.removeByAutoScalePolicyId(id); + if (!success) { + s_logger.warn("Failed to remove AutoScale Policy Condition mappings"); + return false; + } + txn.commit(); + s_logger.info("Successfully deleted autoscale policy id : " + id); + return true; // successful + } + + public void checkCallerAccess(String accountName, Long domainId) + { + Account caller = UserContext.current().getCaller(); + Account owner = _accountDao.findActiveAccount(accountName, domainId); + if (owner == null) { + List idList = new ArrayList(); + idList.add(ApiDBUtils.findDomainById(domainId).getUuid()); + throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain with specifed domainId"); + } + _accountMgr.checkAccess(caller, null, false, owner); + } + + private class SearchWrapper { + GenericDao dao; + SearchBuilder searchBuilder; + SearchCriteria searchCriteria; + Long domainId; + boolean isRecursive; + List permittedAccounts = new ArrayList(); + ListProjectResourcesCriteria listProjectResourcesCriteria; + Filter searchFilter; + + public SearchWrapper(GenericDao dao, Class entityClass, BaseListAccountResourcesCmd cmd, Long id) + { + this.dao = dao; + this.searchBuilder = dao.createSearchBuilder(); + domainId = cmd.getDomainId(); + String accountName = cmd.getAccountName(); + isRecursive = cmd.isRecursive(); + boolean listAll = cmd.listAll(); + long startIndex = cmd.getStartIndex(); + long pageSizeVal = cmd.getPageSizeVal(); + Account caller = UserContext.current().getCaller(); + + Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); + _accountMgr.buildACLSearchParameters(caller, id, accountName, null, permittedAccounts, domainIdRecursiveListProject, + listAll, false); + domainId = domainIdRecursiveListProject.first(); + isRecursive = domainIdRecursiveListProject.second(); + ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); + _accountMgr.buildACLSearchBuilder(searchBuilder, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + searchFilter = new Filter(entityClass, "id", false, startIndex, pageSizeVal); + } + + public SearchBuilder getSearchBuilder() { + return searchBuilder; + } + + public SearchCriteria buildSearchCriteria() + { + searchCriteria = searchBuilder.create(); + _accountMgr.buildACLSearchCriteria(searchCriteria, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); + return searchCriteria; + } + + public List search() { + return dao.search(searchCriteria, searchFilter); + } + } + + @Override + public List listAutoScalePolicies(ListAutoScalePoliciesCmd cmd) { + SearchWrapper searchWrapper = new SearchWrapper(_autoScalePolicyDao, AutoScalePolicyVO.class, cmd, cmd.getId()); + SearchBuilder sb = searchWrapper.getSearchBuilder(); + Long id = cmd.getId(); + Long conditionId = cmd.getConditionId(); + String action = cmd.getAction(); + Long vmGroupId = cmd.getVmGroupId(); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("action", sb.entity().getAction(), SearchCriteria.Op.EQ); + + if (conditionId != null) { + SearchBuilder asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder(); + asPolicyConditionSearch.and("conditionId", asPolicyConditionSearch.entity().getConditionId(), SearchCriteria.Op.EQ); + sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER); + } + + if (vmGroupId != null) { + SearchBuilder asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder(); + asVmGroupPolicySearch.and("vmGroupId", asVmGroupPolicySearch.entity().getVmGroupId(), SearchCriteria.Op.EQ); + sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getPolicyId(), JoinBuilder.JoinType.INNER); + } + + SearchCriteria sc = searchWrapper.buildSearchCriteria(); + + if (id != null) { + sc.setParameters("id", id); + } + + if (action != null) { + sc.setParameters("action", action); + } + + if (conditionId != null) { + sc.setJoinParameters("asPolicyConditionSearch", "conditionId", conditionId); + } + + if (vmGroupId != null) { + sc.setJoinParameters("asVmGroupPolicySearch", "vmGroupId", vmGroupId); + } + + return searchWrapper.search(); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEPOLICY_UPDATE, eventDescription = "updating autoscale policy") + public AutoScalePolicy updateAutoScalePolicy(UpdateAutoScalePolicyCmd cmd) { + Long policyId = cmd.getId(); + Integer duration = cmd.getDuration(); + Integer quietTime = cmd.getQuietTime(); + List conditionIds = cmd.getConditionIds(); + AutoScalePolicyVO policy = getEntityInDatabase(UserContext.current().getCaller(), "Auto Scale Policy", policyId, _autoScalePolicyDao); + + if (duration != null) { + policy.setDuration(duration); + } + + if (quietTime != null) { + policy.setQuietTime(quietTime); + } + + List vmGroupPolicyList = _autoScaleVmGroupPolicyMapDao.listByPolicyId(policyId); + for (AutoScaleVmGroupPolicyMapVO vmGroupPolicy : vmGroupPolicyList) { + AutoScaleVmGroupVO vmGroupVO = _autoScaleVmGroupDao.findById(vmGroupPolicy.getVmGroupId()); + if (vmGroupVO == null) { + s_logger.warn("Stale database entry! There is an entry in VmGroupPolicyMap but the vmGroup is missing:" + vmGroupPolicy.getVmGroupId()); + + continue; + + } + if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { + throw new InvalidParameterValueException("The AutoScale Policy can be updated only if the Vm Group it is associated with is disabled in state"); + } + if (policy.getDuration() < vmGroupVO.getInterval()) { + throw new InvalidParameterValueException("duration is less than the associated AutoScaleVmGroup's interval"); + } + } + + policy = checkValidityAndPersist(policy, conditionIds); + s_logger.info("Successfully updated Auto Scale Policy id:" + policyId); + return policy; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_CREATE, eventDescription = "creating autoscale vm group", create = true) + public AutoScaleVmGroup createAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) { + int minMembers = cmd.getMinMembers(); + int maxMembers = cmd.getMaxMembers(); + Integer interval = cmd.getInterval(); + + if (interval == null) { + interval = NetUtils.DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME; + } + + LoadBalancerVO loadBalancer = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.LBID, cmd.getLbRuleId(), _lbDao); + + Long zoneId = _ipAddressDao.findById(loadBalancer.getSourceIpAddressId()).getDataCenterId(); + + if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancer.getId())) { + throw new InvalidParameterValueException("an AutoScaleVmGroup is already attached to the lb rule, the existing vm group has to be first deleted"); + } + + if (_lb2VmMapDao.isVmAttachedToLoadBalancer(loadBalancer.getId())) { + throw new InvalidParameterValueException("there are Vms already bound to the specified LoadBalancing Rule. User bound Vms and AutoScaled Vm Group cannot co-exist on a Load Balancing Rule"); + } + + AutoScaleVmGroupVO vmGroupVO = new AutoScaleVmGroupVO(cmd.getLbRuleId(), zoneId, loadBalancer.getDomainId(), loadBalancer.getAccountId(), minMembers, maxMembers, + loadBalancer.getDefaultPortStart(), interval, cmd.getProfileId(), AutoScaleVmGroup.State_New); + + vmGroupVO = checkValidityAndPersist(vmGroupVO, cmd.getScaleUpPolicyIds(), cmd.getScaleDownPolicyIds()); + s_logger.info("Successfully created Autoscale Vm Group with Id: " + vmGroupVO.getId()); + + return vmGroupVO; + } + + @Override + public boolean configureAutoScaleVmGroup(CreateAutoScaleVmGroupCmd cmd) throws ResourceUnavailableException { + return configureAutoScaleVmGroup(cmd.getEntityId(), AutoScaleVmGroup.State_New); + } + + public boolean isLoadBalancerBasedAutoScaleVmGroup(AutoScaleVmGroup vmGroup) { + return vmGroup.getLoadBalancerId() != null; + } + + private boolean configureAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException { + AutoScaleVmGroup vmGroup = _autoScaleVmGroupDao.findById(vmGroupid); + + if (isLoadBalancerBasedAutoScaleVmGroup(vmGroup)) { + try { + return _lbRulesMgr.configureLbAutoScaleVmGroup(vmGroupid, currentState); + } catch (ResourceUnavailableException re) { + throw re; + } catch (Exception e) { + s_logger.warn("Exception during configureLbAutoScaleVmGroup in lb rules manager", e); + return false; + } + } + + // This should never happen, because today loadbalancerruleid is manadatory for AutoScaleVmGroup. + throw new InvalidParameterValueException("Only LoadBalancer based AutoScale is supported"); + } + + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DELETE, eventDescription = "deleting autoscale vm group") + public boolean deleteAutoScaleVmGroup(long id) { + AutoScaleVmGroupVO autoScaleVmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); + + if (autoScaleVmGroupVO.getState().equals(AutoScaleVmGroup.State_New)) { + /* This condition is for handling failures during creation command */ + return _autoScaleVmGroupDao.remove(id); + } + String bakupState = autoScaleVmGroupVO.getState(); + autoScaleVmGroupVO.setState(AutoScaleVmGroup.State_Revoke); + _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); + boolean success = false; + + try { + success = configureAutoScaleVmGroup(id, bakupState); + } catch (ResourceUnavailableException e) { + autoScaleVmGroupVO.setState(bakupState); + _autoScaleVmGroupDao.persist(autoScaleVmGroupVO); + } finally { + if (!success) { + s_logger.warn("Could not delete AutoScale Vm Group id : " + id); + return false; + } + } + + Transaction txn = Transaction.currentTxn(); + txn.start(); + success = _autoScaleVmGroupDao.remove(id); + + if (!success) { + s_logger.warn("Failed to remove AutoScale Group db object"); + return false; + } + + success = _autoScaleVmGroupPolicyMapDao.removeByGroupId(id); + if (!success) { + s_logger.warn("Failed to remove AutoScale Group Policy mappings"); + return false; + } + + txn.commit(); + s_logger.info("Successfully deleted autoscale vm group id : " + id); + return success; // Successfull + } + + @Override + public List listAutoScaleVmGroups(ListAutoScaleVmGroupsCmd cmd) { + Long id = cmd.getId(); + Long policyId = cmd.getPolicyId(); + Long loadBalancerId = cmd.getLoadBalancerId(); + Long profileId = cmd.getProfileId(); + Long zoneId = cmd.getZoneId(); + + SearchWrapper searchWrapper = new SearchWrapper(_autoScaleVmGroupDao, AutoScaleVmGroupVO.class, cmd, cmd.getId()); + SearchBuilder sb = searchWrapper.getSearchBuilder(); + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("loadBalancerId", sb.entity().getLoadBalancerId(), SearchCriteria.Op.EQ); + sb.and("profileId", sb.entity().getProfileId(), SearchCriteria.Op.EQ); + sb.and("zoneId", sb.entity().getZoneId(), SearchCriteria.Op.EQ); + + if (policyId != null) { + SearchBuilder asVmGroupPolicySearch = _autoScaleVmGroupPolicyMapDao.createSearchBuilder(); + asVmGroupPolicySearch.and("policyId", asVmGroupPolicySearch.entity().getPolicyId(), SearchCriteria.Op.EQ); + sb.join("asVmGroupPolicySearch", asVmGroupPolicySearch, sb.entity().getId(), asVmGroupPolicySearch.entity().getVmGroupId(), JoinBuilder.JoinType.INNER); + } + + SearchCriteria sc = searchWrapper.buildSearchCriteria(); + if (id != null) { + sc.setParameters("id", id); + } + if (loadBalancerId != null) { + sc.setParameters("loadBalancerId", loadBalancerId); + } + if (profileId != null) { + sc.setParameters("profileId", profileId); + } + if (zoneId != null) { + sc.setParameters("zoneId", zoneId); + } + if (policyId != null) { + sc.setJoinParameters("asVmGroupPolicySearch", "policyId", policyId); + } + return searchWrapper.search(); + } + + @DB + protected AutoScaleVmGroupVO checkValidityAndPersist(AutoScaleVmGroupVO vmGroup, List passedScaleUpPolicyIds, List passedScaleDownPolicyIds) { + int minMembers = vmGroup.getMinMembers(); + int maxMembers = vmGroup.getMaxMembers(); + int interval = vmGroup.getInterval(); + List counters = new ArrayList(); + List policies = new ArrayList(); + List policyIds = new ArrayList(); + List currentScaleUpPolicyIds = new ArrayList(); + List currentScaleDownPolicyIds = new ArrayList(); + if (vmGroup.getCreated() != null) { + ApiDBUtils.getAutoScaleVmGroupPolicyIds(vmGroup.getId(), currentScaleUpPolicyIds, currentScaleDownPolicyIds); + } + + if (minMembers < 0) { + throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " is an invalid value: " + minMembers); + } + + if (maxMembers < 0) { + throw new InvalidParameterValueException(ApiConstants.MAX_MEMBERS + " is an invalid value: " + maxMembers); + } + + if (minMembers > maxMembers) { + throw new InvalidParameterValueException(ApiConstants.MIN_MEMBERS + " (" + minMembers + ")cannot be greater than " + ApiConstants.MAX_MEMBERS + " (" + maxMembers + ")"); + } + + if (interval < 0) { + throw new InvalidParameterValueException("interval is an invalid value: " + interval); + } + + if (passedScaleUpPolicyIds != null) { + policies.addAll(getAutoScalePolicies("scaleuppolicyid", passedScaleUpPolicyIds, counters, interval, true)); + policyIds.addAll(passedScaleUpPolicyIds); + } else { + // Run the interval check for existing policies + getAutoScalePolicies("scaleuppolicyid", currentScaleUpPolicyIds, counters, interval, true); + policyIds.addAll(currentScaleUpPolicyIds); + } + + if (passedScaleDownPolicyIds != null) { + policies.addAll(getAutoScalePolicies("scaledownpolicyid", passedScaleDownPolicyIds, counters, interval, false)); + policyIds.addAll(passedScaleDownPolicyIds); + } else { + // Run the interval check for existing policies + getAutoScalePolicies("scaledownpolicyid", currentScaleDownPolicyIds, counters, interval, false); + policyIds.addAll(currentScaleDownPolicyIds); + } + AutoScaleVmProfileVO profileVO = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.VMPROFILE_ID, vmGroup.getProfileId(), _autoScaleVmProfileDao); + + LoadBalancerVO loadBalancer = getEntityInDatabase(UserContext.current().getCaller(), ApiConstants.LBID, vmGroup.getLoadBalancerId(), _lbDao); + validateAutoScaleCounters(loadBalancer.getNetworkId(), counters, profileVO.getCounterParams()); + + ControlledEntity[] sameOwnerEntities = policies.toArray(new ControlledEntity[policies.size() + 2]); + sameOwnerEntities[sameOwnerEntities.length - 2] = loadBalancer; + sameOwnerEntities[sameOwnerEntities.length - 1] = profileVO; + _accountMgr.checkAccess(UserContext.current().getCaller(), null, true, sameOwnerEntities); + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + vmGroup = _autoScaleVmGroupDao.persist(vmGroup); + + if (passedScaleUpPolicyIds != null || passedScaleDownPolicyIds != null) { + _autoScaleVmGroupPolicyMapDao.removeByGroupId(vmGroup.getId()); + + for (Long policyId : policyIds) { + _autoScaleVmGroupPolicyMapDao.persist(new AutoScaleVmGroupPolicyMapVO(vmGroup.getId(), policyId)); + } + } + txn.commit(); + + return vmGroup; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_UPDATE, eventDescription = "updating autoscale vm group") + public AutoScaleVmGroup updateAutoScaleVmGroup(UpdateAutoScaleVmGroupCmd cmd) { + Long vmGroupId = cmd.getId(); + Integer minMembers = cmd.getMinMembers(); + Integer maxMembers = cmd.getMaxMembers(); + Integer interval = cmd.getInterval(); + + List scaleUpPolicyIds = cmd.getScaleUpPolicyIds(); + List scaleDownPolicyIds = cmd.getScaleDownPolicyIds(); + + AutoScaleVmGroupVO vmGroupVO = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", vmGroupId, _autoScaleVmGroupDao); + + if (!vmGroupVO.getState().equals(AutoScaleVmGroup.State_Disabled)) { + throw new InvalidParameterValueException("An AutoScale Vm Group can be updated only when it is in disabled state"); + } + + if (minMembers != null) { + vmGroupVO.setMinMembers(minMembers); + } + + if (maxMembers != null) { + vmGroupVO.setMaxMembers(maxMembers); + } + + if (interval != null) { + vmGroupVO.setInterval(interval); + } + + vmGroupVO = checkValidityAndPersist(vmGroupVO, scaleUpPolicyIds, scaleDownPolicyIds); + if (vmGroupVO != null) { + s_logger.debug("Updated Auto Scale VmGroup id:" + vmGroupId); + return vmGroupVO; + } else + return null; + } + + @Override + @DB + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_ENABLE, eventDescription = "enabling autoscale vm group") + public AutoScaleVmGroup enableAutoScaleVmGroup(Long id) { + AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); + boolean success = false; + if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Disabled)) { + throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Disabled state can be enabled."); + } + + try { + vmGroup.setState(AutoScaleVmGroup.State_Enabled); + vmGroup = _autoScaleVmGroupDao.persist(vmGroup); + success = configureAutoScaleVmGroup(id, AutoScaleVmGroup.State_Disabled); + } catch (ResourceUnavailableException e) { + vmGroup.setState(AutoScaleVmGroup.State_Disabled); + _autoScaleVmGroupDao.persist(vmGroup); + } finally { + if (!success) { + s_logger.warn("Failed to enable AutoScale Vm Group id : " + id); + return null; + } + s_logger.info("Successfully enabled AutoScale Vm Group with Id:" + id); + } + return vmGroup; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_AUTOSCALEVMGROUP_DISABLE, eventDescription = "disabling autoscale vm group") + @DB + public AutoScaleVmGroup disableAutoScaleVmGroup(Long id) { + AutoScaleVmGroupVO vmGroup = getEntityInDatabase(UserContext.current().getCaller(), "AutoScale Vm Group", id, _autoScaleVmGroupDao); + boolean success = false; + if (!vmGroup.getState().equals(AutoScaleVmGroup.State_Enabled)) { + throw new InvalidParameterValueException("Only a AutoScale Vm Group which is in Enabled state can be disabled."); + } + + try { + vmGroup.setState(AutoScaleVmGroup.State_Disabled); + vmGroup = _autoScaleVmGroupDao.persist(vmGroup); + success = configureAutoScaleVmGroup(id, AutoScaleVmGroup.State_Enabled); + } catch (ResourceUnavailableException e) { + vmGroup.setState(AutoScaleVmGroup.State_Enabled); + _autoScaleVmGroupDao.persist(vmGroup); + } finally { + if (!success) { + s_logger.warn("Failed to disable AutoScale Vm Group id : " + id); + return null; + } + s_logger.info("Successfully disabled AutoScale Vm Group with Id:" + id); + } + return vmGroup; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_COUNTER_CREATE, eventDescription = "Counter", create = true) + @DB + public Counter createCounter(CreateCounterCmd cmd) { + String source = cmd.getSource().toLowerCase(); + String name = cmd.getName(); + Counter.Source src; + // Validate Source + try { + src = Counter.Source.valueOf(source); + } catch (Exception ex) { + throw new InvalidParameterValueException("The Source " + source + " does not exist; Unable to create Counter"); + } + + CounterVO counter = null; + + s_logger.debug("Adding Counter " + name); + counter = _counterDao.persist(new CounterVO(src, name, cmd.getValue())); + + UserContext.current().setEventDetails(" Id: " + counter.getId() + " Name: " + name); + return counter; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_CONDITION_CREATE, eventDescription = "Condition", create = true) + public Condition createCondition(CreateConditionCmd cmd) { + checkCallerAccess(cmd.getAccountName(), cmd.getDomainId()); + String opr = cmd.getRelationalOperator().toUpperCase(); + long cid = cmd.getCounterId(); + long threshold = cmd.getThreshold(); + Condition.Operator op; + // Validate Relational Operator + try { + op = Condition.Operator.valueOf(opr); + } catch (IllegalArgumentException ex) { + throw new InvalidParameterValueException("The Operator " + opr + " does not exist; Unable to create Condition."); + } + // TODO - Validate threshold + + CounterVO counter = _counterDao.findById(cid); + + if (counter == null) { + throw new InvalidParameterValueException("Unable to find counter"); + } + ConditionVO condition = null; + + condition = _conditionDao.persist(new ConditionVO(cid, threshold, cmd.getEntityOwnerId(), cmd.getDomainId(), op)); + s_logger.info("Successfully created condition with Id: " + condition.getId()); + + UserContext.current().setEventDetails(" Id: " + condition.getId()); + return condition; + } + + @Override + public List listCounters(ListCountersCmd cmd) { + String name = cmd.getName(); + Long id = cmd.getId(); + String source = cmd.getSource(); + if (source != null) + source = source.toLowerCase(); + + Filter searchFilter = new Filter(CounterVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); + + List counters = _counterDao.listCounters(id, name, source, cmd.getKeyword(), searchFilter); + + return counters; + } + + @Override + public List listConditions(ListConditionsCmd cmd) { + Long id = cmd.getId(); + Long counterId = cmd.getCounterId(); + Long policyId = cmd.getPolicyId(); + SearchWrapper searchWrapper = new SearchWrapper(_conditionDao, ConditionVO.class, cmd, cmd.getId()); + SearchBuilder sb = searchWrapper.getSearchBuilder(); + if (policyId != null) { + SearchBuilder asPolicyConditionSearch = _autoScalePolicyConditionMapDao.createSearchBuilder(); + asPolicyConditionSearch.and("policyId", asPolicyConditionSearch.entity().getPolicyId(), SearchCriteria.Op.EQ); + sb.join("asPolicyConditionSearch", asPolicyConditionSearch, sb.entity().getId(), asPolicyConditionSearch.entity().getConditionId(), JoinBuilder.JoinType.INNER); + } + + sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("counterId", sb.entity().getCounterid(), SearchCriteria.Op.EQ); + + // now set the SC criteria... + SearchCriteria sc = searchWrapper.buildSearchCriteria(); + + if (id != null) { + sc.setParameters("id", id); + } + + if (counterId != null) { + sc.setParameters("counterId", counterId); + } + + if (policyId != null) { + sc.setJoinParameters("asPolicyConditionSearch", "policyId", policyId); + } + + return searchWrapper.search(); + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_COUNTER_DELETE, eventDescription = "counter") + public boolean deleteCounter(long counterId) throws ResourceInUseException { + // Verify Counter id + CounterVO counter = _counterDao.findById(counterId); + if (counter == null) { + throw new InvalidParameterValueException("Unable to find Counter"); + } + + // Verify if it is used in any Condition + + ConditionVO condition = _conditionDao.findByCounterId(counterId); + if (condition != null) { + s_logger.info("Cannot delete counter " + counter.getName() + " as it is being used in a condition."); + throw new ResourceInUseException("Counter is in use."); + } + + boolean success = _counterDao.remove(counterId); + if (success) { + s_logger.info("Successfully deleted counter with Id: " + counterId); + } + + return success; + } + + @Override + @ActionEvent(eventType = EventTypes.EVENT_CONDITION_DELETE, eventDescription = "condition") + public boolean deleteCondition(long conditionId) throws ResourceInUseException { + /* Check if entity is in database */ + ConditionVO condition = getEntityInDatabase(UserContext.current().getCaller(), "Condition", conditionId, _conditionDao); + if (condition == null) { + throw new InvalidParameterValueException("Unable to find Condition"); + } + + // Verify if condition is used in any autoscale policy + if (_autoScalePolicyConditionMapDao.isConditionInUse(conditionId)) { + s_logger.info("Cannot delete condition " + conditionId + " as it is being used in a condition."); + throw new ResourceInUseException("Cannot delete Condition when it is in use by one or more AutoScale Policies."); + } + boolean success = _conditionDao.remove(conditionId); + if (success) { + s_logger.info("Successfully deleted condition " + condition.getId()); + } + return success; + } + + @Override + public void cleanUpAutoScaleResources(Long accountId) { + // cleans Autoscale VmProfiles, AutoScale Policies and Conditions belonging to an account + int count = 0; + count = _autoScaleVmProfileDao.removeByAccountId(accountId); + if (count > 0) { + s_logger.debug("Deleted " + count + " AutoScale Vm Profile for account Id: " + accountId); + } + count = _autoScalePolicyDao.removeByAccountId(accountId); + if (count > 0) { + s_logger.debug("Deleted " + count + " AutoScale Policies for account Id: " + accountId); + } + count = _conditionDao.removeByAccountId(accountId); + if (count > 0) { + s_logger.debug("Deleted " + count + " Conditions for account Id: " + accountId); + } + } +} diff --git a/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.java new file mode 100644 index 00000000000..7d87b27507c --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScalePolicyConditionMapVO.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.network.as; + +import org.apache.cloudstack.api.InternalIdentity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name=("autoscale_policy_condition_map")) +public class AutoScalePolicyConditionMapVO implements InternalIdentity { + + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="policy_id") + private long policyId; + + @Column(name="condition_id") + private long conditionId; + + public AutoScalePolicyConditionMapVO() { } + + public AutoScalePolicyConditionMapVO(long policyId, long conditionId) { + this.policyId = policyId; + this.conditionId = conditionId; + } + + public long getId() { + return id; + } + + public long getPolicyId() { + return policyId; + } + + public long getConditionId() { + return conditionId; + } +} diff --git a/server/src/com/cloud/network/as/AutoScalePolicyVO.java b/server/src/com/cloud/network/as/AutoScalePolicyVO.java new file mode 100644 index 00000000000..f8fbcb483f5 --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScalePolicyVO.java @@ -0,0 +1,134 @@ +// 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.as; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "autoscale_policies") +@Inheritance(strategy = InheritanceType.JOINED) +public class AutoScalePolicyVO implements AutoScalePolicy, InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "uuid") + String uuid; + + @Column(name = "domain_id") + private long domainId; + + @Column(name = "account_id") + private long accountId; + + @Column(name = "duration") + private int duration; + + @Column(name = "quiet_time", updatable = true, nullable = false) + private int quietTime; + + @Column(name = "action", updatable = false, nullable = false) + private String action; + + @Column(name = GenericDao.REMOVED_COLUMN) + protected Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + protected Date created; + + public AutoScalePolicyVO() { + } + + public AutoScalePolicyVO(long domainId, long accountId, int duration, int quietTime, String action) { + this.uuid = UUID.randomUUID().toString(); + this.domainId = domainId; + this.accountId = accountId; + this.duration = duration; + this.quietTime = quietTime; + this.action = action; + } + + @Override + public String toString() { + return new StringBuilder("AutoScalePolicy[").append("id-").append(id).append("]").toString(); + } + + @Override + public long getId() { + return id; + } + + public String getUuid() { + return uuid; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public int getDuration() { + return duration; + } + + @Override + public int getQuietTime() { + return quietTime; + } + + @Override + public String getAction() { + return action; + } + + public Date getRemoved() { + return removed; + } + + public Date getCreated() { + return created; + } + + public void setDuration(Integer duration) { + this.duration = duration; + } + + public void setQuietTime(Integer quietTime) { + this.quietTime = quietTime; + } +} diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java new file mode 100644 index 00000000000..7e1c38af108 --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScaleVmGroupPolicyMapVO.java @@ -0,0 +1,64 @@ +// 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.as; + +import org.apache.cloudstack.api.InternalIdentity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name=("autoscale_vmgroup_policy_map")) +public class AutoScaleVmGroupPolicyMapVO implements InternalIdentity { + @Id + @GeneratedValue(strategy=GenerationType.IDENTITY) + @Column(name="id") + private long id; + + @Column(name="vmgroup_id") + private long vmGroupId; + + @Column(name="policy_id") + private long policyId; + + public AutoScaleVmGroupPolicyMapVO() { } + + public AutoScaleVmGroupPolicyMapVO(long vmGroupId, long policyId) { + this.vmGroupId = vmGroupId; + this.policyId = policyId; + } + + public AutoScaleVmGroupPolicyMapVO(long vmgroupId, long policyId, boolean revoke) { + this(vmgroupId, policyId); + } + + public long getId() { + return id; + } + + public long getVmGroupId() { + return vmGroupId; + } + + public long getPolicyId() { + return policyId; + } +} diff --git a/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java new file mode 100644 index 00000000000..d1d85f9e293 --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScaleVmGroupVO.java @@ -0,0 +1,191 @@ +// 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.as; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "autoscale_vmgroups") +@Inheritance(strategy = InheritanceType.JOINED) +public class AutoScaleVmGroupVO implements AutoScaleVmGroup, InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + long id; + + @Column(name = "uuid") + String uuid; + + @Column(name = "zone_id", updatable = false) + private long zoneId; + + @Column(name = "domain_id", updatable = false) + private long domainId; + + @Column(name = "account_id") + private long accountId; + + @Column(name = "load_balancer_id") + private Long loadBalancerId; + + @Column(name = "min_members", updatable = true) + private int minMembers; + + @Column(name = "max_members", updatable = true) + private int maxMembers; + + @Column(name = "member_port") + private int memberPort; + + @Column(name = "interval") + private int interval; + + @Column(name = "profile_id") + private long profileId; + + @Column(name = GenericDao.REMOVED_COLUMN) + protected Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + protected Date created; + + @Column(name = "state") + private String state; + + public AutoScaleVmGroupVO() { + } + + public AutoScaleVmGroupVO(long lbRuleId, long zoneId, long domainId, long accountId, int minMembers, int maxMembers, int memberPort, int interval, long profileId, String state) { + this.uuid = UUID.randomUUID().toString(); + this.loadBalancerId = lbRuleId; + this.minMembers = minMembers; + this.maxMembers = maxMembers; + this.memberPort = memberPort; + this.profileId = profileId; + this.accountId = accountId; + this.domainId = domainId; + this.zoneId = zoneId; + this.state = state; + this.interval = interval; + } + + @Override + public String toString() { + return new StringBuilder("AutoScaleVmGroupVO[").append("id").append("]").toString(); + } + + @Override + public long getId() { + return id; + } + + public long getZoneId() { + return zoneId; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public Long getLoadBalancerId() { + return loadBalancerId; + } + + @Override + public int getMinMembers() { + return minMembers; + } + + @Override + public int getMaxMembers() { + return maxMembers; + } + + @Override + public int getMemberPort() { + return memberPort; + } + + @Override + public int getInterval() { + return interval; + } + + @Override + public long getProfileId() { + return profileId; + } + + public Date getRemoved() { + return removed; + } + + public Date getCreated() { + return created; + } + + @Override + public String getState() { + return state; + } + + public void setState(String state) { + this.state = state; + } + + public void setMinMembers(int minMembers) { + this.minMembers = minMembers; + } + + public void setMaxMembers(int maxMembers) { + this.maxMembers = maxMembers; + } + + public void setInterval(Integer interval) { + this.interval = interval; + } + + public void setLoadBalancerId(Long loadBalancerId) { + this.loadBalancerId = loadBalancerId; + } + + @Override + public String getUuid() { + return uuid; + } +} diff --git a/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.java new file mode 100644 index 00000000000..011be2b41ca --- /dev/null +++ b/server/src/com/cloud/network/as/AutoScaleVmProfileVO.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.network.as; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Inheritance; +import javax.persistence.InheritanceType; +import javax.persistence.Table; + +import org.apache.cloudstack.api.Identity; +import com.cloud.utils.Pair; +import com.cloud.utils.db.GenericDao; +import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "autoscale_vmprofiles") +@Inheritance(strategy = InheritanceType.JOINED) +public class AutoScaleVmProfileVO implements AutoScaleVmProfile, Identity, InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + protected long id; + + @Column(name = "uuid") + protected String uuid; + + @Column(name = "zone_id", updatable = true, nullable = false) + protected Long zoneId; + + @Column(name = "domain_id", updatable = true) + private long domainId; + + @Column(name = "account_id") + private long accountId; + + @Column(name = "autoscale_user_id") + private long autoscaleUserId; + + @Column(name = "service_offering_id", updatable = true, nullable = false) + private Long serviceOfferingId; + + @Column(name = "template_id", updatable = true, nullable = false, length = 17) + private Long templateId; + + @Column(name = "other_deploy_params", updatable = true, length = 1024) + private String otherDeployParams; + + @Column(name = "destroy_vm_grace_period", updatable = true) + private Integer destroyVmGraceperiod = NetUtils.DEFAULT_AUTOSCALE_VM_DESTROY_TIME; + + @Column(name = "counter_params", updatable = true) + private String counterParams; + + @Column(name = GenericDao.REMOVED_COLUMN) + protected Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + protected Date created; + + public AutoScaleVmProfileVO() { + } + + public AutoScaleVmProfileVO(long zoneId, long domainId, long accountId, long serviceOfferingId, long templateId, String otherDeployParams, Map counterParamList, Integer destroyVmGraceperiod, + long autoscaleUserId) { + this.uuid = UUID.randomUUID().toString(); + this.zoneId = zoneId; + this.domainId = domainId; + this.accountId = accountId; + this.serviceOfferingId = serviceOfferingId; + this.templateId = templateId; + this.otherDeployParams = otherDeployParams; + this.autoscaleUserId = autoscaleUserId; + if (destroyVmGraceperiod != null) { + this.destroyVmGraceperiod = destroyVmGraceperiod; + } + setCounterParamsForUpdate(counterParamList); + } + + @Override + public String toString() { + return new StringBuilder("AutoScaleVMProfileVO[").append("id").append(id).append("-").append("templateId").append("-").append(templateId).append("]").toString(); + } + + @Override + public Long getTemplateId() { + return templateId; + } + + public void setTemplateId(Long templateId) { + this.templateId = templateId; + } + + @Override + public Long getServiceOfferingId() { + return serviceOfferingId; + } + + @Override + public String getOtherDeployParams() { + return otherDeployParams; + } + + public void setOtherDeployParams(String otherDeployParams) { + this.otherDeployParams = otherDeployParams; + } + + @Override + public List> getCounterParams() { + List> paramsList = new ArrayList>(); + if (counterParams != null) { + String[] params = counterParams.split("[=&]"); + for (int i = 0; i < (params.length - 1); i = i + 2) { + paramsList.add(new Pair(params[i], params[i + 1])); + } + } + return paramsList; + } + + public void setCounterParams(String counterParam) { + this.counterParams = counterParam; + } + + public void setCounterParamsForUpdate(Map counterParamList) { + StringBuilder sb = new StringBuilder(""); + boolean isFirstParam = true; + if (counterParamList != null) { + Iterator> iter = counterParamList.values().iterator(); + while (iter.hasNext()) { + HashMap paramKVpair = iter.next(); + if (!isFirstParam) { + sb.append("&"); + } + String paramName = paramKVpair.get("name"); + String paramValue = paramKVpair.get("value"); + sb.append(paramName + "=" + paramValue); + isFirstParam = false; + } + } + /* + * setCounterParams(String counterParam)'s String param is caught by UpdateBuilder and stored in an internal + * list. + * Which is used later to update the db. The variables in a VO object is not used to update the db. + * Hence calling the function which is intercepted. + */ + setCounterParams(sb.toString()); + } + + @Override + public String getUuid() { + return uuid; + } + + public void setAutoscaleUserId(long autoscaleUserId) { + this.autoscaleUserId = autoscaleUserId; + } + + @Override + public Long getZoneId() { + return zoneId; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public long getId() { + return id; + } + + @Override + public Integer getDestroyVmGraceperiod() { + return destroyVmGraceperiod; + } + + public void setDestroyVmGraceperiod(Integer destroyVmGraceperiod) { + this.destroyVmGraceperiod = destroyVmGraceperiod; + } + + @Override + public long getAutoScaleUserId() { + return autoscaleUserId; + } +} diff --git a/server/src/com/cloud/network/as/ConditionVO.java b/server/src/com/cloud/network/as/ConditionVO.java new file mode 100644 index 00000000000..bbae72f2312 --- /dev/null +++ b/server/src/com/cloud/network/as/ConditionVO.java @@ -0,0 +1,129 @@ +// 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.as; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.Identity; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "conditions") +public class ConditionVO implements Condition, Identity, InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "counter_id") + private long counterid; + + @Column(name = "threshold") + private long threshold; + + @Column(name = "relational_operator") + @Enumerated(value = EnumType.STRING) + private Operator relationalOperator; + + @Column(name = "domain_id") + protected long domainId; + + @Column(name = "account_id") + protected long accountId; + + @Column(name = "uuid") + private String uuid; + + @Column(name = GenericDao.REMOVED_COLUMN) + Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + Date created; + + public ConditionVO() { + } + + public ConditionVO(long counterid, long threshold, long accountId, long domainId, Operator relationalOperator) { + this.counterid = counterid; + this.threshold = threshold; + this.relationalOperator = relationalOperator; + this.accountId = accountId; + this.domainId = domainId; + this.uuid = UUID.randomUUID().toString(); + } + + public Date getCreated() { + return created; + } + + @Override + public long getId() { + return id; + } + + @Override + public String toString() { + return new StringBuilder("Condition[").append("id-").append(id).append("]").toString(); + } + + @Override + public long getCounterid() { + return counterid; + } + + @Override + public long getThreshold() { + return threshold; + } + + @Override + public Operator getRelationalOperator() { + return relationalOperator; + } + + @Override + public long getAccountId() { + return accountId; + } + + @Override + public long getDomainId() { + return domainId; + } + + @Override + public String getUuid() { + return this.uuid; + } + + public Date getRemoved() { + return removed; + } +} diff --git a/server/src/com/cloud/network/as/CounterVO.java b/server/src/com/cloud/network/as/CounterVO.java new file mode 100644 index 00000000000..b7b03f716b0 --- /dev/null +++ b/server/src/com/cloud/network/as/CounterVO.java @@ -0,0 +1,111 @@ +// 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.as; + +import java.util.Date; +import java.util.UUID; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import org.apache.cloudstack.api.Identity; +import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +@Entity +@Table(name = "counter") +public class CounterVO implements Counter, Identity, InternalIdentity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + @Column(name = "source") + @Enumerated(value = EnumType.STRING) + private Source source; + + @Column(name = "name") + private String name; + + @Column(name = "value") + private String value; + + @Column(name = "uuid") + private String uuid; + + @Column(name = GenericDao.REMOVED_COLUMN) + Date removed; + + @Column(name = GenericDao.CREATED_COLUMN) + Date created; + + public CounterVO() { + } + + public CounterVO(Source source, String name, String value) { + this.source = source; + this.name = name; + this.value = value; + this.uuid = UUID.randomUUID().toString(); + } + + @Override + public String toString() { + return new StringBuilder("Counter[").append("id-").append(id).append("]").toString(); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getValue() { + return value; + } + + @Override + public Source getSource() { + return source; + } + + @Override + public long getId() { + return id; + } + + @Override + public String getUuid() { + return this.uuid; + } + + public Date getRemoved() { + return removed; + } + + public Date getCreated() { + return created; + } +} diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java new file mode 100644 index 00000000000..88755bb3378 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDao.java @@ -0,0 +1,28 @@ +// 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.as.dao; + +import java.util.List; + +import com.cloud.network.as.AutoScalePolicyConditionMapVO; +import com.cloud.utils.db.GenericDao; + +public interface AutoScalePolicyConditionMapDao extends GenericDao { + List listByAll(Long policyId, Long conditionId); + public boolean isConditionInUse(Long conditionId); + boolean removeByAutoScalePolicyId(long id); +} diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.java new file mode 100644 index 00000000000..84dd191b072 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyConditionMapDaoImpl.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.network.as.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.as.AutoScalePolicyConditionMapVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchCriteria; + +@Local(value={AutoScalePolicyConditionMapDao.class}) +public class AutoScalePolicyConditionMapDaoImpl extends GenericDaoBase implements AutoScalePolicyConditionMapDao { + + private SearchCriteria getSearchCriteria(Long policyId, Long conditionId) + { + SearchCriteria sc = createSearchCriteria(); + + if(policyId != null) + sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); + + if(conditionId != null) + sc.addAnd("conditionId", SearchCriteria.Op.EQ, conditionId); + + return sc; + } + + @Override + public List listByAll(Long policyId, Long conditionId) { + return listBy(getSearchCriteria(policyId, conditionId)); + } + + public boolean isConditionInUse(Long conditionId) { + return findOneBy(getSearchCriteria(null, conditionId)) != null; + } + + @Override + public boolean removeByAutoScalePolicyId(long policyId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); + return expunge(sc) > 0; + } +} diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java new file mode 100644 index 00000000000..51b2a943de6 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyDao.java @@ -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. +package com.cloud.network.as.dao; + +import com.cloud.network.as.AutoScalePolicyVO; +import com.cloud.utils.db.GenericDao; + +public interface AutoScalePolicyDao extends GenericDao { + int removeByAccountId(long accountId); +} diff --git a/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java new file mode 100644 index 00000000000..f8f54915534 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScalePolicyDaoImpl.java @@ -0,0 +1,35 @@ +// 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.as.dao; + +import javax.ejb.Local; + +import com.cloud.network.as.AutoScalePolicyVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchCriteria; + +@Local(value = { AutoScalePolicyDao.class }) +public class AutoScalePolicyDaoImpl extends GenericDaoBase implements AutoScalePolicyDao { + + public int removeByAccountId(long accountId) { + SearchCriteria sc = createSearchCriteria(); + + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + + return remove(sc); + } +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java new file mode 100644 index 00000000000..a11bedda873 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDao.java @@ -0,0 +1,28 @@ +// 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.as.dao; + +import java.util.List; + +import com.cloud.network.as.AutoScaleVmGroupVO; +import com.cloud.utils.db.GenericDao; + +public interface AutoScaleVmGroupDao extends GenericDao { + List listByAll(Long loadBalancerId, Long profileId); + boolean isProfileInUse(long profileId); + boolean isAutoScaleLoadBalancer(Long loadBalancerId); +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDaoImpl.java new file mode 100644 index 00000000000..80f2bee7cbb --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupDaoImpl.java @@ -0,0 +1,62 @@ +// 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.as.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.as.AutoScaleVmGroupVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; + +@Local(value = { AutoScaleVmGroupDao.class }) +public class AutoScaleVmGroupDaoImpl extends GenericDaoBase implements AutoScaleVmGroupDao { + + @Override + public List listByAll(Long loadBalancerId, Long profileId) { + SearchCriteria sc = createSearchCriteria(); + + if(loadBalancerId != null) + sc.addAnd("loadBalancerId", SearchCriteria.Op.EQ, loadBalancerId); + + if(profileId != null) + sc.addAnd("profileId", SearchCriteria.Op.EQ, profileId); + + return listBy(sc); + } + + @Override + public boolean isProfileInUse(long profileId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("profileId", SearchCriteria.Op.EQ, profileId); + return findOneBy(sc) != null; + } + + @Override + public boolean isAutoScaleLoadBalancer(Long loadBalancerId) { + GenericSearchBuilder CountByAccount = createSearchBuilder(Long.class); + CountByAccount.select(null, Func.COUNT, null); + CountByAccount.and("loadBalancerId", CountByAccount.entity().getLoadBalancerId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = CountByAccount.create(); + sc.setParameters("loadBalancerId", loadBalancerId); + return customSearch(sc, null).get(0) > 0; + } +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDao.java b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDao.java new file mode 100644 index 00000000000..41d91f71c7e --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDao.java @@ -0,0 +1,30 @@ +// 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.as.dao; + +import java.util.List; + +import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; +import com.cloud.utils.db.GenericDao; + +public interface AutoScaleVmGroupPolicyMapDao extends GenericDao { + boolean removeByGroupId(long vmGroupId); + boolean removeByGroupAndPolicies(long vmGroupId, List bakupPolicyIds); + List listByVmGroupId(long vmGroupId); + List listByPolicyId(long policyId); + public boolean isAutoScalePolicyInUse(long policyId); +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDaoImpl.java new file mode 100644 index 00000000000..c33a55fe549 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmGroupPolicyMapDaoImpl.java @@ -0,0 +1,74 @@ +// 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.as.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value={AutoScaleVmGroupPolicyMapDao.class}) +public class AutoScaleVmGroupPolicyMapDaoImpl extends GenericDaoBase implements AutoScaleVmGroupPolicyMapDao { + + @Override + public boolean removeByGroupId(long vmGroupId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); + + return expunge(sc) > 0; + } + + @Override + public boolean removeByGroupAndPolicies(long vmGroupId, List policyIds) { + SearchBuilder policySearch = createSearchBuilder(); + policySearch.and("vmGroupId", policySearch.entity().getVmGroupId(), Op.EQ); + policySearch.and("policyIds", policySearch.entity().getPolicyId(), Op.IN); + policySearch.done(); + SearchCriteria sc = policySearch.create(); + sc.setParameters("vmGroupId", vmGroupId); + sc.setParameters("policyIds", policyIds); + return expunge(sc) > 0; + } + + @Override + public List listByVmGroupId(long vmGroupId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("vmGroupId", SearchCriteria.Op.EQ, vmGroupId); + return listBy(sc); + } + + @Override + public List listByPolicyId(long policyId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); + + return listBy(sc); + } + + @Override + public boolean isAutoScalePolicyInUse(long policyId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("policyId", SearchCriteria.Op.EQ, policyId); + return findOneBy(sc) != null; + } + +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDao.java b/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDao.java new file mode 100644 index 00000000000..d97e848a081 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDao.java @@ -0,0 +1,25 @@ +// 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.as.dao; + +import com.cloud.network.as.AutoScaleVmProfileVO; +import com.cloud.utils.db.GenericDao; + +public interface AutoScaleVmProfileDao extends GenericDao { + + int removeByAccountId(long accountId); +} diff --git a/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDaoImpl.java b/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDaoImpl.java new file mode 100644 index 00000000000..d2b162b5915 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/AutoScaleVmProfileDaoImpl.java @@ -0,0 +1,35 @@ +// 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.as.dao; + +import javax.ejb.Local; + +import com.cloud.network.as.AutoScaleVmProfileVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchCriteria; + +@Local(value = { AutoScaleVmProfileDao.class }) +public class AutoScaleVmProfileDaoImpl extends GenericDaoBase implements AutoScaleVmProfileDao { + + @Override + public int removeByAccountId(long accountId) { + SearchCriteria sc = createSearchCriteria(); + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + + return remove(sc); + } +} diff --git a/server/src/com/cloud/network/as/dao/ConditionDao.java b/server/src/com/cloud/network/as/dao/ConditionDao.java new file mode 100644 index 00000000000..128920d1b87 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/ConditionDao.java @@ -0,0 +1,28 @@ +// 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.as.dao; + +import com.cloud.network.as.ConditionVO; +import com.cloud.utils.db.GenericDao; + +public interface ConditionDao extends GenericDao { + + ConditionVO findByCounterId(long ctrId); + + int removeByAccountId(long accountId); +} diff --git a/server/src/com/cloud/network/as/dao/ConditionDaoImpl.java b/server/src/com/cloud/network/as/dao/ConditionDaoImpl.java new file mode 100644 index 00000000000..4f71d451512 --- /dev/null +++ b/server/src/com/cloud/network/as/dao/ConditionDaoImpl.java @@ -0,0 +1,53 @@ +// 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.as.dao; + +import javax.ejb.Local; + +import com.cloud.network.as.ConditionVO; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value = ConditionDao.class) +public class ConditionDaoImpl extends GenericDaoBase implements ConditionDao { + final SearchBuilder AllFieldsSearch; + + protected ConditionDaoImpl() { + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.and("counterId", AllFieldsSearch.entity().getCounterid(), Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public ConditionVO findByCounterId(long ctrId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("counterId", ctrId); + return findOneBy(sc); + } + + public int removeByAccountId(long accountId) { + SearchCriteria sc = createSearchCriteria(); + + sc.addAnd("accountId", SearchCriteria.Op.EQ, accountId); + + return remove(sc); + } +} diff --git a/server/src/com/cloud/network/as/dao/CounterDao.java b/server/src/com/cloud/network/as/dao/CounterDao.java new file mode 100644 index 00000000000..47b0d4876fa --- /dev/null +++ b/server/src/com/cloud/network/as/dao/CounterDao.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.network.as.dao; + +import java.util.List; + +import com.cloud.network.as.CounterVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDao; + +public interface CounterDao extends GenericDao { + public List listCounters(Long id, String name, String source, String keyword, Filter filter); + +} diff --git a/server/src/com/cloud/network/as/dao/CounterDaoImpl.java b/server/src/com/cloud/network/as/dao/CounterDaoImpl.java new file mode 100644 index 00000000000..829d538140e --- /dev/null +++ b/server/src/com/cloud/network/as/dao/CounterDaoImpl.java @@ -0,0 +1,67 @@ +// 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.as.dao; + +import java.util.List; + +import javax.ejb.Local; + +import com.cloud.network.as.CounterVO; +import com.cloud.utils.db.Filter; +import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.SearchBuilder; +import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Op; + +@Local(value = CounterDao.class) +public class CounterDaoImpl extends GenericDaoBase implements CounterDao { + final SearchBuilder AllFieldsSearch; + + protected CounterDaoImpl() { + AllFieldsSearch = createSearchBuilder(); + AllFieldsSearch.and("id", AllFieldsSearch.entity().getId(), Op.EQ); + AllFieldsSearch.and("name", AllFieldsSearch.entity().getName(), Op.LIKE); + AllFieldsSearch.and("source", AllFieldsSearch.entity().getSource(), Op.EQ); + AllFieldsSearch.done(); + } + + @Override + public List listCounters(Long id, String name, String source, String keyword, Filter filter) { + SearchCriteria sc = AllFieldsSearch.create(); + + if (keyword != null) { + SearchCriteria ssc = createSearchCriteria(); + ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); + sc.addAnd("name", SearchCriteria.Op.SC, ssc); + } + + if (name != null) { + sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + name + "%"); + } + + if (id != null) { + sc.addAnd("id", SearchCriteria.Op.EQ, id); + } + + if (source != null) { + sc.addAnd("source", SearchCriteria.Op.EQ, source); + } + return listBy(sc, filter); + } + +} diff --git a/server/src/com/cloud/network/dao/FirewallRulesDao.java b/server/src/com/cloud/network/dao/FirewallRulesDao.java index 2a4c200f116..cc184c84fce 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDao.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDao.java @@ -56,6 +56,6 @@ public interface FirewallRulesDao extends GenericDao { long countRulesByIpId(long sourceIpId); List listByNetworkPurposeTrafficTypeAndNotRevoked(long networkId, FirewallRule.Purpose purpose, FirewallRule.TrafficType trafficType); - - + + List listByIpAndPurposeWithState(Long addressId, FirewallRule.Purpose purpose, FirewallRule.State state); } diff --git a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java index 4b40ab482e2..180468c97b5 100644 --- a/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java +++ b/server/src/com/cloud/network/dao/FirewallRulesDaoImpl.java @@ -313,4 +313,19 @@ public class FirewallRulesDaoImpl extends GenericDaoBase i return result; } + @Override + public List listByIpAndPurposeWithState(Long ipId, Purpose purpose, State state) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("ipId", ipId); + + if (state != null) { + sc.setParameters("state", state); + } + + if (purpose != null) { + sc.setParameters("purpose", purpose); + } + + return listBy(sc); + } } diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java index 24dcf45ef2b..f717344ac2e 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java +++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapDao.java @@ -28,5 +28,5 @@ public interface LoadBalancerVMMapDao extends GenericDao listByLoadBalancerId(long loadBalancerId); List listByLoadBalancerId(long loadBalancerId, boolean revoke); LoadBalancerVMMapVO findByLoadBalancerIdAndVmId(long loadBalancerId, long instanceId); - + boolean isVmAttachedToLoadBalancer(long loadBalancerId); } diff --git a/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java b/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java index 527b53f1b5e..a1a1c4fffa6 100644 --- a/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java +++ b/server/src/com/cloud/network/dao/LoadBalancerVMMapDaoImpl.java @@ -24,7 +24,9 @@ import org.springframework.stereotype.Component; import com.cloud.network.LoadBalancerVMMapVO; import com.cloud.utils.db.GenericDaoBase; +import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.SearchCriteria; +import com.cloud.utils.db.SearchCriteria.Func; @Component @Local(value={LoadBalancerVMMapDao.class}) @@ -83,5 +85,14 @@ public class LoadBalancerVMMapDaoImpl extends GenericDaoBase CountByAccount = createSearchBuilder(Long.class); + CountByAccount.select(null, Func.COUNT, null); + CountByAccount.and("loadBalancerId", CountByAccount.entity().getLoadBalancerId(), SearchCriteria.Op.EQ); + + SearchCriteria sc = CountByAccount.create(); + sc.setParameters("loadBalancerId", loadBalancerId); + return customSearch(sc, null).get(0) > 0; + } } diff --git a/server/src/com/cloud/network/dao/NetworkDao.java b/server/src/com/cloud/network/dao/NetworkDao.java index a2e37b7b33b..1fefb75a360 100644 --- a/server/src/com/cloud/network/dao/NetworkDao.java +++ b/server/src/com/cloud/network/dao/NetworkDao.java @@ -108,4 +108,7 @@ public interface NetworkDao extends GenericDao { long countVpcNetworks(long vpcId); + List listNetworksByAccount(long accountId, long zoneId, Network.GuestType type, boolean isSystem); + + List listRedundantNetworks(); } diff --git a/server/src/com/cloud/network/dao/NetworkDaoImpl.java b/server/src/com/cloud/network/dao/NetworkDaoImpl.java index 9a21346c79b..c6440c3efa2 100644 --- a/server/src/com/cloud/network/dao/NetworkDaoImpl.java +++ b/server/src/com/cloud/network/dao/NetworkDaoImpl.java @@ -25,9 +25,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.persistence.TableGenerator; -import org.springframework.stereotype.Component; - -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.network.Network; import com.cloud.network.Network.GuestType; import com.cloud.network.Network.Provider; @@ -63,31 +61,31 @@ import com.cloud.utils.net.NetUtils; @Local(value = NetworkDao.class) @DB(txn = false) public class NetworkDaoImpl extends GenericDaoBase implements NetworkDao { - SearchBuilder AllFieldsSearch; - SearchBuilder AccountSearch; - SearchBuilder RelatedConfigSearch; - SearchBuilder AccountNetworkSearch; - SearchBuilder ZoneBroadcastUriSearch; - SearchBuilder ZoneSecurityGroupSearch; - GenericSearchBuilder CountBy; - SearchBuilder PhysicalNetworkSearch; - SearchBuilder SecurityGroupSearch; - GenericSearchBuilder NetworksRegularUserCanCreateSearch; - GenericSearchBuilder NetworksCount; - SearchBuilder SourceNATSearch; - GenericSearchBuilder CountByZoneAndURI; - GenericSearchBuilder VpcNetworksCount; - - - @Inject ResourceTagsDaoImpl _tagsDao; - @Inject NetworkAccountDaoImpl _accountsDao; - @Inject NetworkDomainDaoImpl _domainsDao; - @Inject NetworkOpDaoImpl _opDao; - @Inject NetworkServiceMapDaoImpl _ntwkSvcMap; - @Inject NetworkOfferingDaoImpl _ntwkOffDao; + final SearchBuilder AllFieldsSearch; + final SearchBuilder AccountSearch; + final SearchBuilder RelatedConfigSearch; + final SearchBuilder AccountNetworkSearch; + final SearchBuilder ZoneBroadcastUriSearch; + final SearchBuilder ZoneSecurityGroupSearch; + final GenericSearchBuilder CountBy; + final SearchBuilder PhysicalNetworkSearch; + final SearchBuilder SecurityGroupSearch; + final GenericSearchBuilder NetworksRegularUserCanCreateSearch; + private final GenericSearchBuilder NetworksCount; + 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); + NetworkOpDaoImpl _opDao = ComponentLocator.inject(NetworkOpDaoImpl.class); + NetworkServiceMapDaoImpl _ntwkSvcMap = ComponentLocator.inject(NetworkServiceMapDaoImpl.class); + NetworkOfferingDaoImpl _ntwkOffDao = ComponentLocator.inject(NetworkOfferingDaoImpl.class); - TableGenerator _tgMacAddress; + final TableGenerator _tgMacAddress; Random _rand = new Random(System.currentTimeMillis()); long _prefix = 0x2; @@ -110,6 +108,7 @@ public class NetworkDaoImpl extends GenericDaoBase implements N AllFieldsSearch.and("vpcId", AllFieldsSearch.entity().getVpcId(), Op.EQ); SearchBuilder join1 = _ntwkOffDao.createSearchBuilder(); join1.and("isSystem", join1.entity().isSystemOnly(), Op.EQ); + join1.and("isRedundant", join1.entity().getRedundantRouter(), Op.EQ); AllFieldsSearch.join("offerings", join1, AllFieldsSearch.entity().getNetworkOfferingId(), join1.entity().getId(), JoinBuilder.JoinType.INNER); AllFieldsSearch.done(); @@ -209,6 +208,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 @@ -558,4 +568,24 @@ 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; + } + + @Override + public List listRedundantNetworks() { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setJoinParameters("offerings", "isRedundant", true); + + return listBy(sc, null); + } } diff --git a/server/src/com/cloud/network/dao/NetworkOpVO.java b/server/src/com/cloud/network/dao/NetworkOpVO.java index 5beb55cb13d..8d417278188 100644 --- a/server/src/com/cloud/network/dao/NetworkOpVO.java +++ b/server/src/com/cloud/network/dao/NetworkOpVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @@ -23,7 +25,7 @@ import javax.persistence.Table; @Entity @Table(name="op_networks") -public class NetworkOpVO { +public class NetworkOpVO implements InternalIdentity { @Id @Column(name="id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java index d98f86e96be..59967045dbe 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkIsolationMethodVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -28,7 +30,7 @@ import javax.persistence.Table; */ @Entity @Table(name = "physical_network_isolation_methods") -public class PhysicalNetworkIsolationMethodVO { +public class PhysicalNetworkIsolationMethodVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java index 12b08af9327..370e4982156 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkServiceProviderVO.java @@ -33,10 +33,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Service; import com.cloud.network.PhysicalNetworkServiceProvider; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "physical_network_service_providers") -public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceProvider { +public class PhysicalNetworkServiceProviderVO implements PhysicalNetworkServiceProvider, InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java index bca1a45ba12..787c049d3c0 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTagVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.dao; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -28,7 +30,7 @@ import javax.persistence.Table; */ @Entity @Table(name = "physical_network_tags") -public class PhysicalNetworkTagVO { +public class PhysicalNetworkTagVO implements InternalIdentity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java index 2efd904b7e0..42e5b4e0a35 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDao.java @@ -16,14 +16,16 @@ // under the License. package com.cloud.network.dao; + import java.util.List; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Networks.TrafficType; +import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; public interface PhysicalNetworkTrafficTypeDao extends GenericDao { - List listBy(long physicalNetworkId); + Pair, Integer> listAndCountBy(long physicalNetworkId); boolean isTrafficTypeSupported(long physicalNetworkId, TrafficType trafficType); String getNetworkTag (long physicalNetworkId, TrafficType trafficType, HypervisorType hType); PhysicalNetworkTrafficTypeVO findBy(long physicalNetworkId, TrafficType trafficType); diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java index b93219a5b00..7e4723965a8 100755 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeDaoImpl.java @@ -24,6 +24,7 @@ import org.springframework.stereotype.Component; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.network.Networks.TrafficType; +import com.cloud.utils.Pair; import com.cloud.utils.db.DB; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; @@ -80,10 +81,10 @@ public class PhysicalNetworkTrafficTypeDaoImpl extends GenericDaoBase listBy(long physicalNetworkId) { + public Pair, Integer> listAndCountBy(long physicalNetworkId) { SearchCriteria sc = physicalNetworkSearch.create(); sc.setParameters("physicalNetworkId", physicalNetworkId); - return search(sc, null); + return searchAndCount(sc, null); } @Override diff --git a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java index 0561ae86fb9..4c32d0a949b 100644 --- a/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java +++ b/server/src/com/cloud/network/dao/PhysicalNetworkTrafficTypeVO.java @@ -29,6 +29,7 @@ import javax.persistence.Table; import com.cloud.network.Networks.TrafficType; import com.cloud.network.PhysicalNetworkTrafficType; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "physical_network_traffic_types") diff --git a/server/src/com/cloud/network/element/BareMetalElement.java b/server/src/com/cloud/network/element/BareMetalElement.java index b8e45e4283a..d13cf141c0d 100644 --- a/server/src/com/cloud/network/element/BareMetalElement.java +++ b/server/src/com/cloud/network/element/BareMetalElement.java @@ -105,7 +105,7 @@ public class BareMetalElement extends AdapterBase implements NetworkElement { } @Override - public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java index 616a979d77f..0cf632cb666 100644 --- a/server/src/com/cloud/network/element/CloudZonesNetworkElement.java +++ b/server/src/com/cloud/network/element/CloudZonesNetworkElement.java @@ -131,7 +131,7 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem } @Override - public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network config, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return false; // assume that the agent will remove userdata etc } @@ -253,6 +253,12 @@ public class CloudZonesNetworkElement extends AdapterBase implements NetworkElem return false; } + @Override + public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile vm) throws ResourceUnavailableException { + // TODO Auto-generated method stub + return false; + } + @Override public boolean verifyServicesCombination(Set services) { return true; diff --git a/server/src/com/cloud/network/element/ExternalDhcpElement.java b/server/src/com/cloud/network/element/ExternalDhcpElement.java index 29201ee1b78..0f99abdc698 100755 --- a/server/src/com/cloud/network/element/ExternalDhcpElement.java +++ b/server/src/com/cloud/network/element/ExternalDhcpElement.java @@ -116,7 +116,7 @@ public class ExternalDhcpElement extends AdapterBase implements NetworkElement, } @Override - public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/server/src/com/cloud/network/element/SecurityGroupElement.java b/server/src/com/cloud/network/element/SecurityGroupElement.java index 09b8df714ba..bcc8ecc9269 100644 --- a/server/src/com/cloud/network/element/SecurityGroupElement.java +++ b/server/src/com/cloud/network/element/SecurityGroupElement.java @@ -89,7 +89,7 @@ public class SecurityGroupElement extends AdapterBase implements NetworkElement } @Override - public boolean destroy(Network network) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network network, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/server/src/com/cloud/network/element/VirtualRouterElement.java b/server/src/com/cloud/network/element/VirtualRouterElement.java index 7f278435d0b..481844364a6 100755 --- a/server/src/com/cloud/network/element/VirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VirtualRouterElement.java @@ -25,11 +25,11 @@ import java.util.Set; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.cloudstack.api.command.admin.router.ConfigureVirtualRouterElementCmd; +import org.apache.cloudstack.api.command.admin.router.ListVirtualRouterElementsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ConfigureVirtualRouterElementCmd; -import com.cloud.api.commands.ListVirtualRouterElementsCmd; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenter; @@ -623,7 +623,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl if (!result) { s_logger.warn("Failed to stop virtual router element " + router + ", but would try to process clean up anyway."); } - result = (_routerMgr.destroyRouter(router.getId()) != null); + result = (_routerMgr.destroyRouter(router.getId(), context.getAccount(), context.getCaller().getId()) != null); if (!result) { s_logger.warn("Failed to clean up virtual router element " + router); } @@ -633,14 +633,14 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network config, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { List routers = _routerDao.listByNetworkAndRole(config.getId(), Role.VIRTUAL_ROUTER); if (routers == null || routers.isEmpty()) { return true; } boolean result = true; for (DomainRouterVO router : routers) { - result = result && (_routerMgr.destroyRouter(router.getId()) != null); + result = result && (_routerMgr.destroyRouter(router.getId(), context.getAccount(), context.getCaller().getId()) != null); } return result; } @@ -664,8 +664,26 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl } @Override - public String getPropertiesFile() { - return "virtualrouter_commands.properties"; + public boolean saveUserData(Network network, NicProfile nic, VirtualMachineProfile vm) + throws ResourceUnavailableException { + if (!canHandle(network, null)) { + return false; + } + List routers = _routerDao.listByNetworkAndRole(network.getId(), Role.VIRTUAL_ROUTER); + if (routers == null || routers.isEmpty()) { + s_logger.debug("Can't find virtual router element in network " + network.getId()); + return true; + } + + @SuppressWarnings("unchecked") + VirtualMachineProfile uservm = (VirtualMachineProfile) vm; + + return _routerMgr.saveUserDataToRouter(network, nic, uservm, routers); + } + + @Override + public String[] getPropertiesFiles() { + return new String[] { "virtualrouter_commands.properties" }; } @Override @@ -738,7 +756,7 @@ public class VirtualRouterElement extends AdapterBase implements VirtualRouterEl List routers = _routerDao.listByElementId(elementId); boolean result = true; for (DomainRouterVO router : routers) { - result = result && (_routerMgr.destroyRouter(router.getId()) != null); + result = result && (_routerMgr.destroyRouter(router.getId(), context.getAccount(), context.getCaller().getId()) != null); } _vrProviderDao.remove(elementId); diff --git a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java index c491fd2004e..ff2b6210504 100644 --- a/server/src/com/cloud/network/element/VirtualRouterProviderVO.java +++ b/server/src/com/cloud/network/element/VirtualRouterProviderVO.java @@ -30,6 +30,7 @@ import javax.persistence.Table; import com.cloud.network.VirtualRouterProvider; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name=("virtual_router_providers")) diff --git a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java index ca1378400eb..49ca0b4878d 100644 --- a/server/src/com/cloud/network/element/VpcVirtualRouterElement.java +++ b/server/src/com/cloud/network/element/VpcVirtualRouterElement.java @@ -124,14 +124,14 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc } @Override - public boolean shutdownVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { List routers = _routerDao.listByVpcId(vpc.getId()); if (routers == null || routers.isEmpty()) { return true; } boolean result = true; for (DomainRouterVO router : routers) { - result = result && (_routerMgr.destroyRouter(router.getId()) != null); + result = result && (_routerMgr.destroyRouter(router.getId(), context.getAccount(), context.getCaller().getId()) != null); } return result; } @@ -254,7 +254,7 @@ public class VpcVirtualRouterElement extends VirtualRouterElement implements Vpc } @Override - public boolean destroy(Network config) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroy(Network config, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { boolean success = true; Long vpcId = config.getVpcId(); if (vpcId == null) { diff --git a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java index 489ecaa6f97..6193d1117ff 100644 --- a/server/src/com/cloud/network/firewall/FirewallManagerImpl.java +++ b/server/src/com/cloud/network/firewall/FirewallManagerImpl.java @@ -27,10 +27,10 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.firewall.ListFirewallRulesCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ListFirewallRulesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.dao.DomainDao; @@ -68,6 +68,7 @@ import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; import com.cloud.user.UserContext; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; @@ -208,7 +209,7 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma } @Override - public List listFirewallRules(ListFirewallRulesCmd cmd) { + public Pair, Integer> listFirewallRules(ListFirewallRulesCmd cmd) { Long ipId = cmd.getIpAddressId(); Long id = cmd.getId(); Map tags = cmd.getTags(); @@ -274,7 +275,8 @@ public class FirewallManagerImpl implements FirewallService, FirewallManager, Ma sc.setParameters("purpose", Purpose.Firewall); - return _firewallDao.search(sc, filter); + Pair, Integer> result = _firewallDao.searchAndCount(sc, filter); + return new Pair, Integer>(result.first(), result.second()); } @Override diff --git a/server/src/com/cloud/network/guru/GuestNetworkGuru.java b/server/src/com/cloud/network/guru/GuestNetworkGuru.java index 8bd05bb978e..97c1d5f6c45 100755 --- a/server/src/com/cloud/network/guru/GuestNetworkGuru.java +++ b/server/src/com/cloud/network/guru/GuestNetworkGuru.java @@ -155,25 +155,7 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur } protected abstract boolean canHandle(NetworkOffering offering, final NetworkType networkType, PhysicalNetwork physicalNetwork); -/* protected boolean canHandle(NetworkOffering offering, final NetworkType networkType, final List isolationMethods) { - // This guru handles only Guest Isolated network that supports Source nat service -<<<<<<< HEAD - if (dc.getNetworkType() == NetworkType.Advanced && isMyTrafficType(offering.getTrafficType()) - && offering.getGuestType() == Network.GuestType.Isolated && !offering.isSystemOnly()) { -======= - if (networkType == NetworkType.Advanced - && isMyTrafficType(offering.getTrafficType()) - && offering.getGuestType() == Network.GuestType.Isolated - && isMyIsolationMethod(isolationMethods)) { ->>>>>>> master - return true; - } else { - s_logger.trace("We only take care of non-system Guest networks of type " + GuestType.Isolated + " in zone of type " - + NetworkType.Advanced); - return false; - } - } -*/ + @Override public Network design(NetworkOffering offering, DeploymentPlan plan, Network userSpecified, Account owner) { DataCenter dc = _dcDao.findById(plan.getDataCenterId()); @@ -444,15 +426,17 @@ public abstract class GuestNetworkGuru extends AdapterBase implements NetworkGur @Override public void shutdown(NetworkProfile profile, NetworkOffering offering) { + + if (profile.getBroadcastDomainType() == BroadcastDomainType.Vlan && + profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) { s_logger.debug("Releasing vnet for the network id=" + profile.getId()); - if (profile.getBroadcastUri() != null && !offering.getSpecifyVlan()) { _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/lb/LoadBalancingRulesManager.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java index d901663bd91..c9b3f9336b8 100644 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManager.java @@ -18,7 +18,7 @@ package com.cloud.network.lb; import java.util.List; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLoadBalancerRuleCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.lb.LoadBalancingRule.LbDestination; @@ -28,21 +28,23 @@ import com.cloud.network.rules.LoadBalancer; import com.cloud.user.Account; public interface LoadBalancingRulesManager extends LoadBalancingRulesService { - + LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException; - + boolean removeAllLoadBalanacersForIp(long ipId, Account caller, long callerUserId); boolean removeAllLoadBalanacersForNetwork(long networkId, Account caller, long callerUserId); List getExistingDestinations(long lbId); List getStickinessPolicies(long lbId); List getStickinessMethods(long networkid); - + /** * Remove vm from all load balancers * @param vmId * @return true if removal is successful */ boolean removeVmFromLoadBalancers(long vmId); - + boolean applyLoadBalancersForNetwork(long networkId) throws ResourceUnavailableException; + String getLBCapability(long networkid, String capabilityName); + boolean configureLbAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException; } diff --git a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java index 8f97eae0195..0ffdcea8473 100755 --- a/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java +++ b/server/src/com/cloud/network/lb/LoadBalancingRulesManagerImpl.java @@ -18,6 +18,7 @@ package com.cloud.network.lb; import java.security.InvalidParameterException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; @@ -30,17 +31,20 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.loadbalancer.*; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.CreateLBStickinessPolicyCmd; -import com.cloud.api.commands.CreateLoadBalancerRuleCmd; -import com.cloud.api.commands.ListLBStickinessPoliciesCmd; -import com.cloud.api.commands.ListLoadBalancerRuleInstancesCmd; -import com.cloud.api.commands.ListLoadBalancerRulesCmd; -import com.cloud.api.commands.UpdateLoadBalancerRuleCmd; -import com.cloud.api.response.ServiceResponse; +import org.apache.cloudstack.api.command.user.loadbalancer.CreateLBStickinessPolicyCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRuleInstancesCmd; +import org.apache.cloudstack.api.command.user.loadbalancer.ListLoadBalancerRulesCmd; +import org.apache.cloudstack.api.response.ServiceResponse; +import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.dao.ConfigurationDao; +import com.cloud.dc.DataCenter; +import com.cloud.dc.DataCenter.NetworkType; +import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.VlanDao; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; @@ -65,6 +69,21 @@ 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.as.AutoScalePolicy; +import com.cloud.network.as.AutoScalePolicyConditionMapVO; +import com.cloud.network.as.AutoScaleVmGroup; +import com.cloud.network.as.AutoScaleVmGroupPolicyMapVO; +import com.cloud.network.as.AutoScaleVmGroupVO; +import com.cloud.network.as.AutoScaleVmProfile; +import com.cloud.network.as.Condition; +import com.cloud.network.as.Counter; +import com.cloud.network.as.dao.AutoScalePolicyConditionMapDao; +import com.cloud.network.as.dao.AutoScalePolicyDao; +import com.cloud.network.as.dao.AutoScaleVmGroupDao; +import com.cloud.network.as.dao.AutoScaleVmGroupPolicyMapDao; +import com.cloud.network.as.dao.AutoScaleVmProfileDao; +import com.cloud.network.as.dao.ConditionDao; +import com.cloud.network.as.dao.CounterDao; import com.cloud.network.dao.FirewallRulesCidrsDao; import com.cloud.network.dao.FirewallRulesDao; import com.cloud.network.dao.IPAddressDao; @@ -73,6 +92,10 @@ import com.cloud.network.dao.LoadBalancerDao; import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkServiceMapDao; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScalePolicy; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmGroup; +import com.cloud.network.lb.LoadBalancingRule.LbAutoScaleVmProfile; +import com.cloud.network.lb.LoadBalancingRule.LbCondition; import com.cloud.network.lb.LoadBalancingRule.LbDestination; import com.cloud.network.lb.LoadBalancingRule.LbStickinessPolicy; import com.cloud.network.rules.FirewallManager; @@ -89,14 +112,20 @@ import com.cloud.network.vpc.VpcManager; import com.cloud.offering.NetworkOffering; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.service.dao.ServiceOfferingDao; +import com.cloud.storage.dao.VMTemplateDao; import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; +import com.cloud.template.TemplateManager; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.DomainService; +import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; +import com.cloud.user.dao.UserDao; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; @@ -163,6 +192,8 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa @Inject ConfigurationManager _configMgr; @Inject + TemplateManager _templateMgr; + @Inject ExternalLoadBalancerUsageManager _externalLBUsageMgr; @Inject NetworkServiceMapDao _ntwkSrvcDao; @@ -170,8 +201,35 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa ResourceTagDao _resourceTagDao; @Inject VpcManager _vpcMgr; + @Inject + VMTemplateDao _templateDao; + @Inject + ServiceOfferingDao _offeringsDao; + @Inject + CounterDao _counterDao; + @Inject + ConditionDao _conditionDao; + @Inject + AutoScaleVmProfileDao _autoScaleVmProfileDao; + @Inject + AutoScalePolicyDao _autoScalePolicyDao; + @Inject + AutoScalePolicyConditionMapDao _autoScalePolicyConditionMapDao; + @Inject + AutoScaleVmGroupDao _autoScaleVmGroupDao; + @Inject + AutoScaleVmGroupPolicyMapDao _autoScaleVmGroupPolicyMapDao; + @Inject + ConfigurationDao _configDao; + @Inject + DataCenterDao _dcDao = null; + @Inject + UserDao _userDao; - private String getLBStickinessCapability(long networkid) { + + // Will return a string. For LB Stickiness this will be a json, for autoscale this will be "," separated values + @Override + public String getLBCapability(long networkid, String capabilityName) { Map> serviceCapabilitiesMap = _networkMgr.getNetworkCapabilities(networkid); if (serviceCapabilitiesMap != null) { for (Service service : serviceCapabilitiesMap.keySet()) { @@ -183,8 +241,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (serviceCapabilities != null) { for (Capability capability : serviceCapabilities .keySet()) { - if (Capability.SupportedStickinessMethods.getName() - .equals(capability.getName())) { + if (capabilityName.equals(capability.getName())) { return serviceCapabilities.get(capability); } } @@ -194,6 +251,137 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } return null; } + private LbAutoScaleVmGroup getLbAutoScaleVmGroup(AutoScaleVmGroupVO vmGroup, String currentState, LoadBalancerVO lb) { + long lbNetworkId = lb.getNetworkId(); + String lbName = lb.getName(); + List vmGroupPolicyMapList = _autoScaleVmGroupPolicyMapDao.listByVmGroupId(vmGroup.getId()); + List autoScalePolicies = new ArrayList(); + for (AutoScaleVmGroupPolicyMapVO vmGroupPolicyMap : vmGroupPolicyMapList) { + AutoScalePolicy autoScalePolicy = _autoScalePolicyDao.findById(vmGroupPolicyMap.getPolicyId()); + List autoScalePolicyConditionMapList = _autoScalePolicyConditionMapDao.listByAll(autoScalePolicy.getId(), null); + List lbConditions = new ArrayList(); + for (AutoScalePolicyConditionMapVO autoScalePolicyConditionMap : autoScalePolicyConditionMapList) { + Condition condition = _conditionDao.findById(autoScalePolicyConditionMap.getConditionId()); + Counter counter = _counterDao.findById(condition.getCounterid()); + lbConditions.add(new LbCondition(counter, condition)); + } + autoScalePolicies.add(new LbAutoScalePolicy(autoScalePolicy, lbConditions)); + } + AutoScaleVmProfile autoScaleVmProfile = _autoScaleVmProfileDao.findById(vmGroup.getProfileId()); + Long autoscaleUserId = autoScaleVmProfile.getAutoScaleUserId(); + User user = _userDao.findByIdIncludingRemoved(autoscaleUserId); + String apiKey = user.getApiKey(); + String secretKey = user.getSecretKey(); + String csUrl = _configDao.getValue(Config.EndpointeUrl.key()); + String zoneId = _dcDao.findById(autoScaleVmProfile.getZoneId()).getUuid(); + String domainId = _domainDao.findById(autoScaleVmProfile.getDomainId()).getUuid(); + String serviceOfferingId = _offeringsDao.findById(autoScaleVmProfile.getServiceOfferingId()).getUuid(); + String templateId = _templateDao.findById(autoScaleVmProfile.getTemplateId()).getUuid(); + String vmName = "AutoScale-LB-" + lbName; + String lbNetworkUuid = null; + + DataCenter zone = _configMgr.getZone(vmGroup.getZoneId()); + if (zone == null) { + // This should never happen, but still a cautious check + s_logger.warn("Unable to find zone while packaging AutoScale Vm Group, zoneid: " + vmGroup.getZoneId()); + throw new InvalidParameterValueException("Unable to find zone"); + } else { + if (zone.getNetworkType() == NetworkType.Advanced) { + NetworkVO lbNetwork = _networkDao.findById(lbNetworkId); + lbNetworkUuid = lbNetwork.getUuid(); + } + } + + + if (apiKey == null) { + throw new InvalidParameterValueException("apiKey for user: " + user.getUsername() + " is empty. Please generate it"); + } + + if (secretKey == null) { + throw new InvalidParameterValueException("secretKey for user: " + user.getUsername() + " is empty. Please generate it"); + } + + if (csUrl == null || csUrl.contains("localhost")) { + throw new InvalidParameterValueException("Global setting endpointe.url has to be set to the Management Server's API end point"); + } + + + LbAutoScaleVmProfile lbAutoScaleVmProfile = new LbAutoScaleVmProfile(autoScaleVmProfile, apiKey, secretKey, csUrl, zoneId, domainId, serviceOfferingId, templateId, vmName, lbNetworkUuid); + return new LbAutoScaleVmGroup(vmGroup, autoScalePolicies, lbAutoScaleVmProfile, currentState); + } + + private boolean applyAutoScaleConfig(LoadBalancerVO lb, AutoScaleVmGroupVO vmGroup, String currentState) throws ResourceUnavailableException { + LbAutoScaleVmGroup lbAutoScaleVmGroup = getLbAutoScaleVmGroup(vmGroup, currentState, lb); + /* Regular config like destinations need not be packed for applying autoscale config as of today.*/ + LoadBalancingRule rule = new LoadBalancingRule(lb, null, null); + rule.setAutoScaleVmGroup(lbAutoScaleVmGroup); + + if (!isRollBackAllowedForProvider(lb)) { + // this is for Netscaler type of devices. if their is failure the db entries will be rollbacked. + return false; + } + + List rules = Arrays.asList(rule); + + if (!_networkMgr.applyRules(rules, false)) { + s_logger.debug("LB rules' autoscale config are not completely applied"); + return false; + } + + return true; + } + + @Override + @DB + public boolean configureLbAutoScaleVmGroup(long vmGroupid, String currentState) throws ResourceUnavailableException { + AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.findById(vmGroupid); + boolean success = false; + + LoadBalancerVO loadBalancer = _lbDao.findById(vmGroup.getLoadBalancerId()); + + FirewallRule.State backupState = loadBalancer.getState(); + + if (vmGroup.getState().equals(AutoScaleVmGroup.State_New)) { + loadBalancer.setState(FirewallRule.State.Add); + _lbDao.persist(loadBalancer); + } + else if (loadBalancer.getState() == FirewallRule.State.Active && + vmGroup.getState().equals(AutoScaleVmGroup.State_Revoke)) { + loadBalancer.setState(FirewallRule.State.Add); + _lbDao.persist(loadBalancer); + } + + try { + success = applyAutoScaleConfig(loadBalancer, vmGroup, currentState); + } catch (ResourceUnavailableException e) { + s_logger.warn("Unable to configure AutoScaleVmGroup to the lb rule: " + loadBalancer.getId() + " because resource is unavaliable:", e); + if (isRollBackAllowedForProvider(loadBalancer)) { + loadBalancer.setState(backupState); + _lbDao.persist(loadBalancer); + s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating AutoscaleVmGroup"); + } + throw e; + } finally { + if (!success) { + s_logger.warn("Failed to configure LB Auto Scale Vm Group with Id:" + vmGroupid); + } + } + + if (success) { + if (vmGroup.getState().equals(AutoScaleVmGroup.State_New)) { + Transaction.currentTxn().start(); + loadBalancer.setState(FirewallRule.State.Active); + s_logger.debug("LB rule " + loadBalancer.getId() + " state is set to Active"); + _lbDao.persist(loadBalancer); + vmGroup.setState(AutoScaleVmGroup.State_Enabled); + _autoScaleVmGroupDao.persist(vmGroup); + s_logger.debug("LB Auto Scale Vm Group with Id: " + vmGroupid + " is set to Enabled state."); + Transaction.currentTxn().commit(); + } + s_logger.info("Successfully configured LB Autoscale Vm Group with Id: " + vmGroupid); + } + return success; + } private boolean genericValidator(CreateLBStickinessPolicyCmd cmd) throws InvalidParameterValueException { LoadBalancerVO loadBalancer = _lbDao.findById(cmd.getLbRuleId()); @@ -325,7 +513,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (isRollBackAllowedForProvider(loadBalancer)) { loadBalancer.setState(backupState); _lbDao.persist(loadBalancer); - s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating sticky policy" ); + s_logger.debug("LB Rollback rule id: " + loadBalancer.getId() + " lb state rolback while creating sticky policy"); } deleteLBStickinessPolicy(cmd.getEntityId(), false); success = false; @@ -381,7 +569,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); success = false; } - }else{ + } else { _lb2stickinesspoliciesDao.remove(stickinessPolicy.getLoadBalancerId()); } @@ -390,8 +578,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa private boolean isRollBackAllowedForProvider(LoadBalancerVO loadBalancer) { Network network = _networkDao.findById(loadBalancer.getNetworkId()); - Provider provider = Network.Provider.Netscaler; - return _ntwkSrvcDao.canProviderSupportServiceInNetwork(network.getId(), Service.Lb, provider); + List provider = _networkMgr.getProvidersForServiceInNetwork(network, Service.Lb); + if (provider == null || provider.size() == 0) { + return false; + } + if (provider.get(0) == Provider.Netscaler || provider.get(0) == Provider.F5BigIp) { + return true; + } + return false; } @Override @DB @@ -460,7 +654,12 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa map = _lb2VmMapDao.persist(map); } txn.commit(); - + if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) { + // For autoscaled loadbalancer, the rules need not be applied, + // meaning the call need not reach the resource layer. + // We can consider the job done. + return true; + } boolean success = false; FirewallRule.State backupState = loadBalancer.getState(); try { @@ -487,7 +686,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); } - if(!success){ + if (!success) { CloudRuntimeException ex = new CloudRuntimeException("Failed to add specified loadbalancerruleid for vms " + instanceIds); ex.addProxyObject(loadBalancer, loadBalancerId, "loadBalancerId"); // TBD: Also pack in the instanceIds in the exception using the right VO object or table name. @@ -526,6 +725,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa s_logger.debug("Set load balancer rule for revoke: rule id " + loadBalancerId + ", vmId " + instanceId); } + if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) { + // For autoscaled loadbalancer, the rules need not be applied, + // meaning the call need not reach the resource layer. + // We can consider the job done and only need to remove the rules in DB + _lb2VmMapDao.remove(loadBalancer.getId(), instanceIds, null); + return true; + } + if (!applyLoadBalancerConfig(loadBalancerId)) { s_logger.warn("Failed to remove load balancer rule id " + loadBalancerId + " for vms " + instanceIds); CloudRuntimeException ex = new CloudRuntimeException("Failed to remove specified load balancer rule id for vms " + instanceIds); @@ -549,7 +756,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } s_logger.warn("Unable to apply the load balancer config because resource is unavaliable.", e); } - if(!success){ + if (!success) { CloudRuntimeException ex = new CloudRuntimeException("Failed to remove specified load balancer rule id for vms " + instanceIds); ex.addProxyObject(loadBalancer, loadBalancerId, "loadBalancerId"); throw ex; @@ -660,10 +867,19 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (apply) { try { + if (_autoScaleVmGroupDao.isAutoScaleLoadBalancer(loadBalancerId)) { + // Get the associated VmGroup + AutoScaleVmGroupVO vmGroup = _autoScaleVmGroupDao.listByAll(loadBalancerId, null).get(0); + if (!applyAutoScaleConfig(lb, vmGroup,vmGroup.getState())) { + s_logger.warn("Unable to apply the autoscale config"); + return false; + } + } else { if (!applyLoadBalancerConfig(loadBalancerId)) { s_logger.warn("Unable to apply the load balancer config"); return false; } + } } catch (ResourceUnavailableException e) { if (rollBack && isRollBackAllowedForProvider(lb)) { if (backupMaps != null) { @@ -797,6 +1013,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa return result; } + @Override @DB public LoadBalancer createLoadBalancer(CreateLoadBalancerRuleCmd lb, boolean openFirewall) throws NetworkRuleConflictException { UserContext caller = UserContext.current(); @@ -844,6 +1061,12 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa LoadBalancerVO newRule = new LoadBalancerVO(lb.getXid(), lb.getName(), lb.getDescription(), lb.getSourceIpAddressId(), lb.getSourcePortEnd(), lb.getDefaultPortStart(), lb.getAlgorithm(), network.getId(), ipAddr.getAllocatedToAccountId(), ipAddr.getAllocatedInDomainId()); + // verify rule is supported by Lb provider of the network + LoadBalancingRule loadBalancing = new LoadBalancingRule(newRule, new ArrayList(), new ArrayList()); + if (!_networkMgr.validateRule(loadBalancing)) { + throw new InvalidParameterValueException("LB service provider cannot support this rule"); + } + newRule = _lbDao.persist(newRule); if (openFirewall) { @@ -889,8 +1112,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa List lbs; if (isRollBackAllowedForProvider(lb)) { // this is for Netscalar type of devices. if their is failure the db entries will be rollbacked. - lbs = new ArrayList(1); - lbs.add(_lbDao.findById(lbRuleId)); + lbs = Arrays.asList(lb); } else { // get all rules in transition state lbs = _lbDao.listInTransitionStateByNetworkId(lb.getNetworkId()); @@ -1137,7 +1359,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (lbBackup.getDescription() != null) { lb.setDescription(lbBackup.getDescription()); } - if (lbBackup.getAlgorithm() != null){ + if (lbBackup.getAlgorithm() != null) { lb.setAlgorithm(lbBackup.getAlgorithm()); } lb.setState(lbBackup.getState()); @@ -1209,12 +1431,14 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa return loadBalancerInstances; } + @Override public List getStickinessMethods(long networkid) { - String capability = getLBStickinessCapability(networkid); - if (capability == null) + String capability = getLBCapability(networkid, Capability.SupportedStickinessMethods.getName()); + if (capability == null) { return null; + } Gson gson = new Gson(); java.lang.reflect.Type listType = new TypeToken>() { }.getType(); @@ -1239,7 +1463,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } @Override - public List searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) { + public Pair, Integer> searchForLoadBalancers(ListLoadBalancerRulesCmd cmd) { Long ipId = cmd.getPublicIpId(); Long zoneId = cmd.getZoneId(); Long id = cmd.getId(); @@ -1279,7 +1503,7 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { + for (int count = 0; count < tags.size(); count++) { tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); tagSearch.cp(); @@ -1330,7 +1554,8 @@ public class LoadBalancingRulesManagerImpl implements LoadBalancingRulesMa } } - return _lbDao.search(sc, searchFilter); + Pair, Integer> result = _lbDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java index c57e4725b76..29808717299 100644 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManager.java @@ -62,7 +62,10 @@ public interface VirtualNetworkApplianceManager extends Manager, VirtualNetworkA */ boolean savePasswordToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, List routers) throws ResourceUnavailableException; - + + boolean saveUserDataToRouter(Network network, NicProfile nic, VirtualMachineProfile profile, + List routers) throws ResourceUnavailableException; + List deployVirtualRouterInGuestNetwork(Network guestNetwork, DeployDestination dest, Account owner, Map params, boolean isRedundant) throws InsufficientCapacityException, ResourceUnavailableException, ConcurrentOperationException; diff --git a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java index 892d457745b..875303f0443 100755 --- a/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VirtualNetworkApplianceManagerImpl.java @@ -27,9 +27,14 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Queue; import java.util.Set; import java.util.TimeZone; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -37,6 +42,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.router.UpgradeRouterCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -82,7 +88,6 @@ import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; -import com.cloud.api.commands.UpgradeRouterCmd; import com.cloud.cluster.ManagementServerHostVO; import com.cloud.cluster.ManagementServerNode; import com.cloud.cluster.dao.ManagementServerHostDao; @@ -338,8 +343,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian int _routerStatsInterval = 300; int _routerCheckInterval = 30; + int _rvrStatusUpdatePoolSize = 10; protected ServiceOfferingVO _offering; private String _dnsBasicZoneUpdates = "all"; + private Set _guestOSNeedGatewayOnNonDefaultNetwork = new HashSet(); private boolean _disable_rp_filter = false; int _routerExtraPublicNics = 2; @@ -351,9 +358,12 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian ScheduledExecutorService _executor; ScheduledExecutorService _checkExecutor; ScheduledExecutorService _networkStatsUpdateExecutor; + ExecutorService _rvrStatusUpdateExecutor; Account _systemAcct; + BlockingQueue _vrUpdateQueue = null; + @Override public boolean sendSshKeysToHost(Long hostId, String pubKey, String prvKey) { ModifySshKeysCommand cmd = new ModifySshKeysCommand(pubKey, prvKey); @@ -366,10 +376,10 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } } + + @Override - public VirtualRouter destroyRouter(final long routerId) throws ResourceUnavailableException, ConcurrentOperationException { - UserContext context = UserContext.current(); - User user = _accountMgr.getActiveUser(context.getCallerUserId()); + public VirtualRouter destroyRouter(final long routerId, Account caller, Long callerUserId) throws ResourceUnavailableException, ConcurrentOperationException { if (s_logger.isDebugEnabled()) { s_logger.debug("Attempting to destroy router " + routerId); @@ -380,9 +390,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian return null; } - _accountMgr.checkAccess(context.getCaller(), null, true, router); + _accountMgr.checkAccess(caller, null, true, router); - boolean result = _itMgr.expunge(router, user, _accountMgr.getAccount(router.getAccountId())); + boolean result = _itMgr.expunge(router, _accountMgr.getActiveUser(callerUserId), _accountMgr.getAccount(router.getAccountId())); if (result) { return router; @@ -463,6 +473,24 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian }); } + @Override + public boolean saveUserDataToRouter(Network network, final NicProfile nic, VirtualMachineProfile profile, List routers) throws ResourceUnavailableException { + _userVmDao.loadDetails((UserVmVO) profile.getVirtualMachine()); + + final VirtualMachineProfile updatedProfile = profile; + + return applyRules(network, routers, "save userdata entry", false, null, false, new RuleApplier() { + @Override + public boolean execute(Network network, VirtualRouter router) throws ResourceUnavailableException { + // for basic zone, send vm data/password information only to the router in the same pod + Commands cmds = new Commands(OnError.Stop); + NicVO nicVo = _nicDao.findById(nic.getId()); + createVmDataCommand(router, updatedProfile.getVirtualMachine(), nicVo, null, cmds); + return sendCommandsToRouter(router, cmds); + } + }); + } + @Override @ActionEvent(eventType = EventTypes.EVENT_ROUTER_STOP, eventDescription = "stopping router Vm", async = true) public VirtualRouter stopRouter(long routerId, boolean forced) throws ResourceUnavailableException, ConcurrentOperationException { UserContext context = UserContext.current(); @@ -482,6 +510,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; } @@ -565,6 +601,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); @@ -574,6 +618,17 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian value = configs.get("router.check.interval"); _routerCheckInterval = NumbersUtil.parseInt(value, 30); + value = configs.get("router.check.poolsize"); + _rvrStatusUpdatePoolSize = NumbersUtil.parseInt(value, 10); + + /* + * We assume that one thread can handle 20 requests in 1 minute in normal situation, so here we give the queue size up to 50 minutes. + * It's mostly for buffer, since each time CheckRouterTask running, it would add all the redundant networks in the queue immediately + */ + _vrUpdateQueue = new LinkedBlockingQueue(_rvrStatusUpdatePoolSize * 1000); + + _rvrStatusUpdateExecutor = Executors.newFixedThreadPool(_rvrStatusUpdatePoolSize, new NamedThreadFactory("RedundantRouterStatusMonitor")); + _instance = configs.get("instance.name"); if (_instance == null) { _instance = "DEFAULT"; @@ -671,6 +726,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (_routerCheckInterval > 0) { _checkExecutor.scheduleAtFixedRate(new CheckRouterTask(), _routerCheckInterval, _routerCheckInterval, TimeUnit.SECONDS); + for (int i = 0; i < _rvrStatusUpdatePoolSize; i++) { + _rvrStatusUpdateExecutor.execute(new RvRStatusUpdateTask()); + } } else { s_logger.debug("router.check.interval - " + _routerCheckInterval+ " so not scheduling the redundant router checking thread"); } @@ -1006,14 +1064,11 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian if (host == null || host.getStatus() != Status.Up) { router.setRedundantState(RedundantState.UNKNOWN); updated = true; - } else if (host.getManagementServerId() != ManagementServerNode.getManagementServerId()) { - /* Only cover hosts managed by this management server */ - continue; } else if (privateIP != null) { final CheckRouterCommand command = new CheckRouterCommand(); command.setAccessDetail(NetworkElementCommand.ROUTER_IP, getRouterControlIp(router.getId())); command.setAccessDetail(NetworkElementCommand.ROUTER_NAME, router.getInstanceName()); - command.setWait(60); + command.setWait(30); final Answer origAnswer = _agentMgr.easySend(router.getHostId(), command); CheckRouterAnswer answer = null; if (origAnswer instanceof CheckRouterAnswer) { @@ -1095,9 +1150,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian return priority; } - protected class CheckRouterTask implements Runnable { + protected class RvRStatusUpdateTask implements Runnable { - public CheckRouterTask() { + public RvRStatusUpdateTask() { } /* @@ -1162,9 +1217,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian String title = "More than one redundant virtual router is in MASTER state! Router " + router.getHostName() + " and router " + dupRouter.getHostName(); String context = "Virtual router (name: " + router.getHostName() + ", id: " + router.getId() + " and router (name: " + dupRouter.getHostName() + ", id: " + router.getId() + ") are both in MASTER state! If the problem persist, restart both of routers. "; - _alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER, router.getDataCenterIdToDeployIn(), router.getPodIdToDeployIn(), title, context); _alertMgr.sendAlert(AlertManager.ALERT_TYPE_DOMAIN_ROUTER, dupRouter.getDataCenterIdToDeployIn(), dupRouter.getPodIdToDeployIn(), title, context); + s_logger.warn(context); } else { networkRouterMaps.put(routerGuestNtwkId, router); } @@ -1175,17 +1230,59 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian @Override public void run() { + while (true) { try { - final List routers = _routerDao.listIsolatedByHostId(null); - s_logger.debug("Found " + routers.size() + " routers. "); + Long networkId = _vrUpdateQueue.take(); + List routers = _routerDao.listByNetworkAndRole(networkId, Role.VIRTUAL_ROUTER); + if (routers.size() != 2) { + continue; + } + /* + * We update the router pair which the lower id router owned by this mgmt server, in order + * to prevent duplicate update of router status from cluster mgmt servers + */ + DomainRouterVO router = routers.get(0); + if (routers.get(1).getId() < router.getId()) { + router = routers.get(1); + } + HostVO host = _hostDao.findById(router.getHostId()); + if (host == null || host.getManagementServerId() == null || + host.getManagementServerId() != ManagementServerNode.getManagementServerId()) { + continue; + } updateRoutersRedundantState(routers); - updateSite2SiteVpnConnectionState(routers); - - /* FIXME assumed the a pair of redundant routers managed by same mgmt server, - * then the update above can get the latest status */ checkDuplicateMaster(routers); checkSanity(routers); + } catch (Exception ex) { + s_logger.error("Fail to complete the RvRStatusUpdateTask! ", ex); + } + } + } + + } + + protected class CheckRouterTask implements Runnable { + + public CheckRouterTask() { + } + + @Override + public void run() { + try { + final List routers = _routerDao.listIsolatedByHostId(null); + s_logger.debug("Found " + routers.size() + " routers to update status. "); + + updateSite2SiteVpnConnectionState(routers); + + final List networks = _networkDao.listRedundantNetworks(); + s_logger.debug("Found " + networks.size() + " networks to update RvR status. "); + for (NetworkVO network : networks) { + if (!_vrUpdateQueue.offer(network.getId(), 500, TimeUnit.MILLISECONDS)) { + s_logger.warn("Cannot insert into virtual router update queue! Adjustment of router.check.interval and router.check.poolsize maybe needed."); + break; + } + } } catch (Exception ex) { s_logger.error("Fail to complete the CheckRouterTask! ", ex); } @@ -1265,7 +1362,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian boolean isRedundant, Map params) throws ConcurrentOperationException, InsufficientCapacityException, ResourceUnavailableException { - List routers = new ArrayList(); Network lock = _networkDao.acquireInLockTable(guestNetwork.getId(), _networkMgr.getNetworkLockTimeout()); if (lock == null) { @@ -1288,7 +1384,44 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian _networkMgr.areServicesSupportedInNetwork(guestNetwork.getId(), Service.SecurityGroup)) && guestNetwork.getTrafficType() == TrafficType.Guest; - Pair> planAndRouters = getDeploymentPlanAndRouters(isPodBased, dest, guestNetwork.getId()); + // dest has pod=null, for Basic Zone findOrDeployVRs for all Pods + List destinations = new ArrayList(); + + if (dest.getDataCenter().getNetworkType() == NetworkType.Basic) { + // Find all pods in the data center with running or starting user vms + long dcId = dest.getDataCenter().getId(); + List pods = _podDao.listByDataCenterIdVMTypeAndStates(dcId, VirtualMachine.Type.User, VirtualMachine.State.Starting, VirtualMachine.State.Running); + + // Loop through all the pods skip those with running or starting VRs + for (HostPodVO pod: pods) { + // Get list of VRs in starting or running state + long podId = pod.getId(); + List virtualRouters = _routerDao.listByPodIdAndStates(podId, VirtualMachine.State.Starting, VirtualMachine.State.Running); + + assert (virtualRouters.size() <= 1) : "Pod can have utmost one VR in Basic Zone, please check!"; + + // Add virtualRouters to the routers, this avoids the situation when + // all routers are skipped and VirtualRouterElement throws exception + routers.addAll(virtualRouters); + + // If List size is one, we already have a starting or running VR, skip deployment + if (virtualRouters.size() == 1) { + s_logger.debug("Skipping VR deployment: Found a running or starting VR in Pod " + + pod.getName() + " id=" + podId); + continue; + } + // Add new DeployDestination for this pod + destinations.add(new DeployDestination(dest.getDataCenter(), pod, null, null)); + } + } + else { + // Else, just add the supplied dest + destinations.add(dest); + } + + // Except for Basic Zone, the for loop will iterate only once + for (DeployDestination destination: destinations) { + Pair> planAndRouters = getDeploymentPlanAndRouters(isPodBased, destination, guestNetwork.getId()); routers = planAndRouters.second(); // 2) Figure out required routers count @@ -1297,7 +1430,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian routerCount = 2; } - /* If old network is redundant but new is single router, then routers.size() = 2 but routerCount = 1 */ + // If old network is redundant but new is single router, then routers.size() = 2 but routerCount = 1 if (routers.size() >= routerCount) { return routers; } @@ -1315,14 +1448,14 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } VirtualRouterProvider vrProvider = _vrProviderDao.findByNspIdAndType(provider.getId(), type); if (vrProvider == null) { - throw new CloudRuntimeException("Cannot find virtual router provider " + type.toString()+ " as service provider " + provider.getId()); + throw new CloudRuntimeException("Cannot find virtual router provider " + type.toString() + " as service provider " + provider.getId()); } if (_networkMgr.isNetworkSystem(guestNetwork) || guestNetwork.getGuestType() == Network.GuestType.Shared) { owner = _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM); } - //Check if public network has to be set on VR + // Check if public network has to be set on VR boolean publicNetwork = false; if (_networkMgr.isProviderSupportServiceInNetwork(guestNetwork.getId(), Service.SourceNat, Provider.VirtualRouter)) { publicNetwork = true; @@ -1337,24 +1470,41 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian offeringId = _offering.getId(); } + // 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); + } + } } - //3) deploy virtual router(s) - int count = routerCount - routers.size(); - DeploymentPlan plan = planAndRouters.first(); - for (int i = 0; i < count; i++) { 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 - DomainRouterVO router = deployRouter(owner, dest, plan, params, isRedundant, vrProvider, offeringId, + DomainRouterVO router = deployRouter(owner, destination, plan, params, isRedundant, vrProvider, offeringId, null, networks, false, null); _routerDao.addRouterToGuestNetwork(router, guestNetwork); routers.add(router); } + } } finally { if (lock != null) { _networkDao.releaseFromLockTable(lock.getId()); @@ -1430,7 +1580,7 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian s_logger.debug("Failed to start the VR " + router + " with hypervisor type " + hType + ", " + "destroying it and recreating one more time"); // destroy the router - destroyRouter(router.getId()); + destroyRouter(router.getId(), _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM); continue; } else { throw ex; @@ -1438,6 +1588,9 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian } finally { startRetry++; } + } else { + //return stopped router + return router; } } @@ -1448,10 +1601,6 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian protected List getHypervisors(DeployDestination dest, DeploymentPlan plan, List supportedHypervisors) throws InsufficientServerCapacityException { List hypervisors = new ArrayList(); - HypervisorType defaults = _resourceMgr.getDefaultHypervisor(dest.getDataCenter().getId()); - if (defaults != HypervisorType.None) { - hypervisors.add(defaults); - } if (dest.getCluster() != null) { if (dest.getCluster().getHypervisorType() == HypervisorType.Ovm) { @@ -1460,9 +1609,15 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian hypervisors.add(dest.getCluster().getHypervisorType()); } } else { + HypervisorType defaults = _resourceMgr.getDefaultHypervisor(dest.getDataCenter().getId()); + if (defaults != HypervisorType.None) { + hypervisors.add(defaults); + } else { + //if there is no default hypervisor, get it from the cluster hypervisors = _resourceMgr.getSupportedHypervisorTypes(dest.getDataCenter().getId(), true, plan.getPodId()); } + } //keep only elements defined in supported hypervisors StringBuilder hTypesStr = new StringBuilder(); @@ -2352,6 +2507,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(); @@ -2591,6 +2751,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) { @@ -2730,16 +2896,19 @@ public class VirtualNetworkApplianceManagerImpl implements VirtualNetworkApplian LoadBalancerTO[] lbs = new LoadBalancerTO[rules.size()]; int i = 0; + // We don't support VR to be inline currently + boolean inline = false; for (LoadBalancingRule rule : rules) { boolean revoked = (rule.getState().equals(FirewallRule.State.Revoke)); String protocol = rule.getProtocol(); String algorithm = rule.getAlgorithm(); + String uuid = rule.getUuid(); String srcIp = _networkMgr.getIp(rule.getSourceIpAddressId()).getAddress().addr(); int srcPort = rule.getSourcePortStart(); List destinations = rule.getDestinations(); List stickinessPolicies = rule.getStickinessPolicies(); - LoadBalancerTO lb = new LoadBalancerTO(srcIp, srcPort, protocol, algorithm, revoked, false, destinations, stickinessPolicies); + LoadBalancerTO lb = new LoadBalancerTO(uuid, srcIp, srcPort, protocol, algorithm, revoked, false, false, destinations, stickinessPolicies); lbs[i++] = lb; } String routerPublicIp = null; @@ -2856,14 +3025,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())); @@ -3246,6 +3423,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/router/VpcVirtualNetworkApplianceManagerImpl.java b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java index 00e767ef586..2f1f76d0889 100644 --- a/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java +++ b/server/src/com/cloud/network/router/VpcVirtualNetworkApplianceManagerImpl.java @@ -303,10 +303,8 @@ public class VpcVirtualNetworkApplianceManagerImpl extends VirtualNetworkApplian result = result && _itMgr.removeVmFromNetwork(router, network, null); if (result) { - if (result) { _routerDao.removeRouterFromGuestNetwork(router.getId(), network.getId()); } - } return result; } diff --git a/server/src/com/cloud/network/rules/FirewallRuleVO.java b/server/src/com/cloud/network/rules/FirewallRuleVO.java index b64e8bf7b08..99140c3d6f6 100644 --- a/server/src/com/cloud/network/rules/FirewallRuleVO.java +++ b/server/src/com/cloud/network/rules/FirewallRuleVO.java @@ -35,17 +35,18 @@ import javax.persistence.InheritanceType; import javax.persistence.Table; import javax.persistence.Transient; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.dao.FirewallRulesCidrsDaoImpl; import com.cloud.utils.db.GenericDao; import com.cloud.utils.net.NetUtils; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="firewall_rules") @Inheritance(strategy=InheritanceType.JOINED) @DiscriminatorColumn(name="purpose", discriminatorType=DiscriminatorType.STRING, length=32) -public class FirewallRuleVO implements Identity, FirewallRule { - @Inject protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = null; +public class FirewallRuleVO implements FirewallRule { + protected final FirewallRulesCidrsDaoImpl _firewallRulesCidrsDao = ComponentLocator.inject(FirewallRulesCidrsDaoImpl.class); @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/rules/RulesManagerImpl.java b/server/src/com/cloud/network/rules/RulesManagerImpl.java index c90466fb46a..9f67e0530ff 100755 --- a/server/src/com/cloud/network/rules/RulesManagerImpl.java +++ b/server/src/com/cloud/network/rules/RulesManagerImpl.java @@ -26,10 +26,10 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.firewall.ListPortForwardingRulesCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ListPortForwardingRulesCmd; import com.cloud.configuration.ConfigurationManager; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; @@ -63,6 +63,7 @@ import com.cloud.user.AccountManager; import com.cloud.user.DomainManager; import com.cloud.user.UserContext; import com.cloud.uservm.UserVm; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; @@ -80,6 +81,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.*; @Component @Local(value = { RulesManager.class, RulesService.class }) @@ -688,7 +694,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } @Override - public List listPortForwardingRules(ListPortForwardingRulesCmd cmd) { + public Pair, Integer> listPortForwardingRules(ListPortForwardingRulesCmd cmd) { Long ipId = cmd.getIpAddressId(); Long id = cmd.getId(); Map tags = cmd.getTags(); @@ -754,7 +760,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { sc.setParameters("purpose", Purpose.PortForwarding); - return _portForwardingDao.search(sc, filter); + Pair, Integer> result = _portForwardingDao.searchAndCount(sc, filter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -904,7 +911,7 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { } @Override - public List searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) { + public Pair, Integer> searchStaticNatRules(Long ipId, Long id, Long vmId, Long start, Long size, String accountName, Long domainId, Long projectId, boolean isRecursive, boolean listAll) { Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -952,7 +959,8 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { sc.setJoinParameters("ipSearch", "associatedWithVmId", vmId); } - return _firewallDao.search(sc, filter); + Pair, Integer> result = _firewallDao.searchAndCount(sc, filter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -1183,12 +1191,13 @@ public class RulesManagerImpl implements RulesManager, RulesService, Manager { Network guestNetwork = _networkMgr.getNetwork(ipAddress.getAssociatedWithNetworkId()); NetworkOffering offering = _configMgr.getNetworkOffering(guestNetwork.getNetworkOfferingId()); if (offering.getElasticIp()) { + if (offering.getAssociatePublicIP()) { getSystemIpAndEnableStaticNatForVm(_vmDao.findById(vmId), true); return true; - } else { - return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); } } + return disableStaticNat(ipId, caller, ctx.getCallerUserId(), false); + } @Override public boolean disableStaticNat(long ipId, Account caller, long callerUserId, boolean releaseIpIfElastic) throws ResourceUnavailableException { @@ -1373,7 +1382,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); @@ -1388,7 +1401,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/network/rules/StaticNatRuleImpl.java b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java index 4ae7ab2adab..6103689a31b 100644 --- a/server/src/com/cloud/network/rules/StaticNatRuleImpl.java +++ b/server/src/com/cloud/network/rules/StaticNatRuleImpl.java @@ -5,7 +5,7 @@ // 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, @@ -19,9 +19,10 @@ package com.cloud.network.rules; import java.util.List; -public class StaticNatRuleImpl implements StaticNatRule{ +public class StaticNatRuleImpl implements StaticNatRule { long id; String xid; + String uuid; String protocol; int portStart; int portEnd; @@ -32,9 +33,10 @@ public class StaticNatRuleImpl implements StaticNatRule{ long sourceIpAddressId; String destIpAddress; - public StaticNatRuleImpl(FirewallRuleVO rule, String dstIp) { + public StaticNatRuleImpl(FirewallRuleVO rule, String dstIp) { this.id = rule.getId(); this.xid = rule.getXid(); + this.uuid = rule.getUuid(); this.protocol = rule.getProtocol(); this.portStart = rule.getSourcePortStart(); this.portEnd = rule.getSourcePortEnd(); @@ -55,7 +57,7 @@ public class StaticNatRuleImpl implements StaticNatRule{ public Integer getSourcePortEnd() { return portEnd; } - + @Override public Purpose getPurpose() { return Purpose.StaticNat; @@ -65,17 +67,17 @@ public class StaticNatRuleImpl implements StaticNatRule{ public State getState() { return state; } - + @Override public long getAccountId() { return accountId; } - + @Override public long getDomainId() { return domainId; } - + @Override public long getNetworkId() { return networkId; @@ -105,12 +107,18 @@ public class StaticNatRuleImpl implements StaticNatRule{ public String getXid() { return xid; } - + + + @Override + public String getUuid() { + return uuid; + } + @Override public Integer getIcmpCode() { return null; } - + @Override public Integer getIcmpType() { return null; @@ -130,7 +138,7 @@ public class StaticNatRuleImpl implements StaticNatRule{ public FirewallRuleType getType() { return FirewallRuleType.User; } - + @Override public TrafficType getTrafficType() { return null; diff --git a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java index f0a268b081f..0b0a34773c5 100755 --- a/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java +++ b/server/src/com/cloud/network/security/SecurityGroupManagerImpl.java @@ -37,6 +37,7 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.securitygroup.*; import org.apache.commons.codec.digest.DigestUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -46,13 +47,10 @@ import com.cloud.agent.api.NetworkRulesSystemVmCommand; import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AuthorizeSecurityGroupEgressCmd; -import com.cloud.api.commands.AuthorizeSecurityGroupIngressCmd; -import com.cloud.api.commands.CreateSecurityGroupCmd; -import com.cloud.api.commands.DeleteSecurityGroupCmd; -import com.cloud.api.commands.ListSecurityGroupsCmd; -import com.cloud.api.commands.RevokeSecurityGroupEgressCmd; -import com.cloud.api.commands.RevokeSecurityGroupIngressCmd; +import com.cloud.api.query.dao.SecurityGroupJoinDao; +import com.cloud.api.query.vo.SecurityGroupJoinVO; + +import org.apache.cloudstack.api.command.user.securitygroup.RevokeSecurityGroupEgressCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.dao.DomainDao; @@ -79,8 +77,6 @@ import com.cloud.network.security.dao.VmRulesetLogDao; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.ProjectManager; import com.cloud.server.ManagementServer; -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; @@ -97,10 +93,10 @@ import com.cloud.utils.concurrency.NamedThreadFactory; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.fsm.StateListener; import com.cloud.utils.net.NetUtils; @@ -126,6 +122,8 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG @Inject SecurityGroupDao _securityGroupDao; @Inject + SecurityGroupJoinDao _securityGroupJoinDao; + @Inject SecurityGroupRuleDao _securityGroupRuleDao; @Inject SecurityGroupVMMapDao _securityGroupVMMapDao; @@ -1093,101 +1091,24 @@ public class SecurityGroupManagerImpl implements SecurityGroupManager, SecurityG return true; } - @Override - public List searchForSecurityGroupRules(ListSecurityGroupsCmd cmd) throws PermissionDeniedException, InvalidParameterValueException { - Account caller = UserContext.current().getCaller(); - Long instanceId = cmd.getVirtualMachineId(); - String securityGroup = cmd.getSecurityGroupName(); - Long id = cmd.getId(); - Object keyword = cmd.getKeyword(); - List permittedAccounts = new ArrayList(); - Map tags = cmd.getTags(); - if (instanceId != null) { - UserVmVO userVM = _userVMDao.findById(instanceId); - if (userVM == null) { - throw new InvalidParameterValueException("Unable to list network groups for virtual machine instance " + instanceId + "; instance not found."); + + private Pair, Integer> listSecurityGroupRulesByVM(long vmId, long pageInd, long pageSize) { + Filter sf = new Filter(SecurityGroupVMMapVO.class, null, true, pageInd, pageSize); + Pair, Integer> sgVmMappingPair = _securityGroupVMMapDao.listByInstanceId(vmId, sf); + Integer count = sgVmMappingPair.second(); + if (count.intValue() == 0) { + // handle empty result cases + return new Pair, Integer>(new ArrayList(), count); } - _accountMgr.checkAccess(caller, null, true, userVM); - return listSecurityGroupRulesByVM(instanceId.longValue()); + List sgVmMappings = sgVmMappingPair.first(); + Long[] sgIds = new Long[sgVmMappings.size()]; + int i = 0; + for (SecurityGroupVMMapVO sgVm : sgVmMappings) { + sgIds[i++] = sgVm.getSecurityGroupId(); } - - List securityRulesList = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(SecurityGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _securityGroupDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.EQ); - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (id != null) { - sc.setParameters("id", id); - } - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.SecurityGroup.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - if (securityGroup != null) { - sc.setParameters("name", securityGroup); - } - - if (keyword != null) { - SearchCriteria ssc = _securityGroupRulesDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - List securityGroups = _securityGroupDao.search(sc, searchFilter); - for (SecurityGroupVO group : securityGroups) { - securityRulesList.addAll(_securityGroupRulesDao.listSecurityRulesByGroupId(group.getId())); - } - - return securityRulesList; - } - - private List listSecurityGroupRulesByVM(long vmId) { - List results = new ArrayList(); - List networkGroupMappings = _securityGroupVMMapDao.listByInstanceId(vmId); - if (networkGroupMappings != null) { - for (SecurityGroupVMMapVO networkGroupMapping : networkGroupMappings) { - SecurityGroupVO group = _securityGroupDao.findById(networkGroupMapping.getSecurityGroupId()); - List rules = _securityGroupRulesDao.listSecurityGroupRules(group.getAccountId(), networkGroupMapping.getGroupName()); - if (rules != null) { - results.addAll(rules); - } - } - } - return results; + List sgs = _securityGroupJoinDao.searchByIds(sgIds); + return new Pair, Integer>(sgs, count); } @Override diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java index cc842df7d64..cbeae4f1483 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDao.java @@ -19,12 +19,15 @@ package com.cloud.network.security.dao; import java.util.List; import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDao; import com.cloud.vm.VirtualMachine.State; public interface SecurityGroupVMMapDao extends GenericDao { List listByIpAndInstanceId(String ipAddress, long instanceId); List listByInstanceId(long instanceId); + Pair, Integer> listByInstanceId(long instanceId, Filter filter); List listByIp(String ipAddress); List listBySecurityGroup(long securityGroupId); List listBySecurityGroup(long securityGroupId, State ... vmStates); diff --git a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java index da07e8b1f82..4adeaa971c4 100644 --- a/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java +++ b/server/src/com/cloud/network/security/dao/SecurityGroupVMMapDaoImpl.java @@ -26,6 +26,8 @@ import com.cloud.dc.VlanVO; import com.cloud.dc.Vlan.VlanType; import com.cloud.network.IPAddressVO; import com.cloud.network.security.SecurityGroupVMMapVO; +import com.cloud.utils.Pair; +import com.cloud.utils.db.Filter; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.GenericSearchBuilder; import com.cloud.utils.db.JoinBuilder; @@ -117,6 +119,13 @@ public class SecurityGroupVMMapDaoImpl extends GenericDaoBase, Integer> listByInstanceId(long instanceId, Filter filter) { + SearchCriteria sc = ListByVmId.create(); + sc.setParameters("instanceId", instanceId); + return this.searchAndCount(sc, filter); + } + @Override public int deleteVM(long instanceId) { SearchCriteria sc = ListByVmId.create(); diff --git a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java index 0e3d3141fb5..cfeb15a40b5 100644 --- a/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java +++ b/server/src/com/cloud/network/vpc/NetworkACLManagerImpl.java @@ -24,11 +24,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.network.ListNetworkACLsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.ListNetworkACLsCmd; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; import com.cloud.exception.InvalidParameterValueException; @@ -53,6 +53,7 @@ import com.cloud.tags.dao.ResourceTagDao; import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.UserContext; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; @@ -139,8 +140,11 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ Vpc vpc = _vpcMgr.getVpc(network.getVpcId()); Account aclOwner = _accountMgr.getAccount(vpc.getAccountId()); - _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); + //check if the caller can access vpc + _accountMgr.checkAccess(caller, null, false, vpc); + //check if the acl can be created for this network + _accountMgr.checkAccess(aclOwner, AccessType.UseNetwork, false, network); if (!_networkMgr.areServicesSupportedInNetwork(networkId, Service.NetworkACL)) { throw new InvalidParameterValueException("Service " + Service.NetworkACL + " is not supported in network " + network); @@ -345,7 +349,7 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ @Override - public List listNetworkACLs(ListNetworkACLsCmd cmd) { + public Pair,Integer> listNetworkACLs(ListNetworkACLsCmd cmd) { Long networkId = cmd.getNetworkId(); Long id = cmd.getId(); String trafficType = cmd.getTrafficType(); @@ -410,7 +414,8 @@ public class NetworkACLManagerImpl implements Manager,NetworkACLManager{ sc.setParameters("purpose", Purpose.NetworkACL); - return _firewallDao.search(sc, filter); + Pair, Integer> result = _firewallDao.searchAndCount(sc, filter); + return new Pair, Integer>(result.first(), result.second()); } diff --git a/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java b/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java index 4ad1fb6f525..2595a6a0fa4 100644 --- a/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java +++ b/server/src/com/cloud/network/vpc/PrivateGatewayProfile.java @@ -17,7 +17,7 @@ package com.cloud.network.vpc; -public class PrivateGatewayProfile implements PrivateGateway{ +public class PrivateGatewayProfile implements PrivateGateway { VpcGateway vpcGateway; long physicalNetworkId; diff --git a/server/src/com/cloud/network/vpc/PrivateIpVO.java b/server/src/com/cloud/network/vpc/PrivateIpVO.java index f20150da660..e6616ae3899 100644 --- a/server/src/com/cloud/network/vpc/PrivateIpVO.java +++ b/server/src/com/cloud/network/vpc/PrivateIpVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.network.vpc; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -30,7 +32,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="private_ip_address") -public class PrivateIpVO{ +public class PrivateIpVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/StaticRouteVO.java b/server/src/com/cloud/network/vpc/StaticRouteVO.java index 8f6dd03bb79..eb4c61b7860 100644 --- a/server/src/com/cloud/network/vpc/StaticRouteVO.java +++ b/server/src/com/cloud/network/vpc/StaticRouteVO.java @@ -28,47 +28,48 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="static_routes") -public class StaticRouteVO implements Identity, StaticRoute{ +public class StaticRouteVO implements StaticRoute { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") long id; - + @Column(name="uuid") String uuid; - + @Column(name="vpc_gateway_id", updatable=false) long vpcGatewayId; - + @Column(name="cidr") private String cidr; - + @Enumerated(value=EnumType.STRING) @Column(name="state") State state; - + @Column(name="vpc_id") private Long vpcId; - + @Column(name = "account_id") long accountId; @Column(name = "domain_id") long domainId; - + @Column(name=GenericDao.CREATED_COLUMN) Date created; - + protected StaticRouteVO(){ this.uuid = UUID.randomUUID().toString(); } - + /** * @param vpcGatewayId * @param cidr @@ -86,7 +87,7 @@ public class StaticRouteVO implements Identity, StaticRoute{ this.domainId = domainId; this.uuid = UUID.randomUUID().toString(); } - + @Override public long getVpcGatewayId() { return vpcGatewayId; @@ -130,7 +131,7 @@ public class StaticRouteVO implements Identity, StaticRoute{ public void setState(State state) { this.state = state; } - + @Override public String toString() { StringBuilder buf = new StringBuilder("StaticRoute["); diff --git a/server/src/com/cloud/network/vpc/VpcGatewayVO.java b/server/src/com/cloud/network/vpc/VpcGatewayVO.java index 43a99104834..718e4df82df 100644 --- a/server/src/com/cloud/network/vpc/VpcGatewayVO.java +++ b/server/src/com/cloud/network/vpc/VpcGatewayVO.java @@ -29,11 +29,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_gateways") -public class VpcGatewayVO implements VpcGateway{ +public class VpcGatewayVO implements VpcGateway { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/VpcManager.java b/server/src/com/cloud/network/vpc/VpcManager.java index 14fdbe933af..8d49aa1615c 100644 --- a/server/src/com/cloud/network/vpc/VpcManager.java +++ b/server/src/com/cloud/network/vpc/VpcManager.java @@ -18,7 +18,7 @@ package com.cloud.network.vpc; import java.util.List; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -55,11 +55,13 @@ public interface VpcManager extends VpcService{ /** * @param vpc + * @param caller TODO + * @param callerUserId TODO * @return * @throws ConcurrentOperationException * @throws ResourceUnavailableException */ - boolean destroyVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException; + boolean destroyVpc(Vpc vpc, Account caller, Long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException; /** * @param vpcId diff --git a/server/src/com/cloud/network/vpc/VpcManagerImpl.java b/server/src/com/cloud/network/vpc/VpcManagerImpl.java index 876e5206352..1412d08d706 100644 --- a/server/src/com/cloud/network/vpc/VpcManagerImpl.java +++ b/server/src/com/cloud/network/vpc/VpcManagerImpl.java @@ -31,12 +31,12 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.Resource.ResourceType; @@ -97,6 +97,7 @@ import com.cloud.user.ResourceLimitService; import com.cloud.user.User; import com.cloud.user.UserContext; import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; @@ -616,7 +617,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ @ActionEvent(eventType = EventTypes.EVENT_VPC_DELETE, eventDescription = "deleting VPC") public boolean deleteVpc(long vpcId) throws ConcurrentOperationException, ResourceUnavailableException { UserContext.current().setEventDetails(" Id: " + vpcId); - Account caller = UserContext.current().getCaller(); + UserContext ctx = UserContext.current(); // Verify vpc id Vpc vpc = getVpc(vpcId); @@ -625,15 +626,14 @@ public class VpcManagerImpl implements VpcManager, Manager{ } //verify permissions - _accountMgr.checkAccess(caller, null, false, vpc); + _accountMgr.checkAccess(ctx.getCaller(), null, false, vpc); - return destroyVpc(vpc); + return destroyVpc(vpc, ctx.getCaller(), ctx.getCallerUserId()); } @Override @DB - public boolean destroyVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException { - UserContext ctx = UserContext.current(); + public boolean destroyVpc(Vpc vpc, Account caller, Long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException { s_logger.debug("Destroying vpc " + vpc); //don't allow to delete vpc if it's in use by existing networks @@ -664,7 +664,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ } //cleanup vpc resources - if (!cleanupVpcResources(vpc.getId(), ctx.getCaller(), ctx.getCallerUserId())) { + if (!cleanupVpcResources(vpc.getId(), caller, callerUserId)) { s_logger.warn("Failed to cleanup resources for vpc " + vpc); return false; } @@ -893,7 +893,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ //do cleanup if (!result && destroyOnFailure) { s_logger.debug("Destroying vpc " + vpc + " that failed to start"); - if (destroyVpc(vpc)) { + if (destroyVpc(vpc, caller, callerUser.getId())) { s_logger.warn("Successfully destroyed vpc " + vpc + " that failed to start"); } else { s_logger.warn("Failed to destroy vpc " + vpc + " that failed to start"); @@ -931,7 +931,8 @@ public class VpcManagerImpl implements VpcManager, Manager{ //shutdown provider s_logger.debug("Shutting down vpc " + vpc); - boolean success = getVpcElement().shutdownVpc(vpc); + ReservationContext context = new ReservationContextImpl(null, null, _accountMgr.getActiveUser(ctx.getCallerUserId()), caller); + boolean success = getVpcElement().shutdownVpc(vpc, context); //TODO - shutdown all vpc resources here (ACLs, gateways, etc) if (success) { @@ -1389,7 +1390,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ } @Override - public List listPrivateGateway(ListPrivateGatewaysCmd cmd) { + public Pair, Integer> listPrivateGateway(ListPrivateGatewaysCmd cmd) { String ipAddress = cmd.getIpAddress(); String vlan = cmd.getVlan(); Long vpcId = cmd.getVpcId(); @@ -1444,13 +1445,13 @@ public class VpcManagerImpl implements VpcManager, Manager{ sc.setJoinParameters("networkSearch", "vlan", BroadcastDomainType.Vlan.toUri(vlan)); } - List vos = _vpcGatewayDao.search(sc, searchFilter); - List privateGtws = new ArrayList(vos.size()); - for (VpcGateway vo : vos) { + Pair, Integer> vos = _vpcGatewayDao.searchAndCount(sc, searchFilter); + List privateGtws = new ArrayList(vos.first().size()); + for (VpcGateway vo : vos.first()) { privateGtws.add(getPrivateGatewayProfile(vo)); } - return privateGtws; + return new Pair, Integer>(privateGtws, vos.second()); } @Override @@ -1610,7 +1611,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ } @Override - public List listStaticRoutes(ListStaticRoutesCmd cmd) { + public Pair, Integer> listStaticRoutes(ListStaticRoutesCmd cmd) { Long id = cmd.getId(); Long gatewayId = cmd.getGatewayId(); Long vpcId = cmd.getVpcId(); @@ -1676,7 +1677,8 @@ public class VpcManagerImpl implements VpcManager, Manager{ } } - return _staticRouteDao.search(sc, searchFilter); + Pair, Integer> result = _staticRouteDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } protected void detectRoutesConflict(StaticRoute newRoute) throws NetworkRuleConflictException { @@ -1737,7 +1739,7 @@ public class VpcManagerImpl implements VpcManager, Manager{ s_logger.info("Found " + inactiveVpcs.size() + " removed VPCs to cleanup"); for (VpcVO vpc : inactiveVpcs) { s_logger.debug("Cleaning up " + vpc); - destroyVpc(vpc); + destroyVpc(vpc, _accountMgr.getAccount(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM); } } catch (Exception e) { s_logger.error("Exception ", e); diff --git a/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java b/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java index 3615703ca4a..9dbb32f37d9 100644 --- a/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java +++ b/server/src/com/cloud/network/vpc/VpcOfferingServiceMapVO.java @@ -28,11 +28,12 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_offering_service_map") -public class VpcOfferingServiceMapVO { +public class VpcOfferingServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/network/vpc/VpcOfferingVO.java b/server/src/com/cloud/network/vpc/VpcOfferingVO.java index 7458a66ffbe..dce7a81e4d0 100644 --- a/server/src/com/cloud/network/vpc/VpcOfferingVO.java +++ b/server/src/com/cloud/network/vpc/VpcOfferingVO.java @@ -29,11 +29,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc_offerings") -public class VpcOfferingVO implements VpcOffering{ +public class VpcOfferingVO implements VpcOffering { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) diff --git a/server/src/com/cloud/network/vpc/VpcVO.java b/server/src/com/cloud/network/vpc/VpcVO.java index 4691b0508a9..634df052850 100644 --- a/server/src/com/cloud/network/vpc/VpcVO.java +++ b/server/src/com/cloud/network/vpc/VpcVO.java @@ -26,12 +26,13 @@ import javax.persistence.Enumerated; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="vpc") -public class VpcVO implements Vpc, Identity { +public class VpcVO implements Vpc { @Id @Column(name="id") long id; diff --git a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java index 38ccd2eeb5a..76bf057f4c7 100755 --- a/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/RemoteAccessVpnManagerImpl.java @@ -24,11 +24,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.vpn.ListVpnUsersCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ListRemoteAccessVpnsCmd; -import com.cloud.api.commands.ListVpnUsersCmd; +import org.apache.cloudstack.api.command.user.vpn.ListRemoteAccessVpnsCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.domain.DomainVO; @@ -214,9 +214,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } @Override @DB - public void destroyRemoteAccessVpn(long ipId) throws ResourceUnavailableException { - Account caller = UserContext.current().getCaller(); - + public void destroyRemoteAccessVpn(long ipId, Account caller) throws ResourceUnavailableException { RemoteAccessVpnVO vpn = _remoteAccessVpnDao.findById(ipId); if (vpn == null) { s_logger.debug("vpn id=" + ipId + " does not exists "); @@ -339,9 +337,7 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } @DB @Override - public boolean removeVpnUser(long vpnOwnerId, String username) { - Account caller = UserContext.current().getCaller(); - + public boolean removeVpnUser(long vpnOwnerId, String username, Account caller) { VpnUserVO user = _vpnUsersDao.findByAccountAndUsername(vpnOwnerId, username); if (user == null) { throw new InvalidParameterValueException("Could not find vpn user " + username); @@ -499,10 +495,9 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag } @Override - public List searchForVpnUsers(ListVpnUsersCmd cmd) { + public Pair, Integer> searchForVpnUsers(ListVpnUsersCmd cmd) { String username = cmd.getUsername(); Long id = cmd.getId(); - Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); @@ -534,11 +529,12 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag sc.setParameters("username", username); } - return _vpnUsersDao.search(sc, searchFilter); + Pair, Integer> result = _vpnUsersDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd) { + public Pair, Integer> searchForRemoteAccessVpns(ListRemoteAccessVpnsCmd cmd) { // do some parameter validation Account caller = UserContext.current().getCaller(); Long ipAddressId = cmd.getPublicIpId(); @@ -581,7 +577,8 @@ public class RemoteAccessVpnManagerImpl implements RemoteAccessVpnService, Manag sc.setParameters("serverAddressId", ipAddressId); } - return _remoteAccessVpnDao.search(sc, filter); + Pair, Integer> result = _remoteAccessVpnDao.searchAndCount(sc, filter); + return new Pair, Integer> (result.first(), result.second()); } @Override diff --git a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java index ddc79a0565d..9b2c04946bd 100644 --- a/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java +++ b/server/src/com/cloud/network/vpn/Site2SiteVpnManagerImpl.java @@ -27,17 +27,17 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnCustomerGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ResetVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.event.ActionEvent; @@ -67,8 +67,8 @@ import com.cloud.user.Account; import com.cloud.user.AccountManager; import com.cloud.user.UserContext; import com.cloud.user.dao.AccountDao; -import com.cloud.user.dao.UserStatisticsDao; import com.cloud.utils.NumbersUtil; +import com.cloud.utils.Pair; import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; @@ -570,7 +570,7 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { } @Override - public List searchForCustomerGateways(ListVpnCustomerGatewaysCmd cmd) { + public Pair, Integer> searchForCustomerGateways(ListVpnCustomerGatewaysCmd cmd) { Long id = cmd.getId(); Long domainId = cmd.getDomainId(); boolean isRecursive = cmd.isRecursive(); @@ -602,13 +602,12 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { sc.addAnd("id", SearchCriteria.Op.EQ, id); } - List results = new ArrayList(); - results.addAll(_customerGatewayDao.search(sc, searchFilter)); - return results; + Pair, Integer> result = _customerGatewayDao.searchAndCount(sc, searchFilter); + return new Pair, Integer> (result.first(), result.second()); } @Override - public List searchForVpnGateways(ListVpnGatewaysCmd cmd) { + public Pair, Integer> searchForVpnGateways(ListVpnGatewaysCmd cmd) { Long id = cmd.getId(); Long vpcId = cmd.getVpcId(); @@ -647,13 +646,12 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { sc.addAnd("vpcId", SearchCriteria.Op.EQ, vpcId); } - List results = new ArrayList(); - results.addAll(_vpnGatewayDao.search(sc, searchFilter)); - return results; + Pair, Integer> result = _vpnGatewayDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForVpnConnections(ListVpnConnectionsCmd cmd) { + public Pair, Integer> searchForVpnConnections(ListVpnConnectionsCmd cmd) { Long id = cmd.getId(); Long vpcId = cmd.getVpcId(); @@ -697,9 +695,8 @@ public class Site2SiteVpnManagerImpl implements Site2SiteVpnManager, Manager { sc.setJoinParameters("gwSearch", "vpcId", vpcId); } - List results = new ArrayList(); - results.addAll(_vpnConnectionDao.search(sc, searchFilter)); - return results; + Pair, Integer> result = _vpnConnectionDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override diff --git a/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java index b21581419d0..f249405e7b6 100644 --- a/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingServiceMapVO.java @@ -28,10 +28,11 @@ import javax.persistence.Table; import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="ntwk_offering_service_map") -public class NetworkOfferingServiceMapVO { +public class NetworkOfferingServiceMapVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/offerings/NetworkOfferingVO.java b/server/src/com/cloud/offerings/NetworkOfferingVO.java index 77407560c7e..8de93d87b54 100755 --- a/server/src/com/cloud/offerings/NetworkOfferingVO.java +++ b/server/src/com/cloud/offerings/NetworkOfferingVO.java @@ -5,7 +5,7 @@ // 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, @@ -16,6 +16,8 @@ // under the License. package com.cloud.offerings; +import com.cloud.network.Networks; + import java.util.Date; import java.util.UUID; @@ -28,15 +30,20 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.Network; import com.cloud.network.Networks.TrafficType; import com.cloud.offering.NetworkOffering; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; + +import javax.persistence.*; +import java.util.Date; +import java.util.UUID; @Entity @Table(name = "network_offerings") -public class NetworkOfferingVO implements NetworkOffering, Identity { +public class NetworkOfferingVO implements NetworkOffering { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -122,6 +129,12 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { @Column(name = "elastic_lb_service") boolean elasticLb; + @Column(name = "eip_associate_public_ip") + boolean eipAssociatePublicIp; + + @Column(name = "inline") + boolean inline; + @Override public String getDisplayText() { return displayText; @@ -282,18 +295,22 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { this.redundantRouter = false; this.elasticIp = false; this.elasticLb = false; + this.eipAssociatePublicIp = true; + this.inline = false; 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, boolean inline) { 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; + this.inline = inline; } public NetworkOfferingVO() { @@ -301,7 +318,7 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { /** * Network Offering for all system vms. - * + * * @param name * @param trafficType * @param specifyIpRanges @@ -311,9 +328,9 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { this(name, "System Offering for " + name, trafficType, true, false, 0, 0, true, Availability.Required, null, null, true, specifyIpRanges); this.state = State.Enabled; } - + public NetworkOfferingVO(String name, Network.GuestType guestType) { - this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional, + this(name, "System Offering for " + name, TrafficType.Guest, true, true, 0, 0, true, Availability.Optional, null, Network.GuestType.Isolated, true, false); this.state = State.Enabled; } @@ -355,6 +372,11 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { return elasticIp; } + @Override + public boolean getAssociatePublicIP() { + return eipAssociatePublicIp; + } + @Override public boolean getElasticLb() { return elasticLb; @@ -365,4 +387,8 @@ public class NetworkOfferingVO implements NetworkOffering, Identity { return specifyIpRanges; } + @Override + public boolean isInline() { + return inline; + } } diff --git a/server/src/com/cloud/projects/ProjectAccountVO.java b/server/src/com/cloud/projects/ProjectAccountVO.java index c3d7d735e73..8c4f1ba5e04 100644 --- a/server/src/com/cloud/projects/ProjectAccountVO.java +++ b/server/src/com/cloud/projects/ProjectAccountVO.java @@ -28,11 +28,12 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="project_account") @SuppressWarnings("unused") -public class ProjectAccountVO implements ProjectAccount{ +public class ProjectAccountVO implements ProjectAccount, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/projects/ProjectInvitationVO.java b/server/src/com/cloud/projects/ProjectInvitationVO.java index 7dc8f7daf54..78f05c792e6 100644 --- a/server/src/com/cloud/projects/ProjectInvitationVO.java +++ b/server/src/com/cloud/projects/ProjectInvitationVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "project_invitations") -public class ProjectInvitationVO implements ProjectInvitation, Identity { +public class ProjectInvitationVO implements ProjectInvitation { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") diff --git a/server/src/com/cloud/projects/ProjectManager.java b/server/src/com/cloud/projects/ProjectManager.java index a243d2d3891..f5681464615 100644 --- a/server/src/com/cloud/projects/ProjectManager.java +++ b/server/src/com/cloud/projects/ProjectManager.java @@ -35,4 +35,6 @@ public interface ProjectManager extends ProjectService { boolean deleteProject(Account caller, long callerUserId, ProjectVO project); + long getInvitationTimeout(); + } diff --git a/server/src/com/cloud/projects/ProjectManagerImpl.java b/server/src/com/cloud/projects/ProjectManagerImpl.java index 52b9fca546a..ab7b7b126cb 100755 --- a/server/src/com/cloud/projects/ProjectManagerImpl.java +++ b/server/src/com/cloud/projects/ProjectManagerImpl.java @@ -17,7 +17,6 @@ package com.cloud.projects; import java.io.UnsupportedEncodingException; -import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; @@ -42,12 +41,14 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import com.cloud.api.query.dao.ProjectAccountJoinDao; +import com.cloud.api.query.dao.ProjectInvitationJoinDao; +import com.cloud.api.query.dao.ProjectJoinDao; 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.domain.DomainVO; import com.cloud.domain.dao.DomainDao; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; @@ -56,33 +57,26 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; -import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.Project.State; import com.cloud.projects.ProjectAccount.Role; import com.cloud.projects.dao.ProjectAccountDao; import com.cloud.projects.dao.ProjectDao; import com.cloud.projects.dao.ProjectInvitationDao; -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.dao.AccountDao; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; -import com.cloud.utils.Ternary; +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.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.sun.mail.smtp.SMTPMessage; @@ -101,6 +95,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ @Inject private ProjectDao _projectDao; @Inject + private ProjectJoinDao _projectJoinDao; + @Inject AccountManager _accountMgr; @Inject DomainManager _domainMgr; @@ -111,12 +107,16 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ @Inject private ProjectAccountDao _projectAccountDao; @Inject + private ProjectAccountJoinDao _projectAccountJoinDao; + @Inject private AccountDao _accountDao; @Inject private ConfigurationDao _configDao; @Inject private ProjectInvitationDao _projectInvitationDao; @Inject + private ProjectInvitationJoinDao _projectInvitationJoinDao; + @Inject protected ResourceTagDao _resourceTagDao; protected boolean _invitationRequired = false; @@ -285,7 +285,8 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ txn.commit(); if (updateResult) { - if (!cleanupProject(project, _accountDao.findById(caller.getId()), callerUserId)) { + //pass system caller when clenaup projects account + if (!cleanupProject(project, _accountDao.findById(Account.ACCOUNT_ID_SYSTEM), User.UID_SYSTEM)) { s_logger.warn("Failed to cleanup project's id=" + project.getId() + " resources, not removing the project yet"); return false; } else { @@ -353,126 +354,12 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return _projectDao.findById(projectId); } + @Override - public List listProjects(Long id, String name, String displayText, String state, - String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, - boolean isRecursive, Map tags) { - Account caller = UserContext.current().getCaller(); - Long accountId = null; - String path = null; - - Filter searchFilter = new Filter(ProjectVO.class, "id", false, startIndex, pageSize); - SearchBuilder sb = _projectDao.createSearchBuilder(); - - if (_accountMgr.isAdmin(caller.getType())) { - if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist in the system"); - } - - _accountMgr.checkAccess(caller, domain); - - if (accountName != null) { - Account owner = _accountMgr.getActiveAccountByName(accountName, domainId); - if (owner == null) { - throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain " + domainId); - } - accountId = owner.getId(); - } - } - } else { - if (accountName != null && !accountName.equals(caller.getAccountName())) { - throw new PermissionDeniedException("Can't list account " + accountName + " projects; unauthorized"); - } - - if (domainId != null && domainId.equals(caller.getDomainId())) { - throw new PermissionDeniedException("Can't list domain id= " + domainId + " projects; unauthorized"); - } - - accountId = caller.getId(); + public long getInvitationTimeout() { + return _invitationTimeOut; } - if (domainId == null && accountId == null && (caller.getType() == Account.ACCOUNT_TYPE_NORMAL || !listAll)) { - accountId = caller.getId(); - } else if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || (isRecursive && !listAll)) { - DomainVO domain = _domainDao.findById(caller.getDomainId()); - path = domain.getPath(); - } - - if (path != null) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (accountId != null) { - SearchBuilder projectAccountSearch = _projectAccountDao.createSearchBuilder(); - projectAccountSearch.and("accountId", projectAccountSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.join("projectAccountSearch", projectAccountSearch, sb.entity().getId(), projectAccountSearch.entity().getProjectId(), JoinBuilder.JoinType.INNER); - } - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - if (id != null) { - sc.addAnd("id", Op.EQ, id); - } - - if (domainId != null && !isRecursive) { - sc.addAnd("domainId", Op.EQ, domainId); - } - - if (name != null) { - sc.addAnd("name", Op.EQ, name); - } - - if (displayText != null) { - sc.addAnd("displayText", Op.EQ, displayText); - } - - if (accountId != null) { - sc.setJoinParameters("projectAccountSearch", "accountId", accountId); - } - - if (state != null) { - sc.addAnd("state", Op.EQ, state); - } - - if (keyword != null) { - SearchCriteria ssc = _projectDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("displayText", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (path != null) { - sc.setJoinParameters("domainSearch", "path", path); - } - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Project.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - return _projectDao.search(sc, searchFilter); - } @Override public ProjectAccount assignAccountToProject(Project project, long accountId, ProjectAccount.Role accountRole) { @@ -741,48 +628,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ } - @Override - public List listProjectAccounts(long projectId, String accountName, String role, Long startIndex, Long pageSizeVal) { - Account caller = UserContext.current().getCaller(); - //check that the project exists - Project project = getProject(projectId); - - if (project == null) { - throw new InvalidParameterValueException("Unable to find the project id=" + projectId); - } - - //verify permissions - only accounts belonging to the project can list project's account - if (!_accountMgr.isAdmin(caller.getType()) && _projectAccountDao.findByProjectIdAccountId(projectId, caller.getAccountId()) == null) { - throw new PermissionDeniedException("Account " + caller + " is not authorized to list users of the project id=" + projectId); - } - - Filter searchFilter = new Filter(ProjectAccountVO.class, "id", false, startIndex, pageSizeVal); - SearchBuilder sb = _projectAccountDao.createSearchBuilder(); - sb.and("accountRole", sb.entity().getAccountRole(), Op.EQ); - sb.and("projectId", sb.entity().getProjectId(), Op.EQ); - - SearchBuilder accountSearch; - if (accountName != null) { - accountSearch = _accountDao.createSearchBuilder(); - accountSearch.and("accountName", accountSearch.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - sc.setParameters("projectId", projectId); - - if (role != null) { - sc.setParameters("accountRole", role); - } - - if (accountName != null) { - sc.setJoinParameters("accountSearch", "accountName", accountName); - } - - return _projectAccountDao.search(sc, searchFilter); - } public ProjectInvitation createAccountInvitation(Project project, Long accountId) { if (activeInviteExists(project, accountId, null)) { @@ -852,49 +698,7 @@ public class ProjectManagerImpl implements ProjectManager, Manager{ return _projectInvitationDao.update(invite.getId(), invite); } - @Override - public List listProjectInvitations(Long id, Long projectId, String accountName, Long domainId, String state, boolean activeOnly, Long startIndex, Long pageSizeVal, boolean isRecursive, boolean listAll) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(domainId, isRecursive, null); - _accountMgr.buildACLSearchParameters(caller, id, accountName, projectId, permittedAccounts, domainIdRecursiveListProject, listAll, true); - domainId = domainIdRecursiveListProject.first(); - isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(ProjectInvitationVO.class, "id", true, startIndex, pageSizeVal); - SearchBuilder sb = _projectInvitationDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - sb.and("projectId", sb.entity().getProjectId(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("created", sb.entity().getCreated(), SearchCriteria.Op.GT); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - - if (projectId != null){ - sc.setParameters("projectId", projectId); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (activeOnly) { - sc.setParameters("state", ProjectInvitation.State.Pending); - sc.setParameters("created", new Date((DateUtil.currentGMTTime().getTime()) - _invitationTimeOut)); - } - - return _projectInvitationDao.search(sc, searchFilter); - } @Override @DB @ActionEvent(eventType = EventTypes.EVENT_PROJECT_INVITATION_UPDATE, eventDescription = "updating project invitation", async=true) diff --git a/server/src/com/cloud/projects/ProjectVO.java b/server/src/com/cloud/projects/ProjectVO.java index 9a84a213da7..53947f1562d 100644 --- a/server/src/com/cloud/projects/ProjectVO.java +++ b/server/src/com/cloud/projects/ProjectVO.java @@ -28,12 +28,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="projects") -public class ProjectVO implements Project, Identity { +public class ProjectVO implements Project, Identity, InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/resource/ResourceManagerImpl.java b/server/src/com/cloud/resource/ResourceManagerImpl.java index b4f6d146ee9..cbcdccb5f64 100755 --- a/server/src/com/cloud/resource/ResourceManagerImpl.java +++ b/server/src/com/cloud/resource/ResourceManagerImpl.java @@ -32,6 +32,16 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.cluster.AddClusterCmd; +import org.apache.cloudstack.api.command.admin.storage.ListS3sCmd; +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 org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; +import com.cloud.storage.S3; +import com.cloud.storage.S3VO; +import com.cloud.storage.s3.S3Manager; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -49,19 +59,12 @@ import com.cloud.agent.api.UpdateHostPasswordCommand; import com.cloud.agent.manager.AgentAttache; import com.cloud.agent.manager.allocator.PodAllocator; import com.cloud.agent.transport.Request; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.AddClusterCmd; -import com.cloud.api.commands.AddHostCmd; -import com.cloud.api.commands.AddSecondaryStorageCmd; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.CancelMaintenanceCmd; -import com.cloud.api.commands.DeleteClusterCmd; -import com.cloud.api.commands.ListSwiftsCmd; -import com.cloud.api.commands.PrepareForMaintenanceCmd; -import com.cloud.api.commands.ReconnectHostCmd; -import com.cloud.api.commands.UpdateHostCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; +import org.apache.cloudstack.api.command.admin.host.AddHostCmd; +import org.apache.cloudstack.api.command.admin.host.CancelMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.host.PrepareForMaintenanceCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostCmd; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityVO; import com.cloud.capacity.dao.CapacityDao; @@ -72,7 +75,6 @@ import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.ClusterDetailsDao; import com.cloud.dc.ClusterVO; -import com.cloud.dc.ClusterVSMMapVO; import com.cloud.dc.DataCenterIpAddressVO; import com.cloud.dc.DataCenterVO; import com.cloud.dc.HostPodVO; @@ -133,7 +135,6 @@ import com.cloud.user.UserContext; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.UriUtils; -import com.cloud.utils.cisco.n1kv.vsm.NetconfHelper; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; @@ -184,6 +185,8 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma @Inject protected SwiftManager _swiftMgr; @Inject + protected S3Manager _s3Mgr; + @Inject protected HostDetailsDao _hostDetailsDao; @Inject protected ConfigurationDao _configDao; @@ -570,6 +573,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; @@ -1170,7 +1183,7 @@ public class ResourceManagerImpl implements ResourceManager, ResourceService, Ma throw new InvalidParameterValueException("There are other servers in PrepareForMaintenance OR ErrorInMaintenance STATUS in cluster " + host.getClusterId()); } - if (_storageMgr.isLocalStorageActiveOnHost(host)) { + if (_storageMgr.isLocalStorageActiveOnHost(host.getId())) { throw new InvalidParameterValueException("There are active VMs using the host's local storage pool. Please stop all VMs on this host that use local storage."); } diff --git a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java index 53e260b0e33..3566834cd75 100755 --- a/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java +++ b/server/src/com/cloud/resourcelimit/ResourceLimitManagerImpl.java @@ -32,7 +32,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.alert.AlertManager; import com.cloud.configuration.Config; import com.cloud.configuration.Resource; @@ -244,6 +244,36 @@ public class ResourceLimitManagerImpl implements ResourceLimitService, Manager { return max; } + @Override + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type) { + + long max = Resource.RESOURCE_UNLIMITED; // if resource limit is not found, then we treat it as unlimited + + // No limits for Root Admin accounts + if (_accountMgr.isRootAdmin(accountType)) { + return max; + } + + + // Check if limit is configured for account + if (limit != null) { + max = limit.longValue(); + } else { + // If the account has an no limit set, then return global default account limits + Long value = null; + if (accountType == Account.ACCOUNT_TYPE_PROJECT) { + value = projectResourceLimitMap.get(type); + } else { + value = accountResourceLimitMap.get(type); + } + if (value != null) { + return value; + } + } + + return max; + } + @Override public long findCorrectResourceLimitForDomain(Domain domain, ResourceType type) { long max = Resource.RESOURCE_UNLIMITED; diff --git a/server/src/com/cloud/secstorage/CommandExecLogVO.java b/server/src/com/cloud/secstorage/CommandExecLogVO.java index e9d7d9a2580..4ec023e4e55 100644 --- a/server/src/com/cloud/secstorage/CommandExecLogVO.java +++ b/server/src/com/cloud/secstorage/CommandExecLogVO.java @@ -28,10 +28,11 @@ import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.cloud.utils.DateUtil; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="cmd_exec_log") -public class CommandExecLogVO { +public class CommandExecLogVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/server/ConfigurationServerImpl.java b/server/src/com/cloud/server/ConfigurationServerImpl.java index 781305b3715..28f28cb4b60 100755 --- a/server/src/com/cloud/server/ConfigurationServerImpl.java +++ b/server/src/com/cloud/server/ConfigurationServerImpl.java @@ -16,37 +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.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 javax.inject.Inject; - -import org.apache.commons.codec.binary.Base64; -import org.apache.log4j.Logger; -import org.springframework.stereotype.Component; - import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.Resource; @@ -76,11 +45,7 @@ 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; @@ -106,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; @Component public class ConfigurationServerImpl implements ConfigurationServer { @@ -286,6 +265,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { _identityDao.initializeDefaultUuid("virtual_router_providers"); _identityDao.initializeDefaultUuid("networks"); _identityDao.initializeDefaultUuid("user_ip_address"); + _identityDao.initializeDefaultUuid("counter"); } private String getMountParent() { @@ -321,7 +301,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { } catch (SQLException ex) { } // insert system user - insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) VALUES (1, 'system', '', 1, 'system', 'cloud', now())"; + insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created)" + + " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())"; txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); @@ -329,29 +310,12 @@ public class ConfigurationServerImpl implements ConfigurationServer { } catch (SQLException ex) { } - // insert admin user + // insert admin user, but leave the account disabled until we set a + // password with the user authenticator long id = 2; String username = "admin"; String firstname = "admin"; String lastname = "cloud"; - String password = "password"; - - MessageDigest md5 = null; - try { - md5 = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - return; - } - - md5.reset(); - BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); - String pwStr = pwInt.toString(16); - int padding = 32 - pwStr.length(); - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < padding; i++) { - sb.append('0'); // make sure the MD5 password is 32 digits long - } - sb.append(pwStr); // create an account for the admin user first insertSql = "INSERT INTO `cloud`.`account` (id, account_name, type, domain_id) VALUES (" + id + ", '" + username + "', '1', '1')"; @@ -363,8 +327,8 @@ public class ConfigurationServerImpl implements ConfigurationServer { } // now insert the user - insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) " + - "VALUES (" + id + ",'" + username + "','" + sb.toString() + "', 2, '" + firstname + "','" + lastname + "',now())"; + insertSql = "INSERT INTO `cloud`.`user` (id, username, account_id, firstname, lastname, created, state) " + + "VALUES (" + id + ",'" + username + "', 2, '" + firstname + "','" + lastname + "',now(), 'disabled')"; txn = Transaction.currentTxn(); try { @@ -474,7 +438,7 @@ public class ConfigurationServerImpl implements ConfigurationServer { script.add("-dname", dname); String result = script.execute(); if (result != null) { - throw new IOException("Fail to generate certificate!"); + throw new IOException("Fail to generate certificate!: " + result); } } @@ -570,7 +534,8 @@ 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"); @@ -992,7 +957,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, false); defaultNetscalerNetworkOffering.setState(NetworkOffering.State.Enabled); defaultNetscalerNetworkOffering = _networkOfferingDao.persistDefaultNetworkOffering(defaultNetscalerNetworkOffering); diff --git a/server/src/com/cloud/server/ManagementServer.java b/server/src/com/cloud/server/ManagementServer.java index 0b77acd23ad..8655d15025e 100755 --- a/server/src/com/cloud/server/ManagementServer.java +++ b/server/src/com/cloud/server/ManagementServer.java @@ -25,11 +25,12 @@ import com.cloud.info.ConsoleProxyInfo; import com.cloud.storage.GuestOSVO; import com.cloud.storage.StoragePoolVO; import com.cloud.utils.Pair; +import com.cloud.utils.component.PluggableService; import com.cloud.vm.VirtualMachine; /** */ -public interface ManagementServer extends ManagementService { +public interface ManagementServer extends ManagementService, PluggableService { /** * returns the instance id of this management server. @@ -46,8 +47,6 @@ public interface ManagementServer extends ManagementService { @Override String getVersion(); - String[] getApiConfig(); - /** * Retrieves a host by id * @@ -94,7 +93,9 @@ public interface ManagementServer extends ManagementService { public long getMemoryOrCpuCapacityByHost(Long hostId, short capacityType); - List searchForStoragePools(Criteria c); + Pair, Integer> searchForStoragePools(Criteria c); String getHashKey(); + + public void enableAdminUser(String password); } diff --git a/server/src/com/cloud/server/ManagementServerExt.java b/server/src/com/cloud/server/ManagementServerExt.java index 0804e4fe05f..4e506a3bc4a 100644 --- a/server/src/com/cloud/server/ManagementServerExt.java +++ b/server/src/com/cloud/server/ManagementServerExt.java @@ -21,7 +21,7 @@ import java.util.TimeZone; import com.cloud.api.commands.GenerateUsageRecordsCmd; import com.cloud.api.commands.GetUsageRecordsCmd; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.usage.UsageVO; public interface ManagementServerExt extends ManagementServer { /** diff --git a/server/src/com/cloud/server/ManagementServerExtImpl.java b/server/src/com/cloud/server/ManagementServerExtImpl.java index 8c4b3885c10..5ab6d037d3c 100644 --- a/server/src/com/cloud/server/ManagementServerExtImpl.java +++ b/server/src/com/cloud/server/ManagementServerExtImpl.java @@ -35,7 +35,7 @@ import com.cloud.domain.dao.DomainDao; import com.cloud.exception.InvalidParameterValueException; import com.cloud.exception.PermissionDeniedException; import com.cloud.projects.Project; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; import com.cloud.usage.UsageJobVO; import com.cloud.usage.UsageTypes; import com.cloud.usage.UsageVO; @@ -211,7 +211,7 @@ public class ManagementServerExtImpl extends ManagementServerImpl implements Man } @Override - public String[] getApiConfig() { + public String[] getPropertiesFiles() { return new String[] { "commands.properties", "commands-ext.properties" }; } diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index d98825bd11a..871d0d36da3 100755 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -44,11 +44,33 @@ import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.inject.Inject; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoCmd; +import org.apache.cloudstack.api.command.admin.cluster.ListClustersCmd; +import org.apache.cloudstack.api.command.admin.config.ListCfgsByCmd; +import org.apache.cloudstack.api.command.admin.resource.ListAlertsCmd; +import org.apache.cloudstack.api.command.admin.storage.ListStoragePoolsCmd; +import org.apache.cloudstack.api.command.admin.systemvm.DestroySystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.UpgradeSystemVMCmd; +import org.apache.cloudstack.api.command.user.address.ListPublicIpAddressesCmd; +import org.apache.cloudstack.api.command.user.config.ListCapabilitiesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCategoriesCmd; +import org.apache.cloudstack.api.command.user.guest.ListGuestOsCmd; +import org.apache.cloudstack.api.command.user.iso.ListIsosCmd; +import org.apache.cloudstack.api.command.user.iso.UpdateIsoCmd; +import org.apache.cloudstack.api.command.user.offering.ListDiskOfferingsCmd; +import org.apache.cloudstack.api.command.user.offering.ListServiceOfferingsCmd; +import org.apache.cloudstack.api.command.user.ssh.ListSSHKeyPairsCmd; +import org.apache.cloudstack.api.command.user.ssh.DeleteSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.ssh.RegisterSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.template.ListTemplatesCmd; +import org.apache.cloudstack.api.command.user.template.UpdateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.GetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.zone.ListZonesByCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; @@ -59,48 +81,25 @@ import com.cloud.alert.Alert; import com.cloud.alert.AlertManager; import com.cloud.alert.AlertVO; import com.cloud.alert.dao.AlertDao; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CreateSSHKeyPairCmd; -import com.cloud.api.commands.DeleteSSHKeyPairCmd; -import com.cloud.api.commands.DestroySystemVmCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.commands.GetVMPasswordCmd; -import com.cloud.api.commands.ListAlertsCmd; -import com.cloud.api.commands.ListAsyncJobsCmd; -import com.cloud.api.commands.ListCapabilitiesCmd; -import com.cloud.api.commands.ListCapacityCmd; -import com.cloud.api.commands.ListCfgsByCmd; -import com.cloud.api.commands.ListClustersCmd; -import com.cloud.api.commands.ListDiskOfferingsCmd; -import com.cloud.api.commands.ListEventsCmd; -import com.cloud.api.commands.ListGuestOsCategoriesCmd; -import com.cloud.api.commands.ListGuestOsCmd; -import com.cloud.api.commands.ListHostsCmd; -import com.cloud.api.commands.ListIsosCmd; -import com.cloud.api.commands.ListPodsByCmd; -import com.cloud.api.commands.ListPublicIpAddressesCmd; -import com.cloud.api.commands.ListRoutersCmd; -import com.cloud.api.commands.ListSSHKeyPairsCmd; -import com.cloud.api.commands.ListServiceOfferingsCmd; -import com.cloud.api.commands.ListStoragePoolsCmd; -import com.cloud.api.commands.ListSystemVMsCmd; -import com.cloud.api.commands.ListTemplatesCmd; -import com.cloud.api.commands.ListVMGroupsCmd; -import com.cloud.api.commands.ListVlanIpRangesCmd; -import com.cloud.api.commands.ListZonesByCmd; -import com.cloud.api.commands.RebootSystemVmCmd; -import com.cloud.api.commands.RegisterSSHKeyPairCmd; -import com.cloud.api.commands.StopSystemVmCmd; -import com.cloud.api.commands.UpdateDomainCmd; -import com.cloud.api.commands.UpdateHostPasswordCmd; -import com.cloud.api.commands.UpdateIsoCmd; -import com.cloud.api.commands.UpdateTemplateCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoCmd; -import com.cloud.api.commands.UpdateVMGroupCmd; -import com.cloud.api.commands.UpgradeSystemVMCmd; -import com.cloud.api.commands.UploadCustomCertificateCmd; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.command.user.ssh.CreateSSHKeyPairCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; +import org.apache.cloudstack.api.command.admin.resource.ListCapacityCmd; +import org.apache.cloudstack.api.command.admin.pod.ListPodsByCmd; +import org.apache.cloudstack.api.command.admin.systemvm.ListSystemVMsCmd; +import org.apache.cloudstack.api.command.admin.vlan.ListVlanIpRangesCmd; +import org.apache.cloudstack.api.command.admin.systemvm.RebootSystemVmCmd; +import org.apache.cloudstack.api.command.admin.systemvm.StopSystemVmCmd; +import org.apache.cloudstack.api.command.admin.domain.UpdateDomainCmd; +import org.apache.cloudstack.api.command.admin.host.UpdateHostPasswordCmd; +import com.cloud.api.query.dao.DomainRouterJoinDao; +import com.cloud.api.query.dao.InstanceGroupJoinDao; + +import org.apache.cloudstack.api.command.user.vmgroup.UpdateVMGroupCmd; +import org.apache.cloudstack.api.command.admin.resource.UploadCustomCertificateCmd; +import org.apache.cloudstack.api.response.ExtractResponse; + import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; @@ -113,6 +112,7 @@ import com.cloud.capacity.dao.CapacityDao; import com.cloud.capacity.dao.CapacityDaoImpl.SummedCapacity; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; +import com.cloud.configuration.Configuration; import com.cloud.configuration.ConfigurationVO; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.consoleproxy.ConsoleProxyManagementState; @@ -121,7 +121,9 @@ import com.cloud.dc.AccountVlanMapVO; import com.cloud.dc.ClusterVO; 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; @@ -139,6 +141,7 @@ import com.cloud.event.EventTypes; import com.cloud.event.EventUtils; import com.cloud.event.EventVO; import com.cloud.event.dao.EventDao; +import com.cloud.event.dao.EventJoinDao; import com.cloud.exception.CloudAuthenticationException; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InvalidParameterValueException; @@ -162,6 +165,7 @@ import com.cloud.hypervisor.dao.HypervisorCapabilitiesDao; import com.cloud.info.ConsoleProxyInfo; import com.cloud.keystore.KeystoreManager; import com.cloud.network.IPAddressVO; +import com.cloud.network.IpAddress; import com.cloud.network.LoadBalancerVO; import com.cloud.network.NetworkVO; import com.cloud.network.dao.IPAddressDao; @@ -174,14 +178,18 @@ import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.projects.ProjectManager; import com.cloud.resource.ResourceManager; import com.cloud.server.ResourceTag.TaggedResourceType; +import com.cloud.server.auth.UserAuthenticator; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.GuestOS; import com.cloud.storage.GuestOSCategoryVO; import com.cloud.storage.GuestOSVO; +import com.cloud.storage.GuestOsCategory; import com.cloud.storage.Storage; import com.cloud.storage.Storage.ImageFormat; import com.cloud.storage.StorageManager; +import com.cloud.storage.StoragePool; import com.cloud.storage.StoragePoolVO; import com.cloud.storage.Upload; import com.cloud.storage.Upload.Mode; @@ -196,6 +204,7 @@ import com.cloud.storage.dao.StoragePoolDao; import com.cloud.storage.dao.UploadDao; 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.snapshot.SnapshotManager; import com.cloud.storage.swift.SwiftManager; @@ -205,11 +214,11 @@ import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.VirtualMachineTemplate.TemplateFilter; import com.cloud.user.Account; import com.cloud.user.AccountManager; -import com.cloud.user.AccountVO; import com.cloud.user.SSHKeyPair; import com.cloud.user.SSHKeyPairVO; import com.cloud.user.User; import com.cloud.user.UserContext; +import com.cloud.user.UserVO; import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.SSHKeyPairDao; import com.cloud.user.dao.UserDao; @@ -240,7 +249,6 @@ import com.cloud.utils.ssh.SSHKeysHelper; import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; import com.cloud.vm.InstanceGroupVO; -import com.cloud.vm.NicVO; import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.UserVmVO; import com.cloud.vm.VMInstanceVO; @@ -264,79 +272,148 @@ import edu.emory.mathcs.backport.java.util.Collections; public class ManagementServerImpl implements ManagementServer { public static final Logger s_logger = Logger.getLogger(ManagementServerImpl.class.getName()); - @Inject private AccountManager _accountMgr; - @Inject private AgentManager _agentMgr; - @Inject private AlertManager _alertMgr; - @Inject private IPAddressDao _publicIpAddressDao; - @Inject private DomainRouterDao _routerDao; - @Inject private ConsoleProxyDao _consoleProxyDao; - @Inject private ClusterDao _clusterDao; - @Inject private SecondaryStorageVmDao _secStorageVmDao; - @Inject private EventDao _eventDao; - @Inject private DataCenterDao _dcDao; - @Inject private VlanDao _vlanDao; - @Inject private AccountVlanMapDao _accountVlanMapDao; - @Inject private PodVlanMapDao _podVlanMapDao; - @Inject private HostDao _hostDao; - @Inject private HostDetailsDao _detailsDao; - @Inject private UserDao _userDao; - @Inject private UserVmDao _userVmDao; - @Inject private ConfigurationDao _configDao; - @Inject private ConsoleProxyManager _consoleProxyMgr; - @Inject private SecondaryStorageVmManager _secStorageVmMgr; - @Inject private SwiftManager _swiftMgr; - @Inject private ServiceOfferingDao _offeringsDao; - @Inject private DiskOfferingDao _diskOfferingDao; - @Inject private VMTemplateDao _templateDao; - @Inject private DomainDao _domainDao; - @Inject private AccountDao _accountDao; - @Inject private AlertDao _alertDao; - @Inject private CapacityDao _capacityDao; - @Inject private GuestOSDao _guestOSDao; - @Inject private GuestOSCategoryDao _guestOSCategoryDao; - @Inject private StoragePoolDao _poolDao; - @Inject private NicDao _nicDao; - @Inject private NetworkDao _networkDao; - @Inject private StorageManager _storageMgr; - @Inject private VirtualMachineManager _itMgr; - @Inject private HostPodDao _hostPodDao; - @Inject private VMInstanceDao _vmInstanceDao; - @Inject private VolumeDao _volumeDao; - @Inject private AsyncJobDao _jobDao; - @Inject private AsyncJobManager _asyncMgr; - private int _purgeDelay; - @Inject private InstanceGroupDao _vmGroupDao; - @Inject private UploadMonitor _uploadMonitor; - @Inject private UploadDao _uploadDao; - @Inject private SSHKeyPairDao _sshKeyPairDao; - @Inject private LoadBalancerDao _loadbalancerDao; - @Inject private HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; - - @Inject private List _hostAllocators; - @Inject private ConfigurationManager _configMgr; - @Inject private ResourceTagDao _resourceTagDao; - - @Inject ProjectManager _projectMgr; - @Inject ResourceManager _resourceMgr; - @Inject SnapshotManager _snapshotMgr; - @Inject HighAvailabilityManager _haMgr; - @Inject HostTagsDao _hostTagsDao; + private final AccountManager _accountMgr; + private final AgentManager _agentMgr; + private final AlertManager _alertMgr; + private final IPAddressDao _publicIpAddressDao; + private final DomainRouterDao _routerDao; + private final DomainRouterJoinDao _routerJoinDao; + private final ConsoleProxyDao _consoleProxyDao; + private final ClusterDao _clusterDao; + private final SecondaryStorageVmDao _secStorageVmDao; + private final EventDao _eventDao; + private final EventJoinDao _eventJoinDao; + private final DataCenterDao _dcDao; + private final VlanDao _vlanDao; + private final AccountVlanMapDao _accountVlanMapDao; + private final PodVlanMapDao _podVlanMapDao; + private final HostDao _hostDao; + private final HostDetailsDao _detailsDao; + private final UserDao _userDao; + private final UserVmDao _userVmDao; + private final ConfigurationDao _configDao; + private final ConsoleProxyManager _consoleProxyMgr; + private final SecondaryStorageVmManager _secStorageVmMgr; + private final SwiftManager _swiftMgr; + private final S3Manager _s3Mgr; + private final ServiceOfferingDao _offeringsDao; + private final DiskOfferingDao _diskOfferingDao; + private final VMTemplateDao _templateDao; + private final DomainDao _domainDao; + private final AccountDao _accountDao; + private final AlertDao _alertDao; + private final CapacityDao _capacityDao; + private final GuestOSDao _guestOSDao; + private final GuestOSCategoryDao _guestOSCategoryDao; + private final StoragePoolDao _poolDao; + private final NicDao _nicDao; + private final NetworkDao _networkDao; + private final StorageManager _storageMgr; + private final VirtualMachineManager _itMgr; + private final HostPodDao _hostPodDao; + private final VMInstanceDao _vmInstanceDao; + private final VolumeDao _volumeDao; + private final AsyncJobDao _jobDao; + private final AsyncJobManager _asyncMgr; + private final int _purgeDelay; + private final InstanceGroupDao _vmGroupDao; + private final InstanceGroupJoinDao _vmGroupJoinDao; + private final UploadMonitor _uploadMonitor; + private final UploadDao _uploadDao; + private final SSHKeyPairDao _sshKeyPairDao; + private final LoadBalancerDao _loadbalancerDao; + private final HypervisorCapabilitiesDao _hypervisorCapabilitiesDao; + private final Adapters _hostAllocators; + private final ConfigurationManager _configMgr; + private final ResourceTagDao _resourceTagDao; - @Inject ComponentContext _placeholder; - - private KeystoreManager _ksMgr; + @Inject + ProjectManager _projectMgr; + private final ResourceManager _resourceMgr; + @Inject + SnapshotManager _snapshotMgr; + @Inject + HighAvailabilityManager _haMgr; + @Inject + HostTagsDao _hostTagsDao; - private ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); + private final KeystoreManager _ksMgr; - private Map _configs; + private final ScheduledExecutorService _eventExecutor = Executors.newScheduledThreadPool(1, new NamedThreadFactory("EventChecker")); - private StatsCollector _statsCollector; + private final Map _configs; - private Map _availableIdsMap; + private final StatsCollector _statsCollector; + + private final Map _availableIdsMap; + + private Adapters _userAuthenticators; private String _hashKey = null; - public ManagementServerImpl() { + protected ManagementServerImpl() { + ComponentLocator locator = ComponentLocator.getLocator(Name); + _configDao = locator.getDao(ConfigurationDao.class); + _routerDao = locator.getDao(DomainRouterDao.class); + _routerJoinDao = locator.getDao(DomainRouterJoinDao.class); + _eventDao = locator.getDao(EventDao.class); + _eventJoinDao = locator.getDao(EventJoinDao.class); + _dcDao = locator.getDao(DataCenterDao.class); + _vlanDao = locator.getDao(VlanDao.class); + _accountVlanMapDao = locator.getDao(AccountVlanMapDao.class); + _podVlanMapDao = locator.getDao(PodVlanMapDao.class); + _hostDao = locator.getDao(HostDao.class); + _detailsDao = locator.getDao(HostDetailsDao.class); + _hostPodDao = locator.getDao(HostPodDao.class); + _jobDao = locator.getDao(AsyncJobDao.class); + _clusterDao = locator.getDao(ClusterDao.class); + _nicDao = locator.getDao(NicDao.class); + _networkDao = locator.getDao(NetworkDao.class); + _loadbalancerDao = locator.getDao(LoadBalancerDao.class); + + _accountMgr = locator.getManager(AccountManager.class); + _agentMgr = locator.getManager(AgentManager.class); + _alertMgr = locator.getManager(AlertManager.class); + _consoleProxyMgr = locator.getManager(ConsoleProxyManager.class); + _secStorageVmMgr = locator.getManager(SecondaryStorageVmManager.class); + _swiftMgr = locator.getManager(SwiftManager.class); + _s3Mgr = locator.getManager(S3Manager.class); + _storageMgr = locator.getManager(StorageManager.class); + _publicIpAddressDao = locator.getDao(IPAddressDao.class); + _consoleProxyDao = locator.getDao(ConsoleProxyDao.class); + _secStorageVmDao = locator.getDao(SecondaryStorageVmDao.class); + _userDao = locator.getDao(UserDao.class); + _userVmDao = locator.getDao(UserVmDao.class); + _offeringsDao = locator.getDao(ServiceOfferingDao.class); + _diskOfferingDao = locator.getDao(DiskOfferingDao.class); + _templateDao = locator.getDao(VMTemplateDao.class); + _domainDao = locator.getDao(DomainDao.class); + _accountDao = locator.getDao(AccountDao.class); + _alertDao = locator.getDao(AlertDao.class); + _capacityDao = locator.getDao(CapacityDao.class); + _guestOSDao = locator.getDao(GuestOSDao.class); + _guestOSCategoryDao = locator.getDao(GuestOSCategoryDao.class); + _poolDao = locator.getDao(StoragePoolDao.class); + _vmGroupDao = locator.getDao(InstanceGroupDao.class); + _vmGroupJoinDao = locator.getDao(InstanceGroupJoinDao.class); + _uploadDao = locator.getDao(UploadDao.class); + _configs = _configDao.getConfiguration(); + _vmInstanceDao = locator.getDao(VMInstanceDao.class); + _volumeDao = locator.getDao(VolumeDao.class); + _asyncMgr = locator.getManager(AsyncJobManager.class); + _uploadMonitor = locator.getManager(UploadMonitor.class); + _sshKeyPairDao = locator.getDao(SSHKeyPairDao.class); + _itMgr = locator.getManager(VirtualMachineManager.class); + _ksMgr = locator.getManager(KeystoreManager.class); + _resourceMgr = locator.getManager(ResourceManager.class); + _configMgr = locator.getManager(ConfigurationManager.class); + _resourceTagDao = locator.getDao(ResourceTagDao.class); + + _hypervisorCapabilitiesDao = locator.getDao(HypervisorCapabilitiesDao.class); + + _hostAllocators = locator.getAdapters(HostAllocator.class); + if (_hostAllocators == null || !_hostAllocators.isSet()) { + s_logger.error("Unable to find HostAllocators"); } @PostConstruct @@ -358,6 +435,11 @@ public class ManagementServerImpl implements ManagementServer { for (String id : availableIds) { _availableIdsMap.put(id, true); } + + _userAuthenticators = locator.getAdapters(UserAuthenticator.class); + if (_userAuthenticators == null || !_userAuthenticators.isSet()) { + s_logger.error("Unable to find an user authenticator."); + } } public void startup() { @@ -426,8 +508,10 @@ public class ManagementServerImpl implements ManagementServer { String keyword = cmd.getKeyword(); if (domainId != null) { // for domainId != null - // right now, we made the decision to only list zones associated with this domain - dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private zones + // right now, we made the decision to only list zones associated + // with this domain + dcs = _dcDao.findZonesByDomainId(domainId, keyword); // private + // zones } else if ((account == null || account.getType() == Account.ACCOUNT_TYPE_ADMIN)) { if (keyword != null) { dcs = _dcDao.findByKeyword(keyword); @@ -435,7 +519,8 @@ public class ManagementServerImpl implements ManagementServer { dcs = _dcDao.listAll(); // all zones } } else if (account.getType() == Account.ACCOUNT_TYPE_NORMAL) { - // it was decided to return all zones for the user's domain, and everything above till root + // it was decided to return all zones for the user's domain, and + // everything above till root // list all zones belonging to this domain, and all of its parents // check the parent, if not null, add zones for that parent to list dcs = new ArrayList(); @@ -454,7 +539,8 @@ public class ManagementServerImpl implements ManagementServer { dcs.addAll(_dcDao.listPublicZones(keyword)); removeDisabledZones = true; } else if (account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { - // it was decided to return all zones for the domain admin, and everything above till root + // it was decided to return all zones for the domain admin, and + // everything above till root dcs = new ArrayList(); DomainVO domainRecord = _domainDao.findById(account.getDomainId()); // this covers path till root @@ -471,7 +557,8 @@ public class ManagementServerImpl implements ManagementServer { } // this covers till leaf if (domainRecord != null) { - // find all children for this domain based on a like search by path + // find all children for this domain based on a like search by + // path List allChildDomains = _domainDao.findAllChildren(domainRecord.getPath(), domainRecord.getId()); List allChildDomainIds = new ArrayList(); // create list of domainIds for search @@ -544,11 +631,14 @@ public class ManagementServerImpl implements ManagementServer { throw new InvalidParameterValueException("privatePort is an invalid value"); } - // s_logger.debug("Checking if " + privateIp + " is a valid private IP address. Guest IP address is: " + + // s_logger.debug("Checking if " + privateIp + + // " is a valid private IP address. Guest IP address is: " + // _configs.get("guest.ip.network")); // - // if (!NetUtils.isValidPrivateIp(privateIp, _configs.get("guest.ip.network"))) { - // throw new InvalidParameterValueException("Invalid private ip address"); + // if (!NetUtils.isValidPrivateIp(privateIp, + // _configs.get("guest.ip.network"))) { + // throw new + // InvalidParameterValueException("Invalid private ip address"); // } if (!NetUtils.isValidProto(proto)) { throw new InvalidParameterValueException("Invalid protocol"); @@ -597,7 +687,8 @@ public class ManagementServerImpl implements ManagementServer { return cal.getTime(); } - // This method is used for permissions check for both disk and service offerings + // This method is used for permissions check for both disk and service + // offerings private boolean isPermissible(Long accountDomainId, Long offeringDomainId) { if (accountDomainId == offeringDomainId) { @@ -628,11 +719,13 @@ public class ManagementServerImpl implements ManagementServer { public List searchForServiceOfferings(ListServiceOfferingsCmd cmd) { // Note - // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way -// till + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till // root Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); isAscending = (isAscending == null ? true : isAscending); @@ -653,16 +746,20 @@ public class ManagementServerImpl implements ManagementServer { } // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the so associated with this domain + // if a domainId is provided, we just return the so associated with this + // domain if (domainId != null && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { - // check if the user's domain == so's domain || user's domain is a child of so's domain + // check if the user's domain == so's domain || user's domain is a + // child of so's domain if (!isPermissible(caller.getDomainId(), domainId)) { - throw new PermissionDeniedException("The account:" + caller.getAccountName() + " does not fall in the same domain hierarchy as the service offering"); + throw new PermissionDeniedException("The account:" + caller.getAccountName() + + " does not fall in the same domain hierarchy as the service offering"); } } // For non-root users - if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if ((caller.getType() == Account.ACCOUNT_TYPE_NORMAL || caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { if (isSystem) { throw new InvalidParameterValueException("Only root admins can access system's offering"); } @@ -693,8 +790,10 @@ public class ManagementServerImpl implements ManagementServer { ServiceOfferingVO offering = _offeringsDao.findByIdIncludingRemoved(vmInstance.getServiceOfferingId()); sc.addAnd("id", SearchCriteria.Op.NEQ, offering.getId()); - // Only return offerings with the same Guest IP type and storage pool preference - // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, offering.getGuestIpType()); + // Only return offerings with the same Guest IP type and storage + // pool preference + // sc.addAnd("guestIpType", SearchCriteria.Op.EQ, + // offering.getGuestIpType()); sc.addAnd("useLocalStorage", SearchCriteria.Op.EQ, offering.getUseLocalStorage()); } if (id != null) { @@ -723,10 +822,12 @@ public class ManagementServerImpl implements ManagementServer { } - private List searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, Filter searchFilter) { + private List searchServiceOfferingsInternal(Account caller, Object name, Object id, Long vmId, Object keyword, + Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user -// or + // it was decided to return all offerings for the user's domain, and + // everything above till root (for normal user + // or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -817,7 +918,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForClusters(ListClustersCmd cmd) { + public Pair, Integer> searchForClusters(ListClustersCmd cmd) { Filter searchFilter = new Filter(ClusterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _clusterDao.createSearchCriteria(); @@ -867,25 +968,10 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.SC, ssc); } - return _clusterDao.search(sc, searchFilter); + Pair, Integer> result = _clusterDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } - @Override - public List searchForServers(ListHostsCmd cmd) { - - Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); - Object name = cmd.getHostName(); - Object type = cmd.getType(); - Object state = cmd.getState(); - Object pod = cmd.getPodId(); - Object cluster = cmd.getClusterId(); - Object id = cmd.getId(); - Object keyword = cmd.getKeyword(); - Object resourceState = cmd.getResourceState(); - Object haHosts = cmd.getHaHost(); - - return searchForServers(cmd.getStartIndex(), cmd.getPageSizeVal(), name, type, state, zoneId, pod, cluster, id, keyword, resourceState, haHosts); - } @Override public Pair, List> listHostsForMigrationOfVM(Long vmId, Long startIndex, Long pageSize) { @@ -914,8 +1000,8 @@ public class ManagementServerImpl implements ManagementServer { throw ex; } - if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) && !vm.getHypervisorType().equals(HypervisorType.KVM) - && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { + if (!vm.getHypervisorType().equals(HypervisorType.XenServer) && !vm.getHypervisorType().equals(HypervisorType.VMware) + && !vm.getHypervisorType().equals(HypervisorType.KVM) && !vm.getHypervisorType().equals(HypervisorType.Ovm)) { if (s_logger.isDebugEnabled()) { s_logger.debug(vm + " is not XenServer/VMware/KVM/OVM, cannot migrate this VM."); } @@ -935,7 +1021,8 @@ public class ManagementServerImpl implements ManagementServer { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the host with id: " + srcHostId + " of this VM:" + vm); } - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find the host (with specified id) of VM with specified id"); + InvalidParameterValueException ex = new InvalidParameterValueException( + "Unable to find the host (with specified id) of VM with specified id"); ex.addProxyObject(srcHost, srcHostId, "hostId"); ex.addProxyObject(vm, vmId, "vmId"); throw ex; @@ -946,7 +1033,8 @@ public class ManagementServerImpl implements ManagementServer { s_logger.debug("Searching for all hosts in cluster: " + cluster + " for migrating VM " + vm); } - List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, null); + List allHostsInCluster = searchForServers(startIndex, pageSize, null, hostType, null, null, null, cluster, null, null, null, + null); // filter out the current host allHostsInCluster.remove(srcHost); @@ -984,8 +1072,8 @@ public class ManagementServerImpl implements ManagementServer { return new Pair, List>(allHostsInCluster, suitableHosts); } - private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, Object cluster, Object id, Object keyword, - Object resourceState, Object haHosts) { + private List searchForServers(Long startIndex, Long pageSize, Object name, Object type, Object state, Object zone, Object pod, + Object cluster, Object id, Object keyword, Object resourceState, Object haHosts) { Filter searchFilter = new Filter(HostVO.class, "id", Boolean.TRUE, startIndex, pageSize); SearchBuilder sb = _hostDao.createSearchBuilder(); @@ -1002,7 +1090,7 @@ public class ManagementServerImpl implements ManagementServer { SearchBuilder hostTagSearch = null; if (haHosts != null && haTag != null && !haTag.isEmpty()) { hostTagSearch = _hostTagsDao.createSearchBuilder(); - if ((Boolean)haHosts) { + if ((Boolean) haHosts) { hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.EQ); } else { hostTagSearch.and().op("tag", hostTagSearch.entity().getTag(), SearchCriteria.Op.NEQ); @@ -1059,7 +1147,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForPods(ListPodsByCmd cmd) { + public Pair, Integer> searchForPods(ListPodsByCmd cmd) { Filter searchFilter = new Filter(HostPodVO.class, "dataCenterId", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _hostPodDao.createSearchCriteria(); @@ -1095,11 +1183,12 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("allocationState", SearchCriteria.Op.EQ, allocationState); } - return _hostPodDao.search(sc, searchFilter); + Pair, Integer> result = _hostPodDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForVlans(ListVlanIpRangesCmd cmd) { + public Pair, Integer> searchForVlans(ListVlanIpRangesCmd cmd) { // If an account name and domain ID are specified, look up the account String accountName = cmd.getAccountName(); Long domainId = cmd.getDomainId(); @@ -1116,8 +1205,10 @@ public class ManagementServerImpl implements ManagementServer { } Account account = _accountDao.findActiveAccount(accountName, domainId); if (account == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + " in specified domain"); - // Since we don't have a DomainVO object here, we directly set tablename to "domain". + InvalidParameterValueException ex = new InvalidParameterValueException("Unable to find account " + accountName + + " in specified domain"); + // Since we don't have a DomainVO object here, we directly set + // tablename to "domain". String tablename = "domain"; ex.addProxyObject(tablename, domainId, "domainId"); throw ex; @@ -1165,7 +1256,8 @@ public class ManagementServerImpl implements ManagementServer { if (accountId != null) { SearchBuilder accountVlanMapSearch = _accountVlanMapDao.createSearchBuilder(); accountVlanMapSearch.and("accountId", accountVlanMapSearch.entity().getAccountId(), SearchCriteria.Op.EQ); - sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), JoinBuilder.JoinType.INNER); + sb.join("accountVlanMapSearch", accountVlanMapSearch, sb.entity().getId(), accountVlanMapSearch.entity().getVlanDbId(), + JoinBuilder.JoinType.INNER); } if (podId != null) { @@ -1213,11 +1305,12 @@ public class ManagementServerImpl implements ManagementServer { } } - return _vlanDao.search(sc, searchFilter); + Pair, Integer> result = _vlanDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForConfigurations(ListCfgsByCmd cmd) { + public Pair, Integer> searchForConfigurations(ListCfgsByCmd cmd) { Filter searchFilter = new Filter(ConfigurationVO.class, "name", true, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _configDao.createSearchCriteria(); @@ -1248,7 +1341,8 @@ public class ManagementServerImpl implements ManagementServer { // hidden configurations are not displayed using the search API sc.addAnd("category", SearchCriteria.Op.NEQ, "Hidden"); - return _configDao.search(sc, searchFilter); + Pair, Integer> result = _configDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -1257,10 +1351,18 @@ public class ManagementServerImpl implements ManagementServer { Account caller = UserContext.current().getCaller(); Map tags = cmd.getTags(); - boolean listAll = (caller.getType() != Account.ACCOUNT_TYPE_NORMAL && (isoFilter != null && isoFilter == TemplateFilter.all)); + boolean listAll = false; + if (isoFilter != null && isoFilter == TemplateFilter.all) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { + throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only"); + } + listAll = true; + } List permittedAccountIds = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, + domainIdRecursiveListProject, listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); @@ -1269,8 +1371,9 @@ public class ManagementServerImpl implements ManagementServer { } HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, - cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + return listTemplates(cmd.getId(), cmd.getIsoName(), cmd.getKeyword(), isoFilter, true, cmd.isBootable(), cmd.getPageSizeVal(), + cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, true, cmd.listInReadyState(), permittedAccounts, caller, + listProjectResourcesCriteria, tags); } @Override @@ -1280,10 +1383,19 @@ public class ManagementServerImpl implements ManagementServer { Map tags = cmd.getTags(); Account caller = UserContext.current().getCaller(); - boolean listAll = (caller.getType() != Account.ACCOUNT_TYPE_NORMAL && (templateFilter != null && templateFilter == TemplateFilter.all)); + boolean listAll = false; + if (templateFilter != null && templateFilter == TemplateFilter.all) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { + throw new InvalidParameterValueException("Filter " + TemplateFilter.all + " can be specified by admin only"); + } + listAll = true; + } + List permittedAccountIds = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, listAll, false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccountIds, domainIdRecursiveListProject, + listAll, false); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); List permittedAccounts = new ArrayList(); for (Long accountId : permittedAccountIds) { @@ -1293,15 +1405,13 @@ public class ManagementServerImpl implements ManagementServer { boolean showDomr = ((templateFilter != TemplateFilter.selfexecutable) && (templateFilter != TemplateFilter.featured)); HypervisorType hypervisorType = HypervisorType.getType(cmd.getHypervisor()); - return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, - cmd.getPageSizeVal(), cmd.getStartIndex(), cmd.getZoneId(), hypervisorType, showDomr, - cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); + return listTemplates(id, cmd.getTemplateName(), cmd.getKeyword(), templateFilter, false, null, cmd.getPageSizeVal(), cmd.getStartIndex(), + cmd.getZoneId(), hypervisorType, showDomr, cmd.listInReadyState(), permittedAccounts, caller, listProjectResourcesCriteria, tags); } - private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, - boolean isIso, Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, - boolean showDomr, boolean onlyReady, List permittedAccounts, Account caller, - ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + private Set> listTemplates(Long templateId, String name, String keyword, TemplateFilter templateFilter, boolean isIso, + Boolean bootable, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean showDomr, boolean onlyReady, + List permittedAccounts, Account caller, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { VMTemplateVO template = null; if (templateId != null) { @@ -1317,7 +1427,8 @@ public class ManagementServerImpl implements ManagementServer { }// If ISO not requested then it shouldn't be an ISO. if (!isIso && template.getFormat() == ImageFormat.ISO) { s_logger.error("Incorrect format of the template id " + templateId); - InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + " of the specified template id"); + InvalidParameterValueException ex = new InvalidParameterValueException("Incorrect format " + template.getFormat() + + " of the specified template id"); ex.addProxyObject(template, templateId, "templateId"); throw ex; } @@ -1337,14 +1448,12 @@ public class ManagementServerImpl implements ManagementServer { Set> templateZonePairSet = new HashSet>(); if (_swiftMgr.isSwiftEnabled()) { if (template == null) { - templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, - hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, - permittedAccounts, caller, tags); + templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, tags); Set> templateZonePairSet2 = new HashSet>(); - templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, - bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, - permittedAccounts, caller, listProjectResourcesCriteria, tags); - + templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); + for (Pair tmpltPair : templateZonePairSet2) { if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { templateZonePairSet.add(tmpltPair); @@ -1359,11 +1468,33 @@ public class ManagementServerImpl implements ManagementServer { } templateZonePairSet.add(new Pair(template.getId(), zoneId)); } - } else { + } else if (_s3Mgr.isS3Enabled()) { if (template == null) { - templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, + templateZonePairSet = _templateDao.searchSwiftTemplates(name, keyword, templateFilter, isIso, + hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, + permittedAccounts, caller, tags); + Set> templateZonePairSet2 = new HashSet>(); + templateZonePairSet2 = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); + + for (Pair tmpltPair : templateZonePairSet2) { + if (!templateZonePairSet.contains(new Pair(tmpltPair.first(), -1L))) { + templateZonePairSet.add(tmpltPair); + } + } + } else { + // if template is not public, perform permission check here + if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + Account owner = _accountMgr.getAccount(template.getAccountId()); + _accountMgr.checkAccess(caller, null, true, owner); + } + templateZonePairSet.add(new Pair(template.getId(), zoneId)); + } + } else { + if (template == null) { + templateZonePairSet = _templateDao.searchTemplates(name, keyword, templateFilter, isIso, hypers, bootable, domain, pageSize, + startIndex, zoneId, hyperType, onlyReady, showDomr, permittedAccounts, caller, listProjectResourcesCriteria, tags); } else { // if template is not public, perform permission check here if (!template.isPublicTemplate() && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { @@ -1387,7 +1518,7 @@ public class ManagementServerImpl implements ManagementServer { return updateTemplateOrIso(cmd); } - private VMTemplateVO updateTemplateOrIso(UpdateTemplateOrIsoCmd cmd) { + private VMTemplateVO updateTemplateOrIso(BaseUpdateTemplateOrIsoCmd cmd) { Long id = cmd.getId(); String name = cmd.getTemplateName(); String displayText = cmd.getDisplayText(); @@ -1416,7 +1547,8 @@ public class ManagementServerImpl implements ManagementServer { // do a permission check _accountMgr.checkAccess(account, AccessType.ModifyEntry, true, template); - boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null && bootable == null && sortKey == null); + boolean updateNeeded = !(name == null && displayText == null && format == null && guestOSId == null && passwordEnabled == null + && bootable == null && sortKey == null); if (!updateNeeded) { return template; } @@ -1440,7 +1572,8 @@ public class ManagementServerImpl implements ManagementServer { try { imageFormat = ImageFormat.valueOf(format.toUpperCase()); } catch (IllegalArgumentException e) { - throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + EnumUtils.listValues(ImageFormat.values())); + throw new InvalidParameterValueException("Image format: " + format + " is incorrect. Supported formats are " + + EnumUtils.listValues(ImageFormat.values())); } template.setFormat(imageFormat); @@ -1469,233 +1602,11 @@ public class ManagementServerImpl implements ManagementServer { return _templateDao.findById(id); } - @Override - public List searchForEvents(ListEventsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - Long id = cmd.getId(); - String type = cmd.getType(); - String level = cmd.getLevel(); - Date startDate = cmd.getStartDate(); - Date endDate = cmd.getEndDate(); - String keyword = cmd.getKeyword(); - Integer entryTime = cmd.getEntryTime(); - Integer duration = cmd.getDuration(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(EventVO.class, "createDate", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _eventDao.createSearchBuilder(); - - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - SearchBuilder accountSearch = _accountDao.createSearchBuilder(); - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("accountType", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - } - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("levelL", sb.entity().getLevel(), SearchCriteria.Op.LIKE); - sb.and("levelEQ", sb.entity().getLevel(), SearchCriteria.Op.EQ); - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("createDateB", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); - sb.and("createDateG", sb.entity().getCreateDate(), SearchCriteria.Op.GTEQ); - sb.and("createDateL", sb.entity().getCreateDate(), SearchCriteria.Op.LTEQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); - sb.and("startId", sb.entity().getStartId(), SearchCriteria.Op.EQ); - sb.and("createDate", sb.entity().getCreateDate(), SearchCriteria.Op.BETWEEN); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "accountType", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (keyword != null) { - SearchCriteria ssc = _eventDao.createSearchCriteria(); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("description", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("level", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("level", SearchCriteria.Op.SC, ssc); - } - - if (level != null) { - sc.setParameters("levelEQ", level); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (startDate != null && endDate != null) { - sc.setParameters("createDateB", startDate, endDate); - } else if (startDate != null) { - sc.setParameters("createDateG", startDate); - } else if (endDate != null) { - sc.setParameters("createDateL", endDate); - } - - if ((entryTime != null) && (duration != null)) { - if (entryTime <= duration) { - throw new InvalidParameterValueException("Entry time must be greater than duration"); - } - Calendar calMin = Calendar.getInstance(); - Calendar calMax = Calendar.getInstance(); - calMin.add(Calendar.SECOND, -entryTime); - calMax.add(Calendar.SECOND, -duration); - Date minTime = calMin.getTime(); - Date maxTime = calMax.getTime(); - - sc.setParameters("state", com.cloud.event.Event.State.Completed); - sc.setParameters("startId", 0); - sc.setParameters("createDate", minTime, maxTime); - List startedEvents = _eventDao.searchAllEvents(sc, searchFilter); - List pendingEvents = new ArrayList(); - for (EventVO event : startedEvents) { - EventVO completedEvent = _eventDao.findCompletedEvent(event.getId()); - if (completedEvent == null) { - pendingEvents.add(event); - } - } - return pendingEvents; - } else { - return _eventDao.searchAllEvents(sc, searchFilter); - } - } @Override - public List searchForRouters(ListRoutersCmd cmd) { - Long id = cmd.getId(); - String name = cmd.getRouterName(); - String state = cmd.getState(); - Long zone = cmd.getZoneId(); - Long pod = cmd.getPodId(); - Long hostId = cmd.getHostId(); - String keyword = cmd.getKeyword(); - Long networkId = cmd.getNetworkId(); - Long vpcId = cmd.getVpcId(); - Boolean forVpc = cmd.getForVpc(); - - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(DomainRouterVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _routerDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("name", sb.entity().getHostName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("accountId", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("dataCenterId", sb.entity().getDataCenterIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("hostId", sb.entity().getHostId(), SearchCriteria.Op.EQ); - sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); - - if (forVpc != null) { - if (forVpc) { - sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NNULL); - } else { - sb.and("forVpc", sb.entity().getVpcId(), SearchCriteria.Op.NULL); - } - } - - if (networkId != null) { - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), SearchCriteria.Op.EQ); - SearchBuilder networkSearch = _networkDao.createSearchBuilder(); - networkSearch.and("networkId", networkSearch.entity().getId(), SearchCriteria.Op.EQ); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity().getNetworkId(), networkSearch.entity().getId(), JoinBuilder.JoinType.INNER); - - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch.entity().getInstanceId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (keyword != null) { - SearchCriteria ssc = _routerDao.createSearchCriteria(); - ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("hostName", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (zone != null) { - sc.setParameters("dataCenterId", zone); - } - - if (pod != null) { - sc.setParameters("podId", pod); - } - - if (hostId != null) { - sc.setParameters("hostId", hostId); - } - - if (networkId != null) { - sc.setJoinParameters("nicSearch", "networkId", networkId); - } - - if (vpcId != null) { - sc.setParameters("vpcId", vpcId); - } - - return _routerDao.search(sc, searchFilter); - } - - @Override - public List searchForIPAddresses(ListPublicIpAddressesCmd cmd) { + public Pair, Integer> searchForIPAddresses(ListPublicIpAddressesCmd cmd) { Object keyword = cmd.getKeyword(); Long physicalNetworkId = cmd.getPhysicalNetworkId(); Long associatedNetworkId = cmd.getAssociatedNetworkId(); @@ -1710,7 +1621,6 @@ public class ManagementServerImpl implements ManagementServer { Long vpcId = cmd.getVpcId(); Map tags = cmd.getTags(); - Boolean isAllocated = cmd.isAllocatedOnly(); if (isAllocated == null) { isAllocated = Boolean.TRUE; @@ -1725,10 +1635,10 @@ public class ManagementServerImpl implements ManagementServer { if (isAllocated) { Account caller = UserContext.current().getCaller(); - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), - permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, cmd.getId(), cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, + domainIdRecursiveListProject, cmd.listAll(), false); domainId = domainIdRecursiveListProject.first(); isRecursive = domainIdRecursiveListProject.second(); listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -1757,7 +1667,7 @@ public class ManagementServerImpl implements ManagementServer { if (tags != null && !tags.isEmpty()) { SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { + for (int count = 0; count < tags.size(); count++) { tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); tagSearch.cp(); @@ -1767,7 +1677,6 @@ public class ManagementServerImpl implements ManagementServer { sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); } - SearchBuilder vlanSearch = _vlanDao.createSearchBuilder(); vlanSearch.and("vlanType", vlanSearch.entity().getVlanType(), SearchCriteria.Op.EQ); sb.join("vlanSearch", vlanSearch, sb.entity().getVlanId(), vlanSearch.entity().getId(), JoinBuilder.JoinType.INNER); @@ -1842,11 +1751,12 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("associatedNetworkIdEq", associatedNetworkId); } - return _publicIpAddressDao.search(sc, searchFilter); + Pair, Integer> result = _publicIpAddressDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List listGuestOSByCriteria(ListGuestOsCmd cmd) { + public Pair, Integer> listGuestOSByCriteria(ListGuestOsCmd cmd) { Filter searchFilter = new Filter(GuestOSVO.class, "displayName", true, cmd.getStartIndex(), cmd.getPageSizeVal()); Long id = cmd.getId(); Long osCategoryId = cmd.getOsCategoryId(); @@ -1871,11 +1781,12 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } - return _guestOSDao.search(sc, searchFilter); + Pair, Integer> result = _guestOSDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd) { + public Pair, Integer> listGuestOSCategoriesByCriteria(ListGuestOsCategoriesCmd cmd) { Filter searchFilter = new Filter(GuestOSCategoryVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); Long id = cmd.getId(); String name = cmd.getName(); @@ -1895,7 +1806,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); } - return _guestOSCategoryDao.search(sc, searchFilter); + Pair, Integer> result = _guestOSCategoryDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -1909,7 +1821,8 @@ public class ManagementServerImpl implements ManagementServer { } @ActionEvent(eventType = EventTypes.EVENT_PROXY_STOP, eventDescription = "stopping console proxy Vm", async = true) - private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + private ConsoleProxyVO stopConsoleProxy(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, + ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -1981,7 +1894,8 @@ public class ManagementServerImpl implements ManagementServer { ex.addProxyObject(domain, domainId, "domainId"); throw ex; } else if (domain.getParent() == null && domainName != null) { - // check if domain is ROOT domain - and deny to edit it with the new name + // check if domain is ROOT domain - and deny to edit it with the new + // name throw new InvalidParameterValueException("ROOT domain can not be edited with a new name"); } @@ -1998,7 +1912,8 @@ public class ManagementServerImpl implements ManagementServer { boolean sameDomain = (domains.size() == 1 && domains.get(0).getId() == domainId); if (!domains.isEmpty() && !sameDomain) { - InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + domainName + "' since it already exists in the system"); + InvalidParameterValueException ex = new InvalidParameterValueException("Failed to update specified domain id with name '" + + domainName + "' since it already exists in the system"); ex.addProxyObject(domain, domainId, "domainId"); throw ex; } @@ -2060,7 +1975,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForAlerts(ListAlertsCmd cmd) { + public Pair, Integer> searchForAlerts(ListAlertsCmd cmd) { Filter searchFilter = new Filter(AlertVO.class, "lastSent", false, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchCriteria sc = _alertDao.createSearchCriteria(); @@ -2087,7 +2002,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("type", SearchCriteria.Op.EQ, type); } - return _alertDao.search(sc, searchFilter); + Pair, Integer> result = _alertDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -2105,13 +2021,15 @@ public class ManagementServerImpl implements ManagementServer { List summedCapacities = new ArrayList(); if (zoneId == null && podId == null) {// Group by Zone, capacity type - List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, cmd.getPageSizeVal()); + List summedCapacitiesAtZone = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 1, + cmd.getPageSizeVal()); if (summedCapacitiesAtZone != null) { summedCapacities.addAll(summedCapacitiesAtZone); } } if (podId == null) {// Group by Pod, capacity type - List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, cmd.getPageSizeVal()); + List summedCapacitiesAtPod = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 2, + cmd.getPageSizeVal()); if (summedCapacitiesAtPod != null) { summedCapacities.addAll(summedCapacitiesAtPod); } @@ -2122,7 +2040,8 @@ public class ManagementServerImpl implements ManagementServer { } // Group by Cluster, capacity type - List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, cmd.getPageSizeVal()); + List summedCapacitiesAtCluster = _capacityDao.listCapacitiesGroupedByLevelAndType(capacityType, zoneId, podId, clusterId, 3, + cmd.getPageSizeVal()); if (summedCapacitiesAtCluster != null) { summedCapacities.addAll(summedCapacitiesAtCluster); } @@ -2174,20 +2093,22 @@ public class ManagementServerImpl implements ManagementServer { } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), - capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), + capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), + capacity.getClusterId()); list.add(summedCapacity); } else { List dcList = _dcDao.listEnabledZones(); for (DataCenterVO dc : dcList) { CapacityVO capacity = _storageMgr.getSecondaryStorageUsedStats(null, dc.getId()); if (capacity.getTotalCapacity() != 0) { - capacity.setUsedPercentage((float)capacity.getUsedCapacity() / capacity.getTotalCapacity()); + capacity.setUsedPercentage((float) capacity.getUsedCapacity() / capacity.getTotalCapacity()); } else { capacity.setUsedPercentage(0); } - SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), - capacity.getPodId(), capacity.getClusterId()); + SummedCapacity summedCapacity = new SummedCapacity(capacity.getUsedCapacity(), capacity.getTotalCapacity(), + capacity.getUsedPercentage(), capacity.getCapacityType(), capacity.getDataCenterId(), capacity.getPodId(), + capacity.getClusterId()); list.add(summedCapacity); }// End of for } @@ -2214,9 +2135,8 @@ public class ManagementServerImpl implements ManagementServer { List capacities = new ArrayList(); for (SummedCapacity summedCapacity : summedCapacities) { - CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, - summedCapacity.getUsedCapacity() + summedCapacity.getReservedCapacity(), - summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); + CapacityVO capacity = new CapacityVO(null, summedCapacity.getDataCenterId(), podId, clusterId, summedCapacity.getUsedCapacity() + + summedCapacity.getReservedCapacity(), summedCapacity.getTotalCapacity(), summedCapacity.getCapacityType()); if (summedCapacity.getCapacityType() == Capacity.CAPACITY_TYPE_CPU) { capacity.setTotalCapacity((long) (summedCapacity.getTotalCapacity() * ApiDBUtils.getCpuOverprovisioningFactor())); @@ -2224,7 +2144,8 @@ public class ManagementServerImpl implements ManagementServer { capacities.add(capacity); } - // op_host_Capacity contains only allocated stats and the real time stats are stored "in memory". + // op_host_Capacity contains only allocated stats and the real time + // stats are stored "in memory". // Show Sec. Storage only when the api is invoked for the zone layer. List dcList = new ArrayList(); if (zoneId == null && podId == null && clusterId == null) { @@ -2232,9 +2153,9 @@ public class ManagementServerImpl implements ManagementServer { } else if (zoneId != null) { dcList.add(ApiDBUtils.findZoneById(zoneId)); } else { - if (clusterId != null){ + if (clusterId != null) { zoneId = ApiDBUtils.findClusterById(clusterId).getDataCenterId(); - }else{ + } else { zoneId = ApiDBUtils.findPodById(podId).getDataCenterId(); } if (capacityType == null || capacityType == Capacity.CAPACITY_TYPE_STORAGE) { @@ -2263,12 +2184,14 @@ public class ManagementServerImpl implements ManagementServer { } public static boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); + return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) + || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } private List searchDiskOfferingsInternal(Account account, Object name, Object id, Object keyword, Filter searchFilter) { - // it was decided to return all offerings for the user's domain, and everything above till root (for normal user -// or + // it was decided to return all offerings for the user's domain, and + // everything above till root (for normal user + // or // domain admin) // list all offerings belonging to this domain, and all of its parents // check the parent, if not null, add offerings for that parent to list @@ -2333,11 +2256,13 @@ public class ManagementServerImpl implements ManagementServer { @Override public List searchForDiskOfferings(ListDiskOfferingsCmd cmd) { // Note - // The list method for offerings is being modified in accordance with discussion with Will/Kevin + // The list method for offerings is being modified in accordance with + // discussion with Will/Kevin // For now, we will be listing the following based on the usertype // 1. For root, we will list all offerings - // 2. For domainAdmin and regular users, we will list everything in their domains+parent domains ... all the way -// till + // 2. For domainAdmin and regular users, we will list everything in + // their domains+parent domains ... all the way + // till // root Boolean isAscending = Boolean.parseBoolean(_configDao.getValue("sortkey.algorithm")); @@ -2345,31 +2270,38 @@ public class ManagementServerImpl implements ManagementServer { Filter searchFilter = new Filter(DiskOfferingVO.class, "sortKey", isAscending, cmd.getStartIndex(), cmd.getPageSizeVal()); SearchBuilder sb = _diskOfferingDao.createSearchBuilder(); - // SearchBuilder and SearchCriteria are now flexible so that the search builder can be built with all possible - // search terms and only those with criteria can be set. The proper SQL should be generated as a result. + // SearchBuilder and SearchCriteria are now flexible so that the search + // builder can be built with all possible + // search terms and only those with criteria can be set. The proper SQL + // should be generated as a result. Account account = UserContext.current().getCaller(); Object name = cmd.getDiskOfferingName(); Object id = cmd.getId(); Object keyword = cmd.getKeyword(); Long domainId = cmd.getDomainId(); // Keeping this logic consistent with domain specific zones - // if a domainId is provided, we just return the disk offering associated with this domain + // if a domainId is provided, we just return the disk offering + // associated with this domain if (domainId != null) { if (account.getType() == Account.ACCOUNT_TYPE_ADMIN) { - return _diskOfferingDao.listByDomainId(domainId);// no perm check + return _diskOfferingDao.listByDomainId(domainId);// no perm + // check } else { - // check if the user's domain == do's domain || user's domain is a child of so's domain + // check if the user's domain == do's domain || user's domain is + // a child of so's domain if (isPermissible(account.getDomainId(), domainId)) { // perm check succeeded return _diskOfferingDao.listByDomainId(domainId); } else { - throw new PermissionDeniedException("The account:" + account.getAccountName() + " does not fall in the same domain hierarchy as the disk offering"); + throw new PermissionDeniedException("The account:" + account.getAccountName() + + " does not fall in the same domain hierarchy as the disk offering"); } } } // For non-root users - if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + if ((account.getType() == Account.ACCOUNT_TYPE_NORMAL || account.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) + || account.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { return searchDiskOfferingsInternal(account, name, id, keyword, searchFilter); } @@ -2378,12 +2310,16 @@ public class ManagementServerImpl implements ManagementServer { sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); sb.and("removed", sb.entity().getRemoved(), SearchCriteria.Op.NULL); - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... /* - * sb.addAnd("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); if (domainId != null) { - * SearchBuilder domainSearch = _domainDao.createSearchBuilder(); domainSearch.addAnd("path", - * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); sb.join("domainSearch", domainSearch, - * sb.entity().getDomainId(), domainSearch.entity().getId()); } + * sb.addAnd("domainId", sb.entity().getDomainId(), + * SearchCriteria.Op.EQ); if (domainId != null) { + * SearchBuilder domainSearch = + * _domainDao.createSearchBuilder(); domainSearch.addAnd("path", + * domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); + * sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), + * domainSearch.entity().getId()); } */ SearchCriteria sc = sb.create(); @@ -2403,19 +2339,21 @@ public class ManagementServerImpl implements ManagementServer { sc.setParameters("id", id); } - // FIXME: disk offerings should search back up the hierarchy for available disk offerings... + // FIXME: disk offerings should search back up the hierarchy for + // available disk offerings... /* - * if (domainId != null) { sc.setParameters("domainId", domainId); // //DomainVO domain = - * _domainDao.findById((Long)domainId); // // I want to join on user_vm.domain_id = domain.id where domain.path - * like - * 'foo%' //sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); // } + * if (domainId != null) { sc.setParameters("domainId", domainId); // + * //DomainVO domain = _domainDao.findById((Long)domainId); // // I want + * to join on user_vm.domain_id = domain.id where domain.path like + * 'foo%' //sc.setJoinParameters("domainSearch", "path", + * domain.getPath() + "%"); // } */ return _diskOfferingDao.search(sc, searchFilter); } @Override - public String[] getApiConfig() { + public String[] getPropertiesFiles() { return new String[] { "commands.properties" }; } @@ -2454,7 +2392,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForStoragePools(ListStoragePoolsCmd cmd) { + public Pair, Integer> searchForStoragePools(ListStoragePoolsCmd cmd) { Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), cmd.getPageSizeVal()); @@ -2467,11 +2405,12 @@ public class ManagementServerImpl implements ManagementServer { c.addCriteria(Criteria.PODID, cmd.getPodId()); c.addCriteria(Criteria.DATACENTERID, zoneId); - return searchForStoragePools(c); + Pair, Integer> result = searchForStoragePools(c); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForStoragePools(Criteria c) { + public Pair, Integer> searchForStoragePools(Criteria c) { Filter searchFilter = new Filter(StoragePoolVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); SearchCriteria sc = _poolDao.createSearchCriteria(); @@ -2519,82 +2458,9 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("clusterId", SearchCriteria.Op.EQ, cluster); } - return _poolDao.search(sc, searchFilter); - } - - @Override - public List searchForAsyncJobs(ListAsyncJobsCmd cmd) { - - Account caller = UserContext.current().getCaller(); - - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), null, permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(AsyncJobVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - SearchBuilder sb = _jobDao.createSearchBuilder(); - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - SearchBuilder accountSearch = null; - boolean accountJoinIsDone = false; - if (permittedAccounts.isEmpty() && domainId != null) { - accountSearch = _accountDao.createSearchBuilder(); - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("domainId", domainSearch.entity().getId(), SearchCriteria.Op.EQ); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - accountJoinIsDone = true; - accountSearch.join("domainSearch", domainSearch, accountSearch.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - if (accountSearch == null) { - accountSearch = _accountDao.createSearchBuilder(); - } - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - accountSearch.and("type", accountSearch.entity().getType(), SearchCriteria.Op.NEQ); + return _poolDao.searchAndCount(sc, searchFilter); } - if (!accountJoinIsDone) { - sb.join("accountSearch", accountSearch, sb.entity().getAccountId(), accountSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - } - - Object keyword = cmd.getKeyword(); - Object startDate = cmd.getStartDate(); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setJoinParameters("accountSearch", "type", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setJoinParameters("domainSearch", "domainId", domainId); - } - } - - if (keyword != null) { - sc.addAnd("cmd", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } - - if (startDate != null) { - sc.addAnd("created", SearchCriteria.Op.GTEQ, startDate); - } - - return _jobDao.search(sc, searchFilter); - } @ActionEvent(eventType = EventTypes.EVENT_SSVM_START, eventDescription = "starting secondary storage Vm", async = true) public SecondaryStorageVmVO startSecondaryStorageVm(long instanceId) { @@ -2602,7 +2468,8 @@ public class ManagementServerImpl implements ManagementServer { } @ActionEvent(eventType = EventTypes.EVENT_SSVM_STOP, eventDescription = "stopping secondary storage Vm", async = true) - private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, OperationTimedoutException, ConcurrentOperationException { + private SecondaryStorageVmVO stopSecondaryStorageVm(VMInstanceVO systemVm, boolean isForced) throws ResourceUnavailableException, + OperationTimedoutException, ConcurrentOperationException { User caller = _userDao.findById(UserContext.current().getCallerUserId()); @@ -2628,7 +2495,7 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List searchForSystemVm(ListSystemVMsCmd cmd) { + public Pair, Integer> searchForSystemVm(ListSystemVMsCmd cmd) { String type = cmd.getSystemVmType(); Long zoneId = _accountMgr.checkAccessAndSpecifyAuthority(UserContext.current().getCaller(), cmd.getZoneId()); Long id = cmd.getId(); @@ -2697,7 +2564,8 @@ public class ManagementServerImpl implements ManagementServer { sc.setJoinParameters("volumeSearch", "poolId", storageId); } - return _vmInstanceDao.search(sc, searchFilter); + Pair, Integer> result = _vmInstanceDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -2871,7 +2739,8 @@ public class ManagementServerImpl implements ManagementServer { String userPublicTemplateEnabled = _configs.get(Config.AllowPublicUserTemplates.key()); capabilities.put("securityGroupsEnabled", securityGroupsEnabled); - capabilities.put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); + capabilities + .put("userPublicTemplateEnabled", (userPublicTemplateEnabled == null || userPublicTemplateEnabled.equals("false") ? false : true)); capabilities.put("cloudStackVersion", getVersion()); capabilities.put("supportELB", supportELB); capabilities.put("projectInviteRequired", _projectMgr.projectInviteRequired()); @@ -2916,21 +2785,29 @@ public class ManagementServerImpl implements ManagementServer { if (volume.getPoolId() == null) { throw new InvalidParameterValueException("The volume doesnt belong to a storage pool so cant extract it"); } - // Extract activity only for detached volumes or for volumes whose instance is stopped + // Extract activity only for detached volumes or for volumes whose + // instance is stopped if (volume.getInstanceId() != null && ApiDBUtils.findVMInstanceById(volume.getInstanceId()).getState() != State.Stopped) { - s_logger.debug("Invalid state of the volume with ID: " + volumeId + ". It should be either detached or the VM should be in stopped state."); - PermissionDeniedException ex = new PermissionDeniedException("Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); + s_logger.debug("Invalid state of the volume with ID: " + volumeId + + ". It should be either detached or the VM should be in stopped state."); + PermissionDeniedException ex = new PermissionDeniedException( + "Invalid state of the volume with specified ID. It should be either detached or the VM should be in stopped state."); ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; } - if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont have any template dependence. + if (volume.getVolumeType() != Volume.Type.DATADISK) { // Datadisk dont + // have any + // template + // dependence. VMTemplateVO template = ApiDBUtils.findTemplateById(volume.getTemplateId()); - if (template != null) { // For ISO based volumes template = null and we allow extraction of all ISO based volumes + if (template != null) { // For ISO based volumes template = null and + // we allow extraction of all ISO based + // volumes boolean isExtractable = template.isExtractable() && template.getTemplateType() != Storage.TemplateType.SYSTEM; if (!isExtractable && account != null && account.getType() != Account.ACCOUNT_TYPE_ADMIN) { // Global -// admins are always allowed to extract + // admins are always allowed to extract PermissionDeniedException ex = new PermissionDeniedException("The volume with specified volumeId is not allowed to be extracted"); ex.addProxyObject(volume, volumeId, "volumeId"); throw ex; @@ -2945,7 +2822,8 @@ public class ManagementServerImpl implements ManagementServer { extractMode = mode.equals(Upload.Mode.FTP_UPLOAD.toString()) ? Upload.Mode.FTP_UPLOAD : Upload.Mode.HTTP_DOWNLOAD; } - // If mode is upload perform extra checks on url and also see if there is an ongoing upload on the same. + // If mode is upload perform extra checks on url and also see if there + // is an ongoing upload on the same. if (extractMode == Upload.Mode.FTP_UPLOAD) { URI uri = new URI(url); if ((uri.getScheme() == null) || (!uri.getScheme().equalsIgnoreCase("ftp"))) { @@ -2966,7 +2844,8 @@ public class ManagementServerImpl implements ManagementServer { } if (_uploadMonitor.isTypeUploadInProgress(volumeId, Upload.Type.VOLUME)) { - throw new IllegalArgumentException(volume.getName() + " upload is in progress. Please wait for some time to schedule another upload for the same"); + throw new IllegalArgumentException(volume.getName() + + " upload is in progress. Please wait for some time to schedule another upload for the same"); } } @@ -2978,14 +2857,19 @@ public class ManagementServerImpl implements ManagementServer { List extractURLList = _uploadDao.listByTypeUploadStatus(volumeId, Upload.Type.VOLUME, UploadVO.Status.DOWNLOAD_URL_CREATED); if (extractMode == Upload.Mode.HTTP_DOWNLOAD && extractURLList.size() > 0) { - return extractURLList.get(0).getId(); // If download url already exists then return + return extractURLList.get(0).getId(); // If download url already + // exists then return } else { - UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, url, extractMode); + UploadVO uploadJob = _uploadMonitor.createNewUploadEntry(sserver.getId(), volumeId, UploadVO.Status.COPY_IN_PROGRESS, Upload.Type.VOLUME, + url, extractMode); s_logger.debug("Extract Mode - " + uploadJob.getMode()); uploadJob = _uploadDao.createForUpdate(uploadJob.getId()); // Update the async Job - ExtractResponse resultObj = new ExtractResponse(volumeId, volume.getName(), accountId, UploadVO.Status.COPY_IN_PROGRESS.toString(), uploadJob.getId()); + + ExtractResponse resultObj = new ExtractResponse(ApiDBUtils.findVolumeById(volumeId).getUuid(), + volume.getName(), ApiDBUtils.findAccountById(accountId).getUuid(), UploadVO.Status.COPY_IN_PROGRESS.toString(), + uploadJob.getUuid()); resultObj.setResponseName(cmd.getCommandName()); AsyncJobExecutor asyncExecutor = BaseAsyncJobExecutor.getCurrentExecutor(); if (asyncExecutor != null) { @@ -3031,10 +2915,13 @@ public class ManagementServerImpl implements ManagementServer { uploadJob.setInstallPath(volumeLocalPath); _uploadDao.update(uploadJob.getId(), uploadJob); - if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is copied perform the actual uploading + if (extractMode == Mode.FTP_UPLOAD) { // Now that the volume is + // copied perform the actual + // uploading _uploadMonitor.extractVolume(uploadJob, sserver, volume, url, zoneId, volumeLocalPath, cmd.getStartEventId(), job.getId(), _asyncMgr); return uploadJob.getId(); - } else { // Volume is copied now make it visible under apache and create a URL. + } else { // Volume is copied now make it visible under apache and + // create a URL. _uploadMonitor.createVolumeDownloadURL(volumeId, volumeLocalPath, Upload.Type.VOLUME, zoneId, uploadJob.getId()); return uploadJob.getId(); } @@ -3087,76 +2974,7 @@ public class ManagementServerImpl implements ManagementServer { return _vmGroupDao.findById(groupId); } - @Override - public List searchForVmGroups(ListVMGroupsCmd cmd) { - Long id = cmd.getId(); - String name = cmd.getGroupName(); - String keyword = cmd.getKeyword(); - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - - Filter searchFilter = new Filter(InstanceGroupVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - SearchBuilder sb = _vmGroupDao.createSearchBuilder(); - - sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { - // if accountId isn't specified, we can do a domain match for the admin case if isRecursive is true - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - if (listProjectResourcesCriteria != null) { - if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); - } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { - sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); - } - } - - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - - SearchCriteria sc = sb.create(); - if (listProjectResourcesCriteria != null) { - sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); - } - - if (!permittedAccounts.isEmpty()) { - sc.setParameters("accountIdIN", permittedAccounts.toArray()); - } else if (domainId != null) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - if (keyword != null) { - SearchCriteria ssc = _vmGroupDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - return _vmGroupDao.search(sc, searchFilter); - } @Override public String getVersion() { @@ -3247,7 +3065,8 @@ public class ManagementServerImpl implements ManagementServer { @Override public String getHashKey() { - // although we may have race conditioning here, database transaction serialization should + // although we may have race conditioning here, database transaction + // serialization should // give us the same key if (_hashKey == null) { _hashKey = _configDao.getValueAndInitIfNotExist(Config.HashKey.key(), Config.HashKey.getCategory(), UUID.randomUUID().toString()); @@ -3290,7 +3109,8 @@ public class ManagementServerImpl implements ManagementServer { SSHKeyPairVO s = _sshKeyPairDao.findByName(owner.getAccountId(), owner.getDomainId(), cmd.getName()); if (s == null) { - InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); + InvalidParameterValueException ex = new InvalidParameterValueException("A key pair with name '" + cmd.getName() + + "' does not exist for account " + owner.getAccountName() + " in specified domain id"); ex.addProxyObject(owner, owner.getDomainId(), "domainId"); throw ex; } @@ -3299,15 +3119,17 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List listSSHKeyPairs(ListSSHKeyPairsCmd cmd) { + public Pair, Integer> listSSHKeyPairs(ListSSHKeyPairsCmd cmd) { String name = cmd.getName(); String fingerPrint = cmd.getFingerprint(); Account caller = UserContext.current().getCaller(); List permittedAccounts = new ArrayList(); - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); + Ternary domainIdRecursiveListProject = new Ternary( + cmd.getDomainId(), cmd.isRecursive(), null); + _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, + cmd.listAll(), false); Long domainId = domainIdRecursiveListProject.first(); Boolean isRecursive = domainIdRecursiveListProject.second(); ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); @@ -3326,7 +3148,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("fingerprint", SearchCriteria.Op.EQ, fingerPrint); } - return _sshKeyPairDao.search(sc, searchFilter); + Pair, Integer> result = _sshKeyPairDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -3426,13 +3249,16 @@ public class ManagementServerImpl implements ManagementServer { nvp.setValue(DBEncryptionUtil.encrypt(cmd.getPassword())); _detailsDao.persist(nvp); } else { - // if one host in the cluster has diff username then rollback to maintain consistency + // if one host in the cluster has diff username then + // rollback to maintain consistency txn.rollback(); - throw new InvalidParameterValueException("The username is not same for all hosts, please modify passwords for individual hosts."); + throw new InvalidParameterValueException( + "The username is not same for all hosts, please modify passwords for individual hosts."); } } txn.commit(); - // if hypervisor is xenserver then we update it in CitrixResourceBase + // if hypervisor is xenserver then we update it in + // CitrixResourceBase } catch (Exception e) { txn.rollback(); throw new CloudRuntimeException("Failed to update password " + e.getMessage()); @@ -3463,7 +3289,8 @@ public class ManagementServerImpl implements ManagementServer { } @Override - public List listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, Long startIndex, Long pageSizeVal) { + public Pair, Integer> listHypervisorCapabilities(Long id, HypervisorType hypervisorType, String keyword, + Long startIndex, Long pageSizeVal) { Filter searchFilter = new Filter(HypervisorCapabilitiesVO.class, "id", true, startIndex, pageSizeVal); SearchCriteria sc = _hypervisorCapabilitiesDao.createSearchCriteria(); @@ -3481,8 +3308,8 @@ public class ManagementServerImpl implements ManagementServer { sc.addAnd("hypervisorType", SearchCriteria.Op.SC, ssc); } - return _hypervisorCapabilitiesDao.search(sc, searchFilter); - + Pair, Integer> result = _hypervisorCapabilitiesDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override @@ -3519,15 +3346,13 @@ public class ManagementServerImpl implements ManagementServer { } } - @Override public VirtualMachine upgradeSystemVM(UpgradeSystemVMCmd cmd) { Long systemVmId = cmd.getId(); Long serviceOfferingId = cmd.getServiceOfferingId(); Account caller = UserContext.current().getCaller(); - VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, - VirtualMachine.Type.SecondaryStorageVm); + VMInstanceVO systemVm = _vmInstanceDao.findByIdTypes(systemVmId, VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm); if (systemVm == null) { throw new InvalidParameterValueException("Unable to find SystemVm with id " + systemVmId); } @@ -3547,4 +3372,28 @@ public class ManagementServerImpl implements ManagementServer { } + public void enableAdminUser(String password) { + String encodedPassword = null; + + UserVO adminUser = _userDao.getUser(2); + if (adminUser.getState() == Account.State.disabled) { + // This means its a new account, set the password using the + // authenticator + + for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { + UserAuthenticator authenticator = en.nextElement(); + encodedPassword = authenticator.encode(password); + if (encodedPassword != null) { + break; + } + } + + adminUser.setPassword(encodedPassword); + adminUser.setState(Account.State.enabled); + _userDao.persist(adminUser); + s_logger.info("Admin user enabled"); + } + + } + } diff --git a/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java b/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java index 1be4c285260..355f3646a65 100644 --- a/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java +++ b/server/src/com/cloud/server/api/response/BaremetalTemplateResponse.java @@ -16,20 +16,19 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.utils.IdentityProxy; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; public class BaremetalTemplateResponse extends BaseResponse { @SerializedName("id") @Param(description="the template ID") - private IdentityProxy id = new IdentityProxy("vm_template"); - - public Long getId() { - return id.getValue(); + private String id; + + public String getId() { + return id; } - - public void setId(Long id) { - this.id.setValue(id); + + public void setId(String id) { + this.id = id; } } diff --git a/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java b/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java index cfde632b134..480107b1b9f 100644 --- a/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java +++ b/server/src/com/cloud/server/api/response/NwDeviceDhcpResponse.java @@ -16,9 +16,10 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class NwDeviceDhcpResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ZONE_ID) @Param(description="Zone where to add PXE server") diff --git a/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java b/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java index 8240c9cb4a8..72063c39b7f 100644 --- a/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java +++ b/server/src/com/cloud/server/api/response/NwDevicePxeServerResponse.java @@ -16,46 +16,46 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; -import com.cloud.utils.IdentityProxy; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.response.NetworkDeviceResponse; public class NwDevicePxeServerResponse extends NetworkDeviceResponse { @SerializedName(ApiConstants.ZONE_ID) @Param(description="Zone where to add PXE server") - private IdentityProxy zoneId = new IdentityProxy("data_center"); - + private String zoneId; + @SerializedName(ApiConstants.POD_ID) @Param(description="Pod where to add PXE server") - private IdentityProxy podId = new IdentityProxy("host_pod_ref"); - + private String podId; + @SerializedName(ApiConstants.URL) @Param(description="Ip of PXE server") private String url; - + @SerializedName(ApiConstants.TYPE) @Param(description="Type of add PXE server") private String type; - - public void setZoneId(Long zoneId) { - this.zoneId.setValue(zoneId); + + public void setZoneId(String zoneId) { + this.zoneId = zoneId; } - public Long getZoneId() { - return zoneId.getValue(); + public String getZoneId() { + return zoneId; } - - public void setPodId(Long podId) { - this.podId.setValue(podId); + + public void setPodId(String podId) { + this.podId = podId; } - public Long getPodId() { - return podId.getValue(); + public String getPodId() { + return podId; } - + public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } - + public void setType(String type) { this.type = type; } diff --git a/server/src/com/cloud/server/api/response/PxePingResponse.java b/server/src/com/cloud/server/api/response/PxePingResponse.java index 93d76907cc7..c37bd42774b 100644 --- a/server/src/com/cloud/server/api/response/PxePingResponse.java +++ b/server/src/com/cloud/server/api/response/PxePingResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java index 3b18f879189..441b9788108 100644 --- a/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/AssociateLunCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java index d0033ab0312..56164eb7843 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateLunCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java index b561b01823a..066c1c0fa2c 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateVolumeOnFilerCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class CreateVolumeOnFilerCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java index 21afec15022..0c7acfa9189 100644 --- a/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/CreateVolumePoolCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class CreateVolumePoolCmdResponse extends BaseResponse{ } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java index d4dc5747556..b4e697b116e 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteLUNCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DeleteLUNCmdResponse extends BaseResponse{ } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java index 455caa00dcd..40083ec3a98 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteVolumeOnFilerCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DeleteVolumeOnFilerCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java index 4f9dc46338f..1740ddc222a 100644 --- a/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DeleteVolumePoolCmdResponse.java @@ -16,7 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.BaseResponse; public class DeleteVolumePoolCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java index 6756b5d2c23..ce3160b699d 100644 --- a/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/DissociateLunCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class DissociateLunCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java index eb95c6d0a00..bd0ee3f4614 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListLunsCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java index ae6ef3e1237..b3f0fe31b3b 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListVolumePoolsCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java index 95e77b17a97..222e45c1320 100644 --- a/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ListVolumesOnFilerCmdResponse.java @@ -16,8 +16,8 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; +import org.apache.cloudstack.api.ApiConstants; +import org.apache.cloudstack.api.BaseResponse; import com.cloud.serializer.Param; import com.google.gson.annotations.SerializedName; diff --git a/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java b/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java index 33b2b788e83..fa0c069c842 100644 --- a/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java +++ b/server/src/com/cloud/server/api/response/netapp/ModifyVolumePoolCmdResponse.java @@ -16,10 +16,7 @@ // under the License. package com.cloud.server.api.response.netapp; -import com.cloud.api.ApiConstants; -import com.cloud.api.response.BaseResponse; -import com.cloud.serializer.Param; -import com.google.gson.annotations.SerializedName; +import org.apache.cloudstack.api.BaseResponse; public class ModifyVolumePoolCmdResponse extends BaseResponse { } diff --git a/server/src/com/cloud/server/auth/UserAuthenticator.java b/server/src/com/cloud/server/auth/UserAuthenticator.java index 725516c096f..95c4f0e4707 100644 --- a/server/src/com/cloud/server/auth/UserAuthenticator.java +++ b/server/src/com/cloud/server/auth/UserAuthenticator.java @@ -34,4 +34,10 @@ public interface UserAuthenticator extends Adapter { * @return true if the user has been successfully authenticated, false otherwise */ public boolean authenticate(String username, String password, Long domainId, Map requestParameters); + + /** + * @param password + * @return the encoded password + */ + public String encode(String password); } diff --git a/server/src/com/cloud/servlet/CloudStartupServlet.java b/server/src/com/cloud/servlet/CloudStartupServlet.java index dfd4c603ac6..4466ca86460 100755 --- a/server/src/com/cloud/servlet/CloudStartupServlet.java +++ b/server/src/com/cloud/servlet/CloudStartupServlet.java @@ -48,9 +48,10 @@ public class CloudStartupServlet extends HttpServlet implements ServletContextLi ConfigurationServer c = (ConfigurationServer)ComponentContext.getCompanent(ConfigurationServer.class); try { c.persistDefaultValues(); - ManagementServer ms = (ManagementServer)ComponentContext.getCompanent(ManagementServer.class); - ms.startup(); - ApiServer.initApiServer(ms.getApiConfig()); + s_locator = ComponentLocator.getLocator(ManagementServer.Name); + ManagementServer ms = (ManagementServer)ComponentLocator.getComponent(ManagementServer.Name); + ms.enableAdminUser("password"); + ApiServer.initApiServer(ms.getPropertiesFiles()); } catch (InvalidParameterValueException ipve) { s_logger.error("Exception starting management server ", ipve); throw new ServletException (ipve.getMessage()); diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 7f073f1a74f..afa5c407316 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -35,7 +35,7 @@ import javax.servlet.http.HttpSession; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; -import com.cloud.api.IdentityService; +import org.apache.cloudstack.api.IdentityService; import com.cloud.exception.PermissionDeniedException; import com.cloud.host.HostVO; import com.cloud.server.ManagementServer; diff --git a/server/src/com/cloud/storage/StorageManager.java b/server/src/com/cloud/storage/StorageManager.java index d535af4bd7e..97853ac76de 100755 --- a/server/src/com/cloud/storage/StorageManager.java +++ b/server/src/com/cloud/storage/StorageManager.java @@ -53,28 +53,28 @@ public interface StorageManager extends StorageService, Manager { * @return absolute ISO path */ public Pair getAbsoluteIsoPath(long templateId, long dataCenterId); - + /** * Returns the URL of the secondary storage host * @param zoneId * @return URL */ public String getSecondaryStorageURL(long zoneId); - + /** * Returns a comma separated list of tags for the specified storage pool * @param poolId * @return comma separated list of tags */ public String getStoragePoolTags(long poolId); - + /** * Returns the secondary storage host * @param zoneId * @return secondary storage host */ public HostVO getSecondaryStorageHost(long zoneId); - + /** * Returns the secondary storage host * @param zoneId @@ -89,7 +89,7 @@ public interface StorageManager extends StorageService, Manager { * @param destPoolPodId * @param destPoolClusterId * @return VolumeVO - * @throws ConcurrentOperationException + * @throws ConcurrentOperationException */ VolumeVO moveVolume(VolumeVO volume, long destPoolDcId, Long destPoolPodId, Long destPoolClusterId, HypervisorType dataDiskHyperType) throws ConcurrentOperationException; @@ -114,10 +114,10 @@ public interface StorageManager extends StorageService, Manager { /** * Marks the specified volume as destroyed in the management server database. The expunge thread will delete the volume from its storage pool. * @param volume - * @return + * @return */ boolean destroyVolume(VolumeVO volume) throws ConcurrentOperationException; - + /** Create capacity entries in the op capacity table * @param storagePool */ @@ -136,7 +136,7 @@ public interface StorageManager extends StorageService, Manager { Answer[] sendToPool(StoragePool pool, Commands cmds) throws StorageUnavailableException; Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Commands cmds) throws StorageUnavailableException; Pair sendToPool(StoragePool pool, long[] hostIdsToTryFirst, List hostIdsToAvoid, Command cmd) throws StorageUnavailableException; - + /** * Checks that one of the following is true: * 1. The volume is not attached to any VM @@ -145,21 +145,21 @@ public interface StorageManager extends StorageService, Manager { * @return true if one of the above conditions is true */ boolean volumeInactive(VolumeVO volume); - + String getVmNameOnVolume(VolumeVO volume); - + /** * Checks if a host has running VMs that are using its local storage pool. * @return true if local storage is active on the host */ - boolean isLocalStorageActiveOnHost(Host host); - + boolean isLocalStorageActiveOnHost(Long hostId); + /** * Cleans up storage pools by removing unused templates. * @param recurring - true if this cleanup is part of a recurring garbage collection thread */ void cleanupStorage(boolean recurring); - + String getPrimaryStorageNameLabel(VolumeVO volume); /** @@ -176,16 +176,16 @@ public interface StorageManager extends StorageService, Manager { */ DiskProfile allocateRawVolume(Type type, String name, DiskOfferingVO offering, Long size, T vm, Account owner); DiskProfile allocateTemplatedVolume(Type type, String name, DiskOfferingVO offering, VMTemplateVO template, T vm, Account owner); - + void createCapacityEntry(StoragePoolVO storagePool, short capacityType, long allocated); - + void prepare(VirtualMachineProfile vm, DeployDestination dest) throws StorageUnavailableException, InsufficientStorageCapacityException, ConcurrentOperationException; void release(VirtualMachineProfile profile); void cleanupVolumes(long vmId) throws ConcurrentOperationException; - + void prepareForMigration(VirtualMachineProfile vm, DeployDestination dest); Answer sendToPool(StoragePool pool, long[] hostIdsToTryFirst, Command cmd) throws StorageUnavailableException; @@ -217,7 +217,7 @@ public interface StorageManager extends StorageService, Manager { boolean stateTransitTo(Volume vol, Event event) throws NoTransitionException; - + VolumeVO allocateDuplicateVolume(VolumeVO oldVol, Long templateId); Host updateSecondaryStorage(long secStorageId, String newUrl); @@ -236,5 +236,7 @@ public interface StorageManager extends StorageService, Manager { HypervisorType getHypervisorTypeFromFormat(ImageFormat format); - boolean storagePoolHasEnoughSpace(List volume, StoragePool pool); -} + boolean storagePoolHasEnoughSpace(List volume, StoragePool pool); + + boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException; +} diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 6289a7a328f..78c24692fe0 100755 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -45,6 +45,9 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.storage.*; +import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.UploadVolumeCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -73,13 +76,7 @@ import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.CancelPrimaryStorageMaintenanceCmd; -import com.cloud.api.commands.CreateStoragePoolCmd; -import com.cloud.api.commands.CreateVolumeCmd; -import com.cloud.api.commands.DeletePoolCmd; -import com.cloud.api.commands.ListVolumesCmd; -import com.cloud.api.commands.UpdateStoragePoolCmd; -import com.cloud.api.commands.UploadVolumeCmd; +import org.apache.cloudstack.api.command.admin.storage.CreateStoragePoolCmd; import com.cloud.async.AsyncJobManager; import com.cloud.capacity.Capacity; import com.cloud.capacity.CapacityManager; @@ -131,11 +128,9 @@ import com.cloud.network.NetworkManager; import com.cloud.offering.ServiceOffering; import com.cloud.org.Grouping; import com.cloud.org.Grouping.AllocationState; -import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; import com.cloud.server.ManagementServer; -import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.server.StatsCollector; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; @@ -153,15 +148,16 @@ 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; -import com.cloud.tags.ResourceTagVO; import com.cloud.tags.dao.ResourceTagDao; import com.cloud.template.TemplateManager; import com.cloud.user.Account; @@ -175,14 +171,12 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.EnumUtils; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; -import com.cloud.utils.Ternary; import com.cloud.utils.UriUtils; import com.cloud.utils.component.Adapters; import com.cloud.utils.component.ComponentLocator; 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.GenericSearchBuilder; import com.cloud.utils.db.GlobalLock; import com.cloud.utils.db.JoinBuilder; @@ -264,6 +258,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; @@ -434,8 +432,8 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } @Override - public boolean isLocalStorageActiveOnHost(Host host) { - List storagePoolHostRefs = _storagePoolHostDao.listByHostId(host.getId()); + public boolean isLocalStorageActiveOnHost(Long hostId) { + List storagePoolHostRefs = _storagePoolHostDao.listByHostId(hostId); for (StoragePoolHostVO storagePoolHostRef : storagePoolHostRefs) { StoragePoolVO storagePool = _storagePoolDao.findById(storagePoolHostRef.getPoolId()); if (storagePool.getPoolType() == StoragePoolType.LVM || storagePool.getPoolType() == StoragePoolType.EXT) { @@ -664,7 +662,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(); @@ -708,8 +705,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)) { @@ -836,11 +835,23 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag for (int i = 0; i < 2; i++) { if (volume.getVolumeType() == Type.ROOT && Storage.ImageFormat.ISO != template.getFormat()) { + if (pool.getPoolType() == StoragePoolType.CLVM) { + //prepareISOForCreate does what we need, which is to tell us where the template is + VMTemplateHostVO tmpltHostOn = _tmpltMgr.prepareISOForCreate(template, pool); + if (tmpltHostOn == null) { + continue; + } + HostVO secondaryStorageHost = _hostDao.findById(tmpltHostOn.getHostId()); + String tmpltHostUrl = secondaryStorageHost.getStorageUrl(); + String fullTmpltUrl = tmpltHostUrl + "/" + tmpltHostOn.getInstallPath(); + cmd = new CreateCommand(dskCh, fullTmpltUrl, new StorageFilerTO(pool)); + } else { tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { continue; } cmd = new CreateCommand(dskCh, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); + } } else { if (volume.getVolumeType() == Type.ROOT && Storage.ImageFormat.ISO == template.getFormat()) { VMTemplateHostVO tmpltHostOn = _tmpltMgr.prepareISOForCreate(template, pool); @@ -1270,7 +1281,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")) { @@ -2864,15 +2875,10 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } } - private boolean isAdmin(short accountType) { - return ((accountType == Account.ACCOUNT_TYPE_ADMIN) || (accountType == Account.ACCOUNT_TYPE_DOMAIN_ADMIN) || (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); - } - @Override @DB @ActionEvent(eventType = EventTypes.EVENT_VOLUME_DELETE, eventDescription = "deleting volume") - public boolean deleteVolume(long volumeId) throws ConcurrentOperationException { - Account caller = UserContext.current().getCaller(); + public boolean deleteVolume(long volumeId, Account caller) throws ConcurrentOperationException { // Check that the volume ID is valid VolumeVO volume = _volsDao.findById(volumeId); @@ -2976,6 +2982,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) { @@ -3382,12 +3396,6 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag @DB protected VolumeVO switchVolume(VolumeVO existingVolume, VirtualMachineProfile vm) throws StorageUnavailableException { Transaction txn = Transaction.currentTxn(); - txn.start(); - try { - stateTransitTo(existingVolume, Volume.Event.DestroyRequested); - } catch (NoTransitionException e) { - s_logger.debug("Unable to destroy existing volume: " + e.toString()); - } Long templateIdToUse = null; Long volTemplateId = existingVolume.getTemplateId(); @@ -3398,7 +3406,19 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag } templateIdToUse = vmTemplateId; } + + txn.start(); VolumeVO newVolume = allocateDuplicateVolume(existingVolume, templateIdToUse); + // In case of Vmware if vm reference is not removed then during root disk cleanup + // the vm also gets deleted, so remove the reference + if (vm.getHypervisorType() == HypervisorType.VMware) { + _volsDao.detachVolume(existingVolume.getId()); + } + try { + stateTransitTo(existingVolume, Volume.Event.DestroyRequested); + } catch (NoTransitionException e) { + s_logger.debug("Unable to destroy existing volume: " + e.toString()); + } txn.commit(); return newVolume; @@ -3439,12 +3459,25 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag for (int i = 0; i < 2; i++) { if (template != null && template.getFormat() != Storage.ImageFormat.ISO) { + if (pool.getPoolType() == StoragePoolType.CLVM) { + //prepareISOForCreate does what we need, which is to tell us where the template is + VMTemplateHostVO tmpltHostOn = _tmpltMgr.prepareISOForCreate(template, pool); + if (tmpltHostOn == null) { + s_logger.debug("cannot find template " + template.getId() + " " + template.getName()); + return null; + } + HostVO secondaryStorageHost = _hostDao.findById(tmpltHostOn.getHostId()); + String tmpltHostUrl = secondaryStorageHost.getStorageUrl(); + String fullTmpltUrl = tmpltHostUrl + "/" + tmpltHostOn.getInstallPath(); + cmd = new CreateCommand(diskProfile, fullTmpltUrl, new StorageFilerTO(pool)); + } else { tmpltStoredOn = _tmpltMgr.prepareTemplateForCreate(template, pool); if (tmpltStoredOn == null) { s_logger.debug("Cannot use this pool " + pool + " because we can't propagate template " + template); return null; } cmd = new CreateCommand(diskProfile, tmpltStoredOn.getLocalDownloadPath(), new StorageFilerTO(pool)); + } } else { if (template != null && Storage.ImageFormat.ISO == template.getFormat()) { VMTemplateHostVO tmpltHostOn = _tmpltMgr.prepareISOForCreate(template, pool); @@ -3824,122 +3857,7 @@ public class StorageManagerImpl implements StorageManager, Manager, ClusterManag return secHost; } - @Override - public List searchForVolumes(ListVolumesCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - Long id = cmd.getId(); - Long vmInstanceId = cmd.getVirtualMachineId(); - String name = cmd.getVolumeName(); - String keyword = cmd.getKeyword(); - String type = cmd.getType(); - Map tags = cmd.getTags(); - - Long zoneId = cmd.getZoneId(); - Long podId = null; - // Object host = null; TODO - if (_accountMgr.isAdmin(caller.getType())) { - podId = cmd.getPodId(); - // host = cmd.getHostId(); TODO - } - - Ternary domainIdRecursiveListProject = new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, cmd.listAll(), false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(VolumeVO.class, "created", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - - // hack for now, this should be done better but due to needing a join I opted to - // do this quickly and worry about making it pretty later - SearchBuilder sb = _volumeDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("name", sb.entity().getName(), SearchCriteria.Op.LIKE); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("volumeType", sb.entity().getVolumeType(), SearchCriteria.Op.LIKE); - sb.and("instanceId", sb.entity().getInstanceId(), SearchCriteria.Op.EQ); - sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); - // Only return volumes that are not destroyed - sb.and("state", sb.entity().getState(), SearchCriteria.Op.NEQ); - - SearchBuilder diskOfferingSearch = _diskOfferingDao.createSearchBuilder(); - diskOfferingSearch.and("systemUse", diskOfferingSearch.entity().getSystemUse(), SearchCriteria.Op.NEQ); - sb.join("diskOfferingSearch", diskOfferingSearch, sb.entity().getDiskOfferingId(), diskOfferingSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - - // display UserVM volumes only - SearchBuilder vmSearch = _vmInstanceDao.createSearchBuilder(); - vmSearch.and("type", vmSearch.entity().getType(), SearchCriteria.Op.NIN); - vmSearch.or("nulltype", vmSearch.entity().getType(), SearchCriteria.Op.NULL); - sb.join("vmSearch", vmSearch, sb.entity().getInstanceId(), vmSearch.entity().getId(), JoinBuilder.JoinType.LEFTOUTER); - - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao.createSearchBuilder(); - for (int count=0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch.entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch.entity().getResourceId(), JoinBuilder.JoinType.INNER); - } - - // now set the SC criteria... - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (keyword != null) { - SearchCriteria ssc = _volumeDao.createSearchCriteria(); - ssc.addOr("name", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("volumeType", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("name", SearchCriteria.Op.SC, ssc); - } - - if (name != null) { - sc.setParameters("name", "%" + name + "%"); - } - - sc.setJoinParameters("diskOfferingSearch", "systemUse", 1); - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", TaggedResourceType.Volume.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", "value" + String.valueOf(count), tags.get(key)); - count++; - } - } - - if (id != null) { - sc.setParameters("id", id); - } - - if (type != null) { - sc.setParameters("volumeType", "%" + type + "%"); - } - if (vmInstanceId != null) { - sc.setParameters("instanceId", vmInstanceId); - } - if (zoneId != null) { - sc.setParameters("dataCenterId", zoneId); - } - if (podId != null) { - sc.setParameters("podId", podId); - } - - // Don't return DomR and ConsoleProxy volumes - sc.setJoinParameters("vmSearch", "type", VirtualMachine.Type.ConsoleProxy, VirtualMachine.Type.SecondaryStorageVm, VirtualMachine.Type.DomainRouter); - - // Only return volumes that are not destroyed - sc.setParameters("state", Volume.State.Destroy); - - return _volumeDao.search(sc, searchFilter); - } @Override public String getSupportedImageFormatForCluster(Long clusterId) { 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/SnapshotScheduleDao.java b/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java index c42200c0a10..0419e2836a0 100644 --- a/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java +++ b/server/src/com/cloud/storage/dao/SnapshotScheduleDao.java @@ -19,7 +19,6 @@ package com.cloud.storage.dao; import java.util.Date; import java.util.List; - import com.cloud.storage.SnapshotPolicyVO; import com.cloud.storage.SnapshotScheduleVO; import com.cloud.utils.db.GenericDao; diff --git a/server/src/com/cloud/storage/dao/VMTemplateDao.java b/server/src/com/cloud/storage/dao/VMTemplateDao.java index f5b6913df8a..a043a2c6079 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDao.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDao.java @@ -58,6 +58,10 @@ public interface VMTemplateDao extends GenericDao { boolean isIso, List hypers, Boolean bootable, DomainVO domain, Long pageSize, Long startIndex, Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List permittedAccounts, Account caller, Map tags); + public Set> searchS3Templates(String name, String keyword, TemplateFilter templateFilter, + boolean isIso, List hypers, Boolean bootable, DomainVO domain, Long pageSize, Long startIndex, + Long zoneId, HypervisorType hyperType, boolean onlyReady, boolean showDomr, List permittedAccounts, Account caller, Map tags); + public long addTemplateToZone(VMTemplateVO tmplt, long zoneId); public List listAllInZone(long dataCenterId); @@ -71,4 +75,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 cd597bc3b97..8093fd5f9e2 100755 --- a/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VMTemplateDaoImpl.java @@ -16,6 +16,9 @@ // under the License. package com.cloud.storage.dao; +import static com.cloud.utils.StringUtils.*; +import static com.cloud.utils.db.DbUtil.*; + import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; @@ -34,7 +37,7 @@ import javax.naming.ConfigurationException; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.BaseCmd; +import org.apache.cloudstack.api.BaseCmd; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.dao.DataCenterDao; import com.cloud.domain.DomainVO; @@ -94,6 +97,17 @@ 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 final String SELECT_TEMPLATE_S3_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; @@ -920,4 +934,143 @@ public class VMTemplateDaoImpl extends GenericDaoBase implem (accountType == Account.ACCOUNT_TYPE_READ_ONLY_ADMIN)); } + @Override + public List findTemplatesToSyncToS3() { + return executeList(SELECT_S3_CANDIDATE_TEMPLATES, new Object[] {}); + } + + @Override + public Set> searchS3Templates(final String name, + final String keyword, final TemplateFilter templateFilter, + final boolean isIso, final List hypers, + final Boolean bootable, final DomainVO domain, final Long pageSize, + final Long startIndex, final Long zoneId, + final HypervisorType hyperType, final boolean onlyReady, + final boolean showDomr, final List permittedAccounts, + final Account caller, final Map tags) { + + final String permittedAccountsStr = join(",", permittedAccounts); + + final Transaction txn = Transaction.currentTxn(); + txn.start(); + + Set> templateZonePairList = new HashSet>(); + PreparedStatement pstmt = null; + ResultSet rs = null; + try { + + final StringBuilder joinClause = new StringBuilder(); + final StringBuilder whereClause = new StringBuilder(" WHERE t.removed IS NULL"); + + if (isIso) { + whereClause.append(" AND t.format = 'ISO'"); + if (!hyperType.equals(HypervisorType.None)) { + joinClause.append(" INNER JOIN guest_os guestOS on (guestOS.id = t.guest_os_id) INNER JOIN guest_os_hypervisor goh on ( goh.guest_os_id = guestOS.id) "); + whereClause.append(" AND goh.hypervisor_type = '"); + whereClause.append(hyperType); + whereClause.append("'"); + } + } else { + whereClause.append(" AND t.format <> 'ISO'"); + if (hypers.isEmpty()) { + return templateZonePairList; + } else { + final StringBuilder relatedHypers = new StringBuilder(); + for (HypervisorType hyper : hypers) { + relatedHypers.append("'"); + relatedHypers.append(hyper.toString()); + relatedHypers.append("'"); + relatedHypers.append(","); + } + relatedHypers.setLength(relatedHypers.length() - 1); + whereClause.append(" AND t.hypervisor_type IN ("); + whereClause.append(relatedHypers); + whereClause.append(")"); + } + } + + joinClause.append(" INNER JOIN template_s3_ref tsr on (t.id = tsr.template_id)"); + + whereClause.append("AND t.name LIKE \"%"); + whereClause.append(keyword == null ? keyword : name); + whereClause.append("%\""); + + if (bootable != null) { + whereClause.append(" AND t.bootable = "); + whereClause.append(bootable); + } + + if (!showDomr) { + whereClause.append(" AND t.type != '"); + whereClause.append(Storage.TemplateType.SYSTEM); + whereClause.append("'"); + } + + if (templateFilter == TemplateFilter.featured) { + whereClause.append(" AND t.public = 1 AND t.featured = 1"); + } else if ((templateFilter == TemplateFilter.self || templateFilter == TemplateFilter.selfexecutable) + && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (caller.getType() == Account.ACCOUNT_TYPE_DOMAIN_ADMIN + || caller.getType() == Account.ACCOUNT_TYPE_RESOURCE_DOMAIN_ADMIN) { + joinClause.append(" INNER JOIN account a on (t.account_id = a.id) INNER JOIN domain d on (a.domain_id = d.id)"); + whereClause.append(" AND d.path LIKE '"); + whereClause.append(domain.getPath()); + whereClause.append("%'"); + } else { + whereClause.append(" AND t.account_id IN ("); + whereClause.append(permittedAccountsStr); + whereClause.append(")"); + } + } else if (templateFilter == TemplateFilter.sharedexecutable + && caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { + joinClause.append(" LEFT JOIN launch_permission lp ON t.id = lp.template_id WHERE (t.account_id IN ("); + joinClause.append(permittedAccountsStr); + joinClause.append(") OR lp.account_id IN ("); + joinClause.append(permittedAccountsStr); + joinClause.append("))"); + } else { + joinClause.append(" INNER JOIN account a on (t.account_id = a.id) "); + } + } else if (templateFilter == TemplateFilter.executable + && !permittedAccounts.isEmpty()) { + whereClause.append(" AND (t.public = 1 OR t.account_id IN ("); + whereClause.append(permittedAccountsStr); + whereClause.append("))"); + } else if (templateFilter == TemplateFilter.community) { + whereClause.append(" AND t.public = 1 AND t.featured = 0"); + } else if (templateFilter == TemplateFilter.all + && caller.getType() == Account.ACCOUNT_TYPE_ADMIN) { + } else if (caller.getType() != Account.ACCOUNT_TYPE_ADMIN) { + return templateZonePairList; + } + + final StringBuilder sql = new StringBuilder(SELECT_TEMPLATE_S3_REF); + sql.append(joinClause); + sql.append(whereClause); + sql.append(getOrderByLimit(pageSize, startIndex)); + + pstmt = txn.prepareStatement(sql.toString()); + rs = pstmt.executeQuery(); + while (rs.next()) { + final Pair templateZonePair = new Pair( + rs.getLong(1), -1L); + templateZonePairList.add(templateZonePair); + } + txn.commit(); + } catch (Exception e) { + s_logger.warn("Error listing S3 templates", e); + if (txn != null) { + txn.rollback(); + } + } finally { + closeResources(pstmt, rs); + if (txn != null) { + txn.close(); + } + } + + return templateZonePairList; + } + } 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/dao/VolumeHostDao.java b/server/src/com/cloud/storage/dao/VolumeHostDao.java index 4ec69c38d89..6ba82370608 100755 --- a/server/src/com/cloud/storage/dao/VolumeHostDao.java +++ b/server/src/com/cloud/storage/dao/VolumeHostDao.java @@ -18,7 +18,6 @@ package com.cloud.storage.dao; import java.util.List; -import com.cloud.host.HostVO; import com.cloud.storage.VolumeHostVO; import com.cloud.utils.db.GenericDao; diff --git a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java index 66e1a717f15..ca14bd7467f 100755 --- a/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java +++ b/server/src/com/cloud/storage/dao/VolumeHostDaoImpl.java @@ -20,10 +20,6 @@ import java.util.List; import javax.ejb.Local; -import org.springframework.stereotype.Component; - -import com.cloud.host.HostVO; -import com.cloud.storage.VMTemplateHostVO; import com.cloud.storage.VolumeHostVO; import com.cloud.utils.db.GenericDaoBase; import com.cloud.utils.db.SearchBuilder; 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..0e47d7273d6 --- /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 org.apache.cloudstack.api.command.admin.storage.AddS3Cmd; +import org.apache.cloudstack.api.command.admin.storage.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..1db809b07b2 --- /dev/null +++ b/server/src/com/cloud/storage/s3/S3ManagerImpl.java @@ -0,0 +1,664 @@ +/* + * 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 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.cloudstack.api.command.admin.storage.AddS3Cmd; +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 org.apache.cloudstack.api.command.admin.storage.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(); + + 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 b8b530a4b13..c4029ea8ffb 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; @@ -26,6 +27,8 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotPolicyCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -36,16 +39,16 @@ 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 com.cloud.api.commands.CreateSnapshotPolicyCmd; -import com.cloud.api.commands.DeleteSnapshotPoliciesCmd; +import org.apache.cloudstack.api.command.user.snapshot.DeleteSnapshotPoliciesCmd; import com.cloud.api.commands.ListRecurringSnapshotScheduleCmd; -import com.cloud.api.commands.ListSnapshotPoliciesCmd; -import com.cloud.api.commands.ListSnapshotsCmd; +import org.apache.cloudstack.api.command.user.snapshot.ListSnapshotPoliciesCmd; import com.cloud.configuration.Config; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; @@ -93,6 +96,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; @@ -174,6 +178,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma @Inject private SwiftManager _swiftMgr; @Inject + private S3Manager _s3Mgr; + @Inject private SecondaryStorageVmManager _ssvmMgr; @Inject private ResourceManager _resourceMgr; @@ -197,15 +203,13 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma protected Answer sendToPool(Volume vol, Command cmd) { StoragePool pool = _storagePoolDao.findById(vol.getPoolId()); - VMInstanceVO vm = _vmDao.findById(vol.getInstanceId()); long[] hostIdsToTryFirst = null; - if (vm != null) { - if(vm.getHostId() != null) { - hostIdsToTryFirst = new long[] { vm.getHostId() }; - } else if(vm.getLastHostId() != null) { - hostIdsToTryFirst = new long[] { vm.getLastHostId() }; - } + + Long vmHostId = getHostIdForSnapshotOperation(vol); + + if (vmHostId != null) { + hostIdsToTryFirst = new long[] { vmHostId }; } List hostIdsToAvoid = new ArrayList(); @@ -237,6 +241,19 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma return null; } + @Override + public Long getHostIdForSnapshotOperation(Volume vol) { + VMInstanceVO vm = _vmDao.findById(vol.getInstanceId()); + if (vm != null) { + if(vm.getHostId() != null) { + return vm.getHostId(); + } else if(vm.getLastHostId() != null) { + return vm.getLastHostId(); + } + } + return null; + } + @Override public SnapshotVO createSnapshotOnPrimary(VolumeVO volume, Long policyId, Long snapshotId) { SnapshotVO snapshot = _snapshotDao.findById(snapshotId); @@ -468,11 +485,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() ) { @@ -534,6 +565,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 @@ -551,7 +630,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(); @@ -568,6 +646,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) { @@ -577,7 +658,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(); } @@ -585,11 +667,13 @@ 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; @@ -612,6 +696,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); @@ -823,7 +910,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()) { @@ -844,7 +937,7 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma } @Override - public List listSnapshots(ListSnapshotsCmd cmd) { + public Pair, Integer> listSnapshots(ListSnapshotsCmd cmd) { Long volumeId = cmd.getVolumeId(); String name = cmd.getSnapshotName(); Long id = cmd.getId(); @@ -945,7 +1038,8 @@ public class SnapshotManagerImpl implements SnapshotManager, SnapshotService, Ma sc.setParameters("snapshotTypeNEQ", Snapshot.Type.TEMPLATE.ordinal()); } - return _snapshotDao.search(sc, searchFilter); + Pair, Integer> result = _snapshotDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @@ -969,9 +1063,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); @@ -988,12 +1088,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/storage/snapshot/SnapshotSchedulerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java index bea077d29bc..c6fc5308070 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotSchedulerImpl.java @@ -27,12 +27,13 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.snapshot.CreateSnapshotCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDispatcher; import com.cloud.api.ApiGsonHelper; -import com.cloud.api.commands.CreateSnapshotCmd; import com.cloud.user.Account; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; @@ -237,10 +238,10 @@ public class SnapshotSchedulerImpl implements SnapshotScheduler { EventTypes.EVENT_SNAPSHOT_CREATE, "creating snapshot for volume Id:"+volumeId,0); Map params = new HashMap(); - params.put("volumeid", ""+volumeId); - params.put("policyid", ""+policyId); + params.put(ApiConstants.VOLUME_ID, "" + volumeId); + params.put(ApiConstants.POLICY_ID, "" + policyId); params.put("ctxUserId", "1"); - params.put("ctxAccountId", "1"); + params.put("ctxAccountId", "" + volume.getAccountId()); params.put("ctxStartEventId", String.valueOf(eventId)); CreateSnapshotCmd cmd = new CreateSnapshotCmd(); @@ -248,14 +249,9 @@ public class SnapshotSchedulerImpl implements SnapshotScheduler { params.put("id", ""+cmd.getEntityId()); params.put("ctxStartEventId", "1"); - AsyncJobVO job = new AsyncJobVO(); - job.setUserId(userId); - // Just have SYSTEM own the job for now. Users won't be able to see this job, but - // it's an internal job so probably not a huge deal. - job.setAccountId(1L); - job.setCmd(CreateSnapshotCmd.class.getName()); - job.setInstanceId(cmd.getEntityId()); - job.setCmdInfo(ApiGsonHelper.getBuilder().create().toJson(params)); + AsyncJobVO job = new AsyncJobVO(User.UID_SYSTEM, volume.getAccountId(), CreateSnapshotCmd.class.getName(), + ApiGsonHelper.getBuilder().create().toJson(params), cmd.getEntityId(), + cmd.getInstanceType()); long jobId = _asyncMgr.submitAsyncJob(job); @@ -361,6 +357,7 @@ public class SnapshotSchedulerImpl implements SnapshotScheduler { _testTimerTask = new TestClock(this, minutesPerHour, hoursPerDay, daysPerWeek, daysPerMonth, weeksPerMonth, monthsPerYear); } _currentTimestamp = new Date(); + s_logger.info("Snapshot Scheduler is configured."); return true; diff --git a/server/src/com/cloud/storage/swift/SwiftManager.java b/server/src/com/cloud/storage/swift/SwiftManager.java index d897442da8e..0dd6e1cf22a 100644 --- a/server/src/com/cloud/storage/swift/SwiftManager.java +++ b/server/src/com/cloud/storage/swift/SwiftManager.java @@ -19,10 +19,10 @@ package com.cloud.storage.swift; import java.util.List; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import com.cloud.exception.DiscoveryException; import com.cloud.storage.Swift; import com.cloud.storage.SwiftVO; diff --git a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java index d7e70673727..ef3deed74b1 100644 --- a/server/src/com/cloud/storage/swift/SwiftManagerImpl.java +++ b/server/src/com/cloud/storage/swift/SwiftManagerImpl.java @@ -26,6 +26,9 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.swift.ListSwiftsCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; @@ -33,10 +36,7 @@ import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.DeleteObjectFromSwiftCommand; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.AddSwiftCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ListSwiftsCmd; +import org.apache.cloudstack.api.command.admin.swift.AddSwiftCmd; import com.cloud.configuration.Config; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/storage/upload/UploadListener.java b/server/src/com/cloud/storage/upload/UploadListener.java index 5e8e3e0a8ab..ee13cf9b0d8 100755 --- a/server/src/com/cloud/storage/upload/UploadListener.java +++ b/server/src/com/cloud/storage/upload/UploadListener.java @@ -24,6 +24,8 @@ import java.util.Map; import java.util.Timer; import java.util.TimerTask; +import org.apache.cloudstack.api.command.user.iso.ExtractIsoCmd; +import org.apache.cloudstack.api.command.user.volume.ExtractVolumeCmd; import org.apache.log4j.Level; import org.apache.log4j.Logger; @@ -38,14 +40,12 @@ import com.cloud.agent.api.storage.UploadAnswer; import com.cloud.agent.api.storage.UploadCommand; import com.cloud.agent.api.storage.UploadProgressCommand; import com.cloud.agent.api.storage.UploadProgressCommand.RequestType; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ExtractVolumeCmd; -import com.cloud.api.response.ExtractResponse; +import org.apache.cloudstack.api.command.user.template.ExtractTemplateCmd; +import org.apache.cloudstack.api.response.ExtractResponse; + +import com.cloud.api.ApiDBUtils; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobResult; -import com.cloud.async.executor.ExtractJobResultObject; -import com.cloud.event.EventVO; import com.cloud.exception.AgentUnavailableException; import com.cloud.host.HostVO; import com.cloud.storage.Storage; @@ -57,12 +57,12 @@ import com.cloud.storage.upload.UploadState.UploadEvent; import com.cloud.utils.exception.CloudRuntimeException; public class UploadListener implements Listener { - + private static final class StatusTask extends TimerTask { private final UploadListener ul; private final RequestType reqType; - + public StatusTask( UploadListener ul, RequestType req) { this.reqType = req; this.ul = ul; @@ -74,10 +74,10 @@ public class UploadListener implements Listener { } } - + private static final class TimeoutTask extends TimerTask { private final UploadListener ul; - + public TimeoutTask( UploadListener ul) { this.ul = ul; } @@ -91,13 +91,13 @@ public class UploadListener implements Listener { public static final Logger s_logger = Logger.getLogger(UploadListener.class.getName()); public static final int SMALL_DELAY = 100; public static final long STATUS_POLL_INTERVAL = 10000L; - + public static final String UPLOADED=Status.UPLOADED.toString(); public static final String NOT_UPLOADED=Status.NOT_UPLOADED.toString(); public static final String UPLOAD_ERROR=Status.UPLOAD_ERROR.toString(); public static final String UPLOAD_IN_PROGRESS=Status.UPLOAD_IN_PROGRESS.toString(); public static final String UPLOAD_ABANDONED=Status.ABANDONED.toString(); - public static final Map responseNameMap; + public static final Map responseNameMap; static{ MaptempMap = new HashMap(); tempMap.put(Type.ISO.toString(), ExtractIsoCmd.getStaticName()); @@ -108,16 +108,16 @@ public class UploadListener implements Listener { } - private HostVO sserver; - + private HostVO sserver; + private boolean uploadActive = true; - + private UploadDao uploadDao; - + private final UploadMonitorImpl uploadMonitor; - + private UploadState currState; - + private UploadCommand cmd; private Timer timer; @@ -133,7 +133,7 @@ public class UploadListener implements Listener { private long eventId; private AsyncJobManager asyncMgr; private ExtractResponse resultObj; - + public AsyncJobManager getAsyncMgr() { return asyncMgr; } @@ -159,12 +159,12 @@ public class UploadListener implements Listener { } private final Map stateMap = new HashMap(); - private Long uploadId; - + private Long uploadId; + public UploadListener(HostVO host, Timer _timer, UploadDao uploadDao, UploadVO uploadObj, UploadMonitorImpl uploadMonitor, UploadCommand cmd, Long accountId, String typeName, Type type, long eventId, long asyncJobId, AsyncJobManager asyncMgr) { - this.sserver = host; + this.sserver = host; this.uploadDao = uploadDao; this.uploadMonitor = uploadMonitor; this.cmd = cmd; @@ -180,15 +180,23 @@ public class UploadListener implements Listener { this.eventId = eventId; this.asyncJobId = asyncJobId; this.asyncMgr = asyncMgr; - this.resultObj = new ExtractResponse(uploadObj.getTypeId(), typeName, accountId, Status.NOT_UPLOADED.toString(), uploadId); + String extractId = null; + if ( type == Type.VOLUME ){ + extractId = ApiDBUtils.findVolumeById(uploadObj.getTypeId()).getUuid(); + } + else{ + extractId = ApiDBUtils.findTemplateById(uploadObj.getTypeId()).getUuid(); + } + this.resultObj = new ExtractResponse(extractId, typeName, ApiDBUtils.findAccountById(accountId).getUuid(), Status.NOT_UPLOADED.toString(), + ApiDBUtils.findUploadById(uploadId).getUuid()); resultObj.setResponseName(responseNameMap.get(type.toString())); updateDatabase(Status.NOT_UPLOADED, cmd.getUrl(),""); } - + public UploadListener(UploadMonitorImpl monitor) { uploadMonitor = monitor; - } - + } + public void checkProgress() { transition(UploadEvent.TIMEOUT_CHECK, null); } @@ -206,15 +214,15 @@ public class UploadListener implements Listener { public void setCommand(UploadCommand _cmd) { this.cmd = _cmd; } - + public void setJobId(String _jobId) { this.jobId = _jobId; } - + public String getJobId() { return jobId; } - + @Override public boolean processAnswers(long agentId, long seq, Answer[] answers) { boolean processed = false; @@ -232,7 +240,7 @@ public class UploadListener implements Listener { } return processed; } - + @Override public boolean processCommands(long agentId, long seq, Command[] commands) { @@ -240,13 +248,13 @@ public class UploadListener implements Listener { } @Override - public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) { + public void processConnect(HostVO agent, StartupCommand cmd, boolean forRebalance) { if (!(cmd instanceof StartupStorageCommand)) { return; } - + long agentId = agent.getId(); - + StartupStorageCommand storage = (StartupStorageCommand)cmd; if (storage.getResourceType() == Storage.StorageResourceType.STORAGE_HOST || storage.getResourceType() == Storage.StorageResourceType.SECONDARY_STORAGE ) @@ -260,35 +268,35 @@ public class UploadListener implements Listener { AgentControlCommand cmd) { return null; } - + public void setUploadInactive(Status reason) { uploadActive=false; uploadMonitor.handleUploadEvent(sserver, accountId, typeName, type, uploadId, reason, eventId); } - + public void logUploadStart() { //uploadMonitor.logEvent(accountId, event, "Storage server " + sserver.getName() + " started upload of " +type.toString() + " " + typeName, EventVO.LEVEL_INFO, eventId); } - + public void cancelTimeoutTask() { if (timeoutTask != null) timeoutTask.cancel(); } - + public void cancelStatusTask() { if (statusTask != null) statusTask.cancel(); } @Override - public boolean processDisconnect(long agentId, com.cloud.host.Status state) { + public boolean processDisconnect(long agentId, com.cloud.host.Status state) { setDisconnected(); return true; } @Override - public boolean processTimeout(long agentId, long seq) { + public boolean processTimeout(long agentId, long seq) { return true; } - + private void initStateMachine() { stateMap.put(Status.NOT_UPLOADED.toString(), new NotUploadedState(this)); stateMap.put(Status.UPLOADED.toString(), new UploadCompleteState(this)); @@ -296,7 +304,7 @@ public class UploadListener implements Listener { stateMap.put(Status.UPLOAD_IN_PROGRESS.toString(), new UploadInProgressState(this)); stateMap.put(Status.ABANDONED.toString(), new UploadAbandonedState(this)); } - + private UploadState getState(String stateName) { return stateMap.get(stateName); } @@ -318,15 +326,15 @@ public class UploadListener implements Listener { throw new CloudRuntimeException("Unhandled event transition: currState="+prevName+", evt="+event); } } - + public Date getLastUpdated() { return lastUpdated; } - + public void setLastUpdated() { lastUpdated = new Date(); } - + public void log(String message, Level level) { s_logger.log(level, message + ", " + type.toString() + " = " + typeName + " at host " + sserver.getName()); } @@ -334,7 +342,7 @@ public class UploadListener implements Listener { public void setDisconnected() { transition(UploadEvent.DISCONNECT, null); } - + public void scheduleStatusCheck(com.cloud.agent.api.storage.UploadProgressCommand.RequestType getStatus) { if (statusTask != null) statusTask.cancel(); @@ -351,27 +359,27 @@ public class UploadListener implements Listener { log("Scheduling timeout at " + delay + " ms", Level.DEBUG); } } - + public void updateDatabase(Status state, String uploadErrorString) { resultObj.setResultString(uploadErrorString); resultObj.setState(state.toString()); asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); - + UploadVO vo = uploadDao.createForUpdate(); vo.setUploadState(state); vo.setLastUpdated(new Date()); vo.setErrorString(uploadErrorString); uploadDao.update(getUploadId(), vo); } - + public void updateDatabase(Status state, String uploadUrl,String uploadErrorString) { resultObj.setResultString(uploadErrorString); resultObj.setState(state.toString()); asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); - - + + UploadVO vo = uploadDao.createForUpdate(); vo.setUploadState(state); vo.setLastUpdated(new Date()); @@ -379,23 +387,23 @@ public class UploadListener implements Listener { vo.setJobId(null); vo.setUploadPercent(0); vo.setErrorString(uploadErrorString); - + uploadDao.update(getUploadId(), vo); } - + private Long getUploadId() { return uploadId; } - public synchronized void updateDatabase(UploadAnswer answer) { - + public synchronized void updateDatabase(UploadAnswer answer) { + if(answer.getErrorString().startsWith("553")){ answer.setErrorString(answer.getErrorString().concat("Please check if the file name already exists.")); } resultObj.setResultString(answer.getErrorString()); resultObj.setState(answer.getUploadStatus().toString()); resultObj.setUploadPercent(answer.getUploadPct()); - + if (answer.getUploadStatus() == Status.UPLOAD_IN_PROGRESS){ asyncMgr.updateAsyncJobAttachment(asyncJobId, type.toString(), 1L); asyncMgr.updateAsyncJobStatus(asyncJobId, AsyncJobResult.STATUS_IN_PROGRESS, resultObj); @@ -411,7 +419,7 @@ public class UploadListener implements Listener { updateBuilder.setLastUpdated(new Date()); updateBuilder.setErrorString(answer.getErrorString()); updateBuilder.setJobId(answer.getJobId()); - + uploadDao.update(getUploadId(), updateBuilder); } @@ -427,9 +435,9 @@ public class UploadListener implements Listener { setDisconnected(); } } - + } - + private UploadCommand getCommand() { return cmd; } @@ -437,7 +445,7 @@ public class UploadListener implements Listener { public void logDisconnect() { s_logger.warn("Unable to monitor upload progress of " + typeName + " at host " + sserver.getName()); } - + public void scheduleImmediateStatusCheck(RequestType request) { if (statusTask != null) statusTask.cancel(); statusTask = new StatusTask(this, request); @@ -445,6 +453,6 @@ public class UploadListener implements Listener { } public void setCurrState(Status uploadState) { - this.currState = getState(currState.toString()); + this.currState = getState(currState.toString()); } } diff --git a/server/src/com/cloud/tags/ResourceTagVO.java b/server/src/com/cloud/tags/ResourceTagVO.java index 4a4a22b44ae..04ae757bf75 100644 --- a/server/src/com/cloud/tags/ResourceTagVO.java +++ b/server/src/com/cloud/tags/ResourceTagVO.java @@ -27,13 +27,14 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.server.ResourceTag; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="resource_tags") -public class ResourceTagVO implements Identity, ResourceTag{ +public class ResourceTagVO implements ResourceTag { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) diff --git a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java index 020b163fed6..a5fb8a0bcac 100644 --- a/server/src/com/cloud/tags/TaggedResourceManagerImpl.java +++ b/server/src/com/cloud/tags/TaggedResourceManagerImpl.java @@ -25,10 +25,13 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.tag.ListTagsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ListTagsCmd; + +import com.cloud.api.query.dao.ResourceTagJoinDao; +import com.cloud.api.query.vo.ResourceTagJoinVO; import com.cloud.domain.Domain; import com.cloud.event.ActionEvent; import com.cloud.event.EventTypes; @@ -85,6 +88,8 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager @Inject ResourceTagDao _resourceTagDao; @Inject + ResourceTagJoinDao _resourceTagJoinDao; + @Inject IdentityDao _identityDao; @Inject DomainManager _domainMgr; @@ -323,69 +328,6 @@ public class TaggedResourceManagerImpl implements TaggedResourceService, Manager return identiyUUId; } - @Override - public List listTags(ListTagsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String key = cmd.getKey(); - String value = cmd.getValue(); - String resourceId = cmd.getResourceId(); - String resourceType = cmd.getResourceType(); - String customerName = cmd.getCustomer(); - boolean listAll = cmd.listAll(); - - Ternary domainIdRecursiveListProject = - new Ternary(cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, null, cmd.getAccountName(), - cmd.getProjectId(), permittedAccounts, domainIdRecursiveListProject, listAll, false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject.third(); - Filter searchFilter = new Filter(ResourceTagVO.class, "resourceType", false, cmd.getStartIndex(), cmd.getPageSizeVal()); - - SearchBuilder sb = _resourceTagDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - sb.and("key", sb.entity().getKey(), SearchCriteria.Op.EQ); - sb.and("value", sb.entity().getValue(), SearchCriteria.Op.EQ); - - if (resourceId != null) { - sb.and().op("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.EQ); - sb.or("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.EQ); - sb.cp(); - } - - sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); - sb.and("customer", sb.entity().getCustomer(), SearchCriteria.Op.EQ); - - // now set the SC criteria... - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - - if (key != null) { - sc.setParameters("key", key); - } - - if (value != null) { - sc.setParameters("value", value); - } - - if (resourceId != null) { - sc.setParameters("resourceId", resourceId); - sc.setParameters("resourceUuid", resourceId); - } - - if (resourceType != null) { - sc.setParameters("resourceType", resourceType); - } - - if (customerName != null) { - sc.setParameters("customer", customerName); - } - - return _resourceTagDao.search(sc, searchFilter); - } - @Override @DB @ActionEvent(eventType = EventTypes.EVENT_TAGS_DELETE, eventDescription = "deleting resource tags") diff --git a/server/src/com/cloud/template/HyervisorTemplateAdapter.java b/server/src/com/cloud/template/HyervisorTemplateAdapter.java index 8cb6bd1c524..732b153bb51 100755 --- a/server/src/com/cloud/template/HyervisorTemplateAdapter.java +++ b/server/src/com/cloud/template/HyervisorTemplateAdapter.java @@ -26,16 +26,16 @@ import java.util.List; import javax.ejb.Local; import javax.inject.Inject; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.storage.DeleteTemplateCommand; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.dc.DataCenterVO; import com.cloud.event.EventTypes; 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/TemplateAdapter.java b/server/src/com/cloud/template/TemplateAdapter.java index 0a1293bca20..19cfef039de 100755 --- a/server/src/com/cloud/template/TemplateAdapter.java +++ b/server/src/com/cloud/template/TemplateAdapter.java @@ -18,10 +18,10 @@ package com.cloud.template; import java.util.Map; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.exception.ResourceAllocationException; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.storage.TemplateProfile; diff --git a/server/src/com/cloud/template/TemplateAdapterBase.java b/server/src/com/cloud/template/TemplateAdapterBase.java index 781e0c00b7a..d0a0ec207b6 100755 --- a/server/src/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/com/cloud/template/TemplateAdapterBase.java @@ -22,14 +22,14 @@ import java.util.Map; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.user.iso.DeleteIsoCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import org.apache.log4j.Logger; -import com.cloud.api.ApiConstants; +import org.apache.cloudstack.api.ApiConstants; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; +import org.apache.cloudstack.api.command.user.template.DeleteTemplateCmd; import com.cloud.configuration.Resource.ResourceType; import com.cloud.configuration.dao.ConfigurationDao; import com.cloud.dc.DataCenterVO; diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 289bcf94dd2..7cce9a764b7 100755 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -35,10 +35,14 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.BaseListTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.BaseUpdateTemplateOrIsoPermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.*; +import org.apache.cloudstack.api.command.user.template.*; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.agent.AgentManager; import com.cloud.agent.api.Answer; import com.cloud.agent.api.downloadTemplateFromSwiftToSecondaryStorageCommand; @@ -47,19 +51,8 @@ import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.to.SwiftTO; -import com.cloud.api.commands.CopyTemplateCmd; -import com.cloud.api.commands.DeleteIsoCmd; -import com.cloud.api.commands.DeleteTemplateCmd; -import com.cloud.api.commands.ExtractIsoCmd; -import com.cloud.api.commands.ExtractTemplateCmd; -import com.cloud.api.commands.ListIsoPermissionsCmd; -import com.cloud.api.commands.ListTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.ListTemplatePermissionsCmd; -import com.cloud.api.commands.RegisterIsoCmd; -import com.cloud.api.commands.RegisterTemplateCmd; -import com.cloud.api.commands.UpdateIsoPermissionsCmd; -import com.cloud.api.commands.UpdateTemplateOrIsoPermissionsCmd; -import com.cloud.api.commands.UpdateTemplatePermissionsCmd; +import org.apache.cloudstack.api.command.user.iso.RegisterIsoCmd; +import org.apache.cloudstack.api.command.user.template.RegisterTemplateCmd; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; import com.cloud.configuration.Config; @@ -116,10 +109,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; @@ -181,8 +176,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; @@ -209,6 +208,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe ExecutorService _preloadExecutor; ScheduledExecutorService _swiftTemplateSyncExecutor; + private ScheduledExecutorService _s3TemplateSyncExecutor = null; @Inject protected List _adapters; @@ -346,10 +346,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."); } @@ -382,7 +386,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 "); } @@ -596,6 +606,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."); @@ -646,7 +662,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()); @@ -710,6 +726,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."); @@ -825,6 +847,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."); @@ -1005,12 +1033,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; } @@ -1043,6 +1091,15 @@ 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")); + + if (_s3Mgr.isS3Enabled()) { + _s3TemplateSyncExecutor = Executors + .newSingleThreadScheduledExecutor(new NamedThreadFactory( + "s3-template-sync")); + } else { + s_logger.info("S3 secondary storage synchronization is disabled."); + } + return false; } @@ -1197,13 +1254,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()); @@ -1236,6 +1299,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."); } @@ -1243,8 +1310,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()); @@ -1268,7 +1337,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe } @Override - public List listTemplatePermissions(ListTemplateOrIsoPermissionsCmd cmd) { + public List listTemplatePermissions(BaseListTemplateOrIsoPermissionsCmd cmd) { Account caller = UserContext.current().getCaller(); Long id = cmd.getId(); @@ -1308,7 +1377,7 @@ public class TemplateManagerImpl implements TemplateManager, Manager, TemplateSe @DB @Override - public boolean updateTemplateOrIsoPermissions(UpdateTemplateOrIsoPermissionsCmd cmd) { + public boolean updateTemplateOrIsoPermissions(BaseUpdateTemplateOrIsoPermissionsCmd cmd) { Transaction txn = Transaction.currentTxn(); // Input validation diff --git a/server/src/com/cloud/test/DatabaseConfig.java b/server/src/com/cloud/test/DatabaseConfig.java index dfdea657532..03cf083b610 100755 --- a/server/src/com/cloud/test/DatabaseConfig.java +++ b/server/src/com/cloud/test/DatabaseConfig.java @@ -1090,7 +1090,8 @@ public class DatabaseConfig { } // insert system user - insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created) VALUES (1, 'system', '', 1, 'system', 'cloud', now())"; + insertSql = "INSERT INTO `cloud`.`user` (id, username, password, account_id, firstname, lastname, created)" + + " VALUES (1, 'system', RAND(), 1, 'system', 'cloud', now())"; txn = Transaction.currentTxn(); try { PreparedStatement stmt = txn.prepareAutoCloseStatement(insertSql); diff --git a/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java b/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java index 8c4dbecd905..88370c10c8c 100755 --- a/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade2214to30.java @@ -161,9 +161,17 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { pstmtUpdate.setLong(2, zoneId); pstmtUpdate.executeUpdate(); pstmtUpdate.close(); - - //check if there are multiple guest networks configured using network_tags + //check if public network needs to be created + boolean crtPbNtwk = false; + pstmt = conn.prepareStatement("SELECT * FROM `cloud`.`networks` where traffic_type=\"public\" and data_center_id=?"); + pstmt.setLong(1, zoneId); + ResultSet rs1 = pstmt.executeQuery(); + if (rs1.next()) { + crtPbNtwk = true; + } + + //check if there are multiple guest networks configured using network_tags PreparedStatement pstmt2 = conn.prepareStatement("SELECT distinct tag FROM `cloud`.`network_tags` t JOIN `cloud`.`networks` n ON t.network_id = n.id WHERE n.data_center_id = ? and n.removed IS NULL"); pstmt2.setLong(1, zoneId); ResultSet rsTags = pstmt2.executeQuery(); @@ -235,7 +243,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { long physicalNetworkId = addPhysicalNetworkToZone(conn, zoneId, zoneName, networkType, (isFirstPhysicalNtwk) ? vnet : null, domainId); //add Traffic types if(isFirstPhysicalNtwk){ - addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); + if (crtPbNtwk) { + addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); + } else { + s_logger.debug("Skip adding public traffic type to zone id=" + zoneId); + } addTrafficType(conn, physicalNetworkId, "Management", xenPrivateLabel, kvmPrivateLabel, vmwarePrivateLabel); addTrafficType(conn, physicalNetworkId, "Storage", xenStorageLabel, null, null); } @@ -270,7 +282,11 @@ public class Upgrade2214to30 extends Upgrade30xBase implements DbUpgrade { //default to one physical network long physicalNetworkId = addPhysicalNetworkToZone(conn, zoneId, zoneName, networkType, vnet, domainId); // add traffic types - addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); + if (crtPbNtwk) { + addTrafficType(conn, physicalNetworkId, "Public", xenPublicLabel, kvmPublicLabel, vmwarePublicLabel); + } else { + s_logger.debug("Skip adding public traffic type to zone id=" + zoneId); + } addTrafficType(conn, physicalNetworkId, "Management", xenPrivateLabel, kvmPrivateLabel, vmwarePrivateLabel); addTrafficType(conn, physicalNetworkId, "Storage", xenStorageLabel, null, null); addTrafficType(conn, physicalNetworkId, "Guest", xenGuestLabel, kvmGuestLabel, vmwareGuestLabel); diff --git a/server/src/com/cloud/upgrade/dao/Upgrade30xBase.java b/server/src/com/cloud/upgrade/dao/Upgrade30xBase.java index 585e08673b8..36ae3c548b7 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade30xBase.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade30xBase.java @@ -193,11 +193,8 @@ public abstract class Upgrade30xBase implements DbUpgrade{ pstmtUpdate.setString(1, UUID.randomUUID().toString()); pstmtUpdate.setLong(2, physicalNetworkId); pstmtUpdate.setString(3, "SecurityGroupProvider"); - if ("Advanced".equals(networkType)) { - pstmtUpdate.setString(4, "Disabled"); - }else{ - pstmtUpdate.setString(4, "Enabled"); - } + pstmtUpdate.setString(4, "Enabled"); + pstmtUpdate.executeUpdate(); pstmtUpdate.close(); } diff --git a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java index 90f9e1723f3..e23837d49f8 100644 --- a/server/src/com/cloud/upgrade/dao/Upgrade40to41.java +++ b/server/src/com/cloud/upgrade/dao/Upgrade40to41.java @@ -17,67 +17,114 @@ 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; /** * @author htrippaers * */ -public class Upgrade40to41 extends Upgrade30xBase implements DbUpgrade { +public class Upgrade40to41 implements DbUpgrade { - /** - * - */ - public Upgrade40to41() { - // TODO Auto-generated constructor stub + /** + * + */ + public Upgrade40to41() { + // TODO Auto-generated constructor stub + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#getUpgradableVersionRange() + */ + @Override + public String[] getUpgradableVersionRange() { + return new String[] { "4.0.0", "4.1.0" }; + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#getUpgradedVersion() + */ + @Override + public String getUpgradedVersion() { + return "4.1.0"; + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#supportsRollingUpgrade() + */ + @Override + public boolean supportsRollingUpgrade() { + return false; + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#getPrepareScripts() + */ + @Override + public File[] getPrepareScripts() { + String script = Script.findScript("", "db/schema-40to410.sql"); + if (script == null) { + throw new CloudRuntimeException("Unable to find db/schema-40to410.sql"); + } + + return new File[] { new File(script) }; + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#performDataMigration(java.sql.Connection) + */ + @Override + public void performDataMigration(Connection conn) { + upgradeEIPNetworkOfferings(conn); + } + + /* (non-Javadoc) + * @see com.cloud.upgrade.dao.DbUpgrade#getCleanupScripts() + */ + @Override + public File[] getCleanupScripts() { + 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) { + } + } } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#getUpgradableVersionRange() - */ - @Override - public String[] getUpgradableVersionRange() { - return new String[] { "4.0.0", "4.1.0" }; - } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#getUpgradedVersion() - */ - @Override - public String getUpgradedVersion() { - return "4.1.0"; - } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#supportsRollingUpgrade() - */ - @Override - public boolean supportsRollingUpgrade() { - return false; - } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#getPrepareScripts() - */ - @Override - public File[] getPrepareScripts() { - return new File[0]; - } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#performDataMigration(java.sql.Connection) - */ - @Override - public void performDataMigration(Connection conn) { - } - - /* (non-Javadoc) - * @see com.cloud.upgrade.dao.DbUpgrade#getCleanupScripts() - */ - @Override - public File[] getCleanupScripts() { - return new File[0]; - } - } diff --git a/server/src/com/cloud/upgrade/dao/VersionVO.java b/server/src/com/cloud/upgrade/dao/VersionVO.java index ed707c56f51..b5e3f355e24 100644 --- a/server/src/com/cloud/upgrade/dao/VersionVO.java +++ b/server/src/com/cloud/upgrade/dao/VersionVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.upgrade.dao; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -31,7 +33,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="version") -public class VersionVO { +public class VersionVO implements InternalIdentity { public enum Step { Upgrade, Complete diff --git a/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java b/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java index f9c034a9400..7ad933c2b8c 100644 --- a/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java +++ b/server/src/com/cloud/usage/ExternalPublicIpStatisticsVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import javax.persistence.Column; import javax.persistence.DiscriminatorValue; import javax.persistence.Entity; @@ -28,7 +30,7 @@ import javax.persistence.Table; @Entity @Table(name="external_public_ip_statistics") @PrimaryKeyJoinColumn(name="id") -public class ExternalPublicIpStatisticsVO { +public class ExternalPublicIpStatisticsVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @@ -61,7 +63,7 @@ public class ExternalPublicIpStatisticsVO { this.currentBytesSent = 0; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageIPAddressVO.java b/server/src/com/cloud/usage/UsageIPAddressVO.java index 8e68182ad5a..a11dfe2b4b6 100644 --- a/server/src/com/cloud/usage/UsageIPAddressVO.java +++ b/server/src/com/cloud/usage/UsageIPAddressVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_ip_address") -public class UsageIPAddressVO { +public class UsageIPAddressVO implements InternalIdentity { @Column(name="account_id") private long accountId; diff --git a/server/src/com/cloud/usage/UsageJobVO.java b/server/src/com/cloud/usage/UsageJobVO.java index 174b6a32150..7761e871665 100644 --- a/server/src/com/cloud/usage/UsageJobVO.java +++ b/server/src/com/cloud/usage/UsageJobVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_job") -public class UsageJobVO { +public class UsageJobVO implements InternalIdentity { public static final int JOB_TYPE_RECURRING = 0; public static final int JOB_TYPE_SINGLE = 1; @@ -80,7 +82,7 @@ public class UsageJobVO { public UsageJobVO() {} - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java index 3ed9a631c1f..e952b1ade0a 100644 --- a/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java +++ b/server/src/com/cloud/usage/UsageLoadBalancerPolicyVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_load_balancer_policy") -public class UsageLoadBalancerPolicyVO { +public class UsageLoadBalancerPolicyVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java index cc0cd433c28..641ae76071c 100644 --- a/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java +++ b/server/src/com/cloud/usage/UsagePortForwardingRuleVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_port_forwarding") -public class UsagePortForwardingRuleVO { +public class UsagePortForwardingRuleVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsageStorageVO.java b/server/src/com/cloud/usage/UsageStorageVO.java index bf2ee158831..1337edc3d59 100644 --- a/server/src/com/cloud/usage/UsageStorageVO.java +++ b/server/src/com/cloud/usage/UsageStorageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_storage") -public class UsageStorageVO { +public class UsageStorageVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/usage/UsageTypes.java b/server/src/com/cloud/usage/UsageTypes.java index af77c323451..e5a48d5c143 100644 --- a/server/src/com/cloud/usage/UsageTypes.java +++ b/server/src/com/cloud/usage/UsageTypes.java @@ -19,7 +19,7 @@ package com.cloud.usage; import java.util.ArrayList; import java.util.List; -import com.cloud.server.api.response.UsageTypeResponse; +import org.apache.cloudstack.api.response.UsageTypeResponse; public class UsageTypes { public static final int RUNNING_VM = 1; diff --git a/server/src/com/cloud/usage/UsageVO.java b/server/src/com/cloud/usage/UsageVO.java index 2e816ffdba3..bcb9c2d6363 100644 --- a/server/src/com/cloud/usage/UsageVO.java +++ b/server/src/com/cloud/usage/UsageVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -29,7 +31,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="cloud_usage") -public class UsageVO { +public class UsageVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") @@ -165,7 +167,7 @@ public class UsageVO { this.endDate = endDate; } - public Long getId() { + public long getId() { return id; } diff --git a/server/src/com/cloud/usage/UsageVolumeVO.java b/server/src/com/cloud/usage/UsageVolumeVO.java index 1e003720ae8..4ba88984fa5 100644 --- a/server/src/com/cloud/usage/UsageVolumeVO.java +++ b/server/src/com/cloud/usage/UsageVolumeVO.java @@ -16,6 +16,8 @@ // under the License. package com.cloud.usage; +import org.apache.cloudstack.api.InternalIdentity; + import java.util.Date; import javax.persistence.Column; @@ -26,7 +28,7 @@ import javax.persistence.TemporalType; @Entity @Table(name="usage_volume") -public class UsageVolumeVO { +public class UsageVolumeVO implements InternalIdentity { @Column(name="zone_id") private long zoneId; diff --git a/server/src/com/cloud/user/AccountDetailVO.java b/server/src/com/cloud/user/AccountDetailVO.java index 76c87b11107..a8afadba3fc 100755 --- a/server/src/com/cloud/user/AccountDetailVO.java +++ b/server/src/com/cloud/user/AccountDetailVO.java @@ -24,10 +24,11 @@ import javax.persistence.Id; import javax.persistence.Table; import com.cloud.utils.db.Encrypt; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name="account_details") -public class AccountDetailVO { +public class AccountDetailVO implements InternalIdentity { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id") diff --git a/server/src/com/cloud/user/AccountManager.java b/server/src/com/cloud/user/AccountManager.java index 90a34ad82b3..9ca4721187c 100755 --- a/server/src/com/cloud/user/AccountManager.java +++ b/server/src/com/cloud/user/AccountManager.java @@ -19,11 +19,9 @@ package com.cloud.user; import java.util.List; import java.util.Map; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.domain.Domain; +import org.apache.cloudstack.acl.ControlledEntity; +import com.cloud.api.query.vo.ControlledViewEntity; import com.cloud.exception.ConcurrentOperationException; -import com.cloud.exception.PermissionDeniedException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.Project.ListProjectResourcesCriteria; import com.cloud.utils.Pair; @@ -93,9 +91,15 @@ public interface AccountManager extends AccountService { void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria); + void buildACLSearchParameters(Account caller, Long id, String accountName, Long projectId, List permittedAccounts, Ternary domainIdRecursiveListProject, boolean listAll, boolean forProjectInvitation); diff --git a/server/src/com/cloud/user/AccountManagerImpl.java b/server/src/com/cloud/user/AccountManagerImpl.java index d0ae74828e6..47b47470fe6 100755 --- a/server/src/com/cloud/user/AccountManagerImpl.java +++ b/server/src/com/cloud/user/AccountManagerImpl.java @@ -37,20 +37,22 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.SecurityChecker; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker; -import com.cloud.acl.SecurityChecker.AccessType; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; import com.cloud.api.ApiDBUtils; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import com.cloud.api.query.dao.UserAccountJoinDao; +import com.cloud.api.query.vo.ControlledViewEntity; + + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; import com.cloud.configuration.Config; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ResourceLimit; @@ -76,15 +78,11 @@ import com.cloud.network.IpAddress; import com.cloud.network.NetworkManager; import com.cloud.network.NetworkVO; import com.cloud.network.RemoteAccessVpnVO; -import com.cloud.network.Site2SiteCustomerGatewayVO; -import com.cloud.network.Site2SiteVpnConnectionVO; import com.cloud.network.VpnUserVO; +import com.cloud.network.as.AutoScaleManager; import com.cloud.network.dao.IPAddressDao; import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.RemoteAccessVpnDao; -import com.cloud.network.dao.Site2SiteCustomerGatewayDao; -import com.cloud.network.dao.Site2SiteVpnConnectionDao; -import com.cloud.network.dao.Site2SiteVpnGatewayDao; import com.cloud.network.dao.VpnUserDao; import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.dao.SecurityGroupDao; @@ -122,7 +120,6 @@ import com.cloud.utils.component.ComponentLocator; 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.GlobalLock; import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; @@ -162,6 +159,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag @Inject private UserAccountDao _userAccountDao; @Inject + private UserAccountJoinDao _userAccountJoinDao; + @Inject private VolumeDao _volumeDao; @Inject private UserVmDao _userVmDao; @@ -221,6 +220,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag private DomainRouterDao _routerDao; @Inject Site2SiteVpnManager _vpnMgr; + @Inject + private AutoScaleManager _autoscaleMgr; @Inject private List _userAuthenticators; @@ -576,7 +577,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag for (VolumeVO volume : volumes) { if (!volume.getState().equals(Volume.State.Destroy)) { try { - _storageMgr.deleteVolume(volume.getId()); + _storageMgr.deleteVolume(volume.getId(), caller); } catch (Exception ex) { s_logger.warn("Failed to cleanup volumes as a part of account id=" + accountId + " cleanup due to Exception: ", ex); accountCleanupNeeded = true; @@ -589,12 +590,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag List vpnUsers = _vpnUser.listByAccount(accountId); for (VpnUserVO vpnUser : vpnUsers) { - _remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername()); + _remoteAccessVpnMgr.removeVpnUser(accountId, vpnUser.getUsername(), caller); } try { for (RemoteAccessVpnVO vpn : remoteAccessVpns) { - _remoteAccessVpnMgr.destroyRemoteAccessVpn(vpn.getServerAddressId()); + _remoteAccessVpnMgr.destroyRemoteAccessVpn(vpn.getServerAddressId(), caller); } } catch (ResourceUnavailableException ex) { s_logger.warn("Failed to cleanup remote access vpn resources as a part of account id=" + accountId + " cleanup due to Exception: ", ex); @@ -612,7 +613,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (networks != null) { for (NetworkVO network : networks) { - ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), account); + ReservationContext context = new ReservationContextImpl(null, null, getActiveUser(callerUserId), caller); if (!_networkMgr.destroyNetwork(network.getId(), context)) { s_logger.warn("Unable to destroy network " + network + " as a part of account id=" + accountId + " cleanup."); @@ -630,7 +631,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag List vpcs = _vpcMgr.getVpcsForAccount(account.getId()); for (Vpc vpc : vpcs) { - if (!_vpcMgr.destroyVpc(vpc)) { + if (!_vpcMgr.destroyVpc(vpc, caller, callerUserId)) { s_logger.warn("Unable to destroy VPC " + vpc + " as a part of account id=" + accountId + " cleanup."); accountCleanupNeeded = true; vpcsDeleted = false; @@ -657,6 +658,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag s_logger.warn("Fail to delete site-to-site VPN customer gateways for account " + accountId); } + // Delete autoscale resources if any + try { + _autoscaleMgr.cleanUpAutoScaleResources(accountId); + } catch (CloudRuntimeException ex) { + s_logger.warn("Failed to cleanup AutoScale resources as a part of account id=" + accountId + " cleanup due to exception:", ex); + accountCleanupNeeded = true; + } + // delete account specific Virtual vlans (belong to system Public Network) - only when networks are cleaned // up successfully if (networksDeleted) { @@ -750,6 +759,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // ////////////// API commands ///////////////////// // /////////////////////////////////////////////////// + @Override @DB @ActionEvent(eventType = EventTypes.EVENT_ACCOUNT_CREATE, eventDescription = "creating Account") @@ -839,6 +849,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("Unable to find account " + accountName + " in domain id=" + domainId + " to create user"); } + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new PermissionDeniedException("Account id : " + account.getId() + " is a system account, can't add a user to it"); + } + if (!_userAccountDao.validateUsernameInDomain(userName, domainId)) { throw new CloudRuntimeException("The user " + userName + " already exists in domain " + domainId); } @@ -880,6 +894,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("unable to find user by id"); } + //don't allow updating system account if (account != null && (account.getId() == Account.ACCOUNT_ID_SYSTEM)) { throw new PermissionDeniedException("user id : " + id + " is system account, update is not allowed"); } @@ -920,7 +935,18 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (password != null) { - user.setPassword(password); + String encodedPassword = null; + for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { + UserAuthenticator authenticator = en.nextElement(); + encodedPassword = authenticator.encode(password); + if (encodedPassword != null) { + break; + } + } + if (encodedPassword == null) { + throw new CloudRuntimeException("Failed to encode password"); + } + user.setPassword(encodedPassword); } if (email != null) { user.setEmail(email); @@ -1158,9 +1184,8 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - // Don't allow to modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Can not modify system account"); + throw new PermissionDeniedException("Account id : " + accountId + " is a system account, enable is not allowed"); } // Check if user performing the action is allowed to modify this account @@ -1191,13 +1216,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("Unable to find active account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } - checkAccess(caller, null, true, account); - - // don't allow modify system account if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("can not lock system account"); + throw new PermissionDeniedException("Account id : " + accountId + " is a system account, lock is not allowed"); } + checkAccess(caller, null, true, account); + if (lockAccount(account.getId())) { return _accountDao.findById(account.getId()); } else { @@ -1221,6 +1245,10 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag throw new InvalidParameterValueException("Unable to find account by accountId: " + accountId + " OR by name: " + accountName + " in domain " + domainId); } + if (account.getId() == Account.ACCOUNT_ID_SYSTEM) { + throw new PermissionDeniedException("Account id : " + accountId + " is a system account, disable is not allowed"); + } + checkAccess(caller, null, true, account); if (disableAccount(account.getId())) { @@ -1562,7 +1590,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // set project information if (projectId != null) { - if (projectId == -1) { + if (projectId.longValue() == -1) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); } else { permittedAccounts.clear(); @@ -1667,7 +1695,20 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag if (s_logger.isDebugEnabled()) { s_logger.debug("Creating user: " + userName + ", accountId: " + accountId + " timezone:" + timezone); } - UserVO user = _userDao.persist(new UserVO(accountId, userName, password, firstName, lastName, email, timezone)); + + String encodedPassword = null; + for (Enumeration en = _userAuthenticators.enumeration(); en.hasMoreElements();) { + UserAuthenticator authenticator = en.nextElement(); + encodedPassword = authenticator.encode(password); + if (encodedPassword != null) { + break; + } + } + if (encodedPassword == null) { + throw new CloudRuntimeException("Failed to encode password"); + } + + UserVO user = _userDao.persist(new UserVO(accountId, userName, encodedPassword, firstName, lastName, email, timezone)); return user; } @@ -1712,7 +1753,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag String singleSignOnTolerance = _configDao.getValue("security.singlesignon.tolerance.millis"); if (singleSignOnTolerance == null) { // the SSO tolerance is gone (how much time before/after system time we'll allow the login request to be -// valid), + // valid), // don't authenticate return null; } @@ -1797,6 +1838,12 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } if (user != null) { + //don't allow to authenticate system user + if (user.getId() == User.UID_SYSTEM) { + s_logger.error("Failed to authenticate user: " + username + " in domain " + domainId); + return null; + } + if (s_logger.isDebugEnabled()) { s_logger.debug("User: " + username + " in domain " + domainId + " has successfully logged in"); } @@ -1893,8 +1940,14 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag public String[] createApiKeyAndSecretKey(RegisterCmd cmd) { Long userId = cmd.getId(); - if (getUserIncludingRemoved(userId) == null) { - throw new InvalidParameterValueException("unable to find user for id : " + userId); + User user = getUserIncludingRemoved(userId); + if (user == null) { + throw new InvalidParameterValueException("unable to find user by id"); + } + + //don't allow updating system user + if (user.getId() == User.UID_SYSTEM) { + throw new PermissionDeniedException("user id : " + user.getId() + " is system account, update is not allowed"); } // generate both an api key and a secret key, update the user table with the keys, return the keys to the user @@ -1963,221 +2016,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag return null; } - @Override - public List searchForAccounts(ListAccountsCmd cmd) { - Account caller = UserContext.current().getCaller(); - Long domainId = cmd.getDomainId(); - Long accountId = cmd.getId(); - String accountName = cmd.getSearchName(); - boolean isRecursive = cmd.isRecursive(); - boolean listAll = cmd.listAll(); - Boolean listForDomain = false; - if (accountId != null) { - Account account = _accountDao.findById(accountId); - if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by id " + accountId); - } - - checkAccess(caller, null, true, account); - } - - if (domainId != null) { - Domain domain = _domainMgr.getDomain(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Domain id=" + domainId + " doesn't exist"); - } - - checkAccess(caller, domain); - - if (accountName != null) { - Account account = _accountDao.findActiveAccount(accountName, domainId); - if (account == null || account.getId() == Account.ACCOUNT_ID_SYSTEM) { - throw new InvalidParameterValueException("Unable to find account by name " + accountName + " in domain " + domainId); - } - checkAccess(caller, null, true, account); - } - } - - if (accountId == null) { - if (isAdmin(caller.getType()) && listAll && domainId == null) { - listForDomain = true; - isRecursive = true; - if (domainId == null) { - domainId = caller.getDomainId(); - } - } else if (isAdmin(caller.getType()) && domainId != null) { - listForDomain = true; - } else { - accountId = caller.getAccountId(); - } - } - - Filter searchFilter = new Filter(AccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - Object type = cmd.getAccountType(); - Object state = cmd.getState(); - Object isCleanupRequired = cmd.isCleanupRequired(); - Object keyword = cmd.getKeyword(); - - SearchBuilder sb = _accountDao.createSearchBuilder(); - sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - sb.and("needsCleanup", sb.entity().getNeedsCleanup(), SearchCriteria.Op.EQ); - sb.and("typeNEQ", sb.entity().getType(), SearchCriteria.Op.NEQ); - sb.and("idNEQ", sb.entity().getId(), SearchCriteria.Op.NEQ); - - if (listForDomain && isRecursive) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - - sc.setParameters("idNEQ", Account.ACCOUNT_ID_SYSTEM); - - if (keyword != null) { - SearchCriteria ssc = _accountDao.createSearchCriteria(); - ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - sc.addAnd("accountName", SearchCriteria.Op.SC, ssc); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (state != null) { - sc.setParameters("state", state); - } - - if (isCleanupRequired != null) { - sc.setParameters("needsCleanup", isCleanupRequired); - } - - if (accountName != null) { - sc.setParameters("accountName", accountName); - } - - // don't return account of type project to the end user - sc.setParameters("typeNEQ", 5); - - if (accountId != null) { - sc.setParameters("id", accountId); - } - - if (listForDomain) { - DomainVO domain = _domainDao.findById(domainId); - if (isRecursive) { - sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); - } else { - sc.setParameters("domainId", domainId); - } - } - - return _accountDao.search(sc, searchFilter); - } - - @Override - public List searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { - Account caller = UserContext.current().getCaller(); - - Long domainId = cmd.getDomainId(); - if (domainId != null) { - Domain domain = _domainDao.findById(domainId); - if (domain == null) { - throw new InvalidParameterValueException("Unable to find domain by id=" + domainId); - } - - checkAccess(caller, domain); - } else { - // default domainId to the caller's domain - domainId = caller.getDomainId(); - } - - Filter searchFilter = new Filter(UserAccountVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - - Long id = cmd.getId(); - Object username = cmd.getUsername(); - Object type = cmd.getAccountType(); - Object accountName = cmd.getAccountName(); - Object state = cmd.getState(); - Object keyword = cmd.getKeyword(); - - SearchBuilder sb = _userAccountDao.createSearchBuilder(); - sb.and("username", sb.entity().getUsername(), SearchCriteria.Op.LIKE); - if (id != null && id == 1) { - // system user should NOT be searchable - List emptyList = new ArrayList(); - return emptyList; - } else if (id != null) { - sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); - } else { - // this condition is used to exclude system user from the search results - sb.and("id", sb.entity().getId(), SearchCriteria.Op.NEQ); - } - - sb.and("type", sb.entity().getType(), SearchCriteria.Op.EQ); - sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); - sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.EQ); - sb.and("state", sb.entity().getState(), SearchCriteria.Op.EQ); - - if ((accountName == null) && (domainId != null)) { - SearchBuilder domainSearch = _domainDao.createSearchBuilder(); - domainSearch.and("path", domainSearch.entity().getPath(), SearchCriteria.Op.LIKE); - sb.join("domainSearch", domainSearch, sb.entity().getDomainId(), domainSearch.entity().getId(), JoinBuilder.JoinType.INNER); - } - - SearchCriteria sc = sb.create(); - if (keyword != null) { - SearchCriteria ssc = _userAccountDao.createSearchCriteria(); - ssc.addOr("username", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("firstname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("lastname", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("email", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("state", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("accountName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("type", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - ssc.addOr("accountState", SearchCriteria.Op.LIKE, "%" + keyword + "%"); - - sc.addAnd("username", SearchCriteria.Op.SC, ssc); - } - - if (username != null) { - sc.setParameters("username", username); - } - - if (id != null) { - sc.setParameters("id", id); - } else { - // Don't return system user, search builder with NEQ - sc.setParameters("id", 1); - } - - if (type != null) { - sc.setParameters("type", type); - } - - if (accountName != null) { - sc.setParameters("accountName", accountName); - if (domainId != null) { - sc.setParameters("domainId", domainId); - } - } else if (domainId != null) { - DomainVO domainVO = _domainDao.findById(domainId); - sc.setJoinParameters("domainSearch", "path", domainVO.getPath() + "%"); - } - - if (state != null) { - sc.setParameters("state", state); - } - - return _userAccountDao.search(sc, searchFilter); - } @Override public void buildACLSearchBuilder(SearchBuilder sb, @@ -2285,7 +2124,7 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag // set project information if (projectId != null) { if (!forProjectInvitation) { - if (projectId == -1) { + if (projectId.longValue() == -1) { if (caller.getType() == Account.ACCOUNT_TYPE_NORMAL) { permittedAccounts.addAll(_projectMgr.listPermittedProjectAccounts(caller.getId())); } else { @@ -2328,6 +2167,49 @@ public class AccountManagerImpl implements AccountManager, AccountService, Manag } @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + sb.and("accountIdIN", sb.entity().getAccountId(), SearchCriteria.Op.IN); + sb.and("domainId", sb.entity().getDomainId(), SearchCriteria.Op.EQ); + + if (((permittedAccounts.isEmpty()) && (domainId != null) && isRecursive)) { + // if accountId isn't specified, we can do a domain match for the + // admin case if isRecursive is true + sb.and("domainPath", sb.entity().getDomainPath(), SearchCriteria.Op.LIKE); + } + + if (listProjectResourcesCriteria != null) { + if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.ListProjectResourcesOnly) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.EQ); + } else if (listProjectResourcesCriteria == Project.ListProjectResourcesCriteria.SkipProjectResources) { + sb.and("accountType", sb.entity().getAccountType(), SearchCriteria.Op.NEQ); + } + } + + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, + Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + + if (listProjectResourcesCriteria != null) { + sc.setParameters("accountType", Account.ACCOUNT_TYPE_PROJECT); + } + + if (!permittedAccounts.isEmpty()) { + sc.setParameters("accountIdIN", permittedAccounts.toArray()); + } else if (domainId != null) { + DomainVO domain = _domainDao.findById(domainId); + if (isRecursive) { + sc.setParameters("domainPath", domain.getPath() + "%"); + } else { + sc.setParameters("domainId", domainId); + } + } + } + + @Override public UserAccount getUserByApiKey(String apiKey) { return _userAccountDao.getUserByApiKey(apiKey); } diff --git a/server/src/com/cloud/user/DomainManagerImpl.java b/server/src/com/cloud/user/DomainManagerImpl.java index 8f69c22b316..15b8a114ae0 100644 --- a/server/src/com/cloud/user/DomainManagerImpl.java +++ b/server/src/com/cloud/user/DomainManagerImpl.java @@ -25,11 +25,11 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; import com.cloud.configuration.ResourceLimit; import com.cloud.configuration.dao.ResourceCountDao; import com.cloud.domain.Domain; @@ -49,6 +49,8 @@ import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.user.dao.AccountDao; +import com.cloud.utils.Pair; +import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; @@ -351,7 +353,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager } @Override - public List searchForDomains(ListDomainsCmd cmd) { + public Pair, Integer> searchForDomains(ListDomainsCmd cmd) { Account caller = UserContext.current().getCaller(); Long domainId = cmd.getId(); boolean listAll = cmd.listAll(); @@ -409,11 +411,12 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager // return only Active domains to the API sc.setParameters("state", Domain.State.Active); - return _domainDao.search(sc, searchFilter); + Pair, Integer> result = _domainDao.searchAndCount(sc, searchFilter); + return new Pair, Integer>(result.first(), result.second()); } @Override - public List searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException { + public Pair, Integer> searchForDomainChildren(ListDomainChildrenCmd cmd) throws PermissionDeniedException { Long domainId = cmd.getId(); String domainName = cmd.getDomainName(); Boolean isRecursive = cmd.isRecursive(); @@ -435,12 +438,12 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager } Filter searchFilter = new Filter(DomainVO.class, "id", true, cmd.getStartIndex(), cmd.getPageSizeVal()); - List domainList = searchForDomainChildren(searchFilter, domainId, domainName, keyword, path, true); + Pair, Integer> result = searchForDomainChildren(searchFilter, domainId, domainName, keyword, path, true); - return domainList; + return new Pair, Integer>(result.first(), result.second()); } - private List searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) { + private Pair, Integer> searchForDomainChildren(Filter searchFilter, Long domainId, String domainName, Object keyword, String path, boolean listActiveOnly) { SearchCriteria sc = _domainDao.createSearchCriteria(); if (keyword != null) { @@ -467,7 +470,7 @@ public class DomainManagerImpl implements DomainManager, DomainService, Manager sc.addAnd("state", SearchCriteria.Op.EQ, Domain.State.Active); } - return _domainDao.search(sc, searchFilter); + return _domainDao.searchAndCount(sc, searchFilter); } } diff --git a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java index 9cde212a964..a6edda2706d 100644 --- a/server/src/com/cloud/uuididentity/IdentityServiceImpl.java +++ b/server/src/com/cloud/uuididentity/IdentityServiceImpl.java @@ -22,10 +22,8 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.springframework.stereotype.Component; - -import com.cloud.api.IdentityMapper; -import com.cloud.api.IdentityService; +import org.apache.cloudstack.api.IdentityService; +import com.cloud.utils.component.Inject; import com.cloud.utils.component.Manager; import com.cloud.uuididentity.dao.IdentityDao; @@ -36,10 +34,6 @@ public class IdentityServiceImpl implements Manager, IdentityService { @Inject private IdentityDao _identityDao; - public Long getIdentityId(IdentityMapper mapper, String identityString) { - return _identityDao.getIdentityId(mapper, identityString); - } - public Long getIdentityId(String tableName, String identityString) { return _identityDao.getIdentityId(tableName, identityString); } diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDao.java b/server/src/com/cloud/uuididentity/dao/IdentityDao.java index e2758fbe88b..e9149a0fe63 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDao.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDao.java @@ -17,13 +17,11 @@ package com.cloud.uuididentity.dao; -import com.cloud.api.IdentityMapper; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; import com.cloud.utils.db.GenericDao; public interface IdentityDao extends GenericDao { - Long getIdentityId(IdentityMapper mapper, String identityString); Long getIdentityId(String tableName, String identityString); String getIdentityUuid(String tableName, String identityString); void initializeDefaultUuid(String tableName); @@ -33,5 +31,5 @@ public interface IdentityDao extends GenericDao { * @param resourceType TODO * @return */ - Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType); -} + Pair getAccountDomainInfo(String tableName, Long identityId, TaggedResourceType resourceType); +} diff --git a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java index f35b57c2b67..7be63ba562d 100644 --- a/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java +++ b/server/src/com/cloud/uuididentity/dao/IdentityDaoImpl.java @@ -28,7 +28,6 @@ import javax.ejb.Local; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.api.IdentityMapper; import com.cloud.exception.InvalidParameterValueException; import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.utils.Pair; @@ -44,12 +43,6 @@ public class IdentityDaoImpl extends GenericDaoBase implements public IdentityDaoImpl() { } - @DB - public Long getIdentityId(IdentityMapper mapper, String identityString) { - assert(mapper.entityTableName() != null); - return getIdentityId(mapper.entityTableName(), identityString); - } - @DB public Long getIdentityId(String tableName, String identityString) { assert(tableName != null); diff --git a/server/src/com/cloud/vm/NicVO.java b/server/src/com/cloud/vm/NicVO.java index 3e9b4dc45b3..64b9153a347 100644 --- a/server/src/com/cloud/vm/NicVO.java +++ b/server/src/com/cloud/vm/NicVO.java @@ -29,14 +29,15 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.cloud.api.Identity; +import org.apache.cloudstack.api.Identity; import com.cloud.network.Networks.AddressFormat; import com.cloud.network.Networks.Mode; import com.cloud.utils.db.GenericDao; +import org.apache.cloudstack.api.InternalIdentity; @Entity @Table(name = "nics") -public class NicVO implements Nic, Identity { +public class NicVO implements Nic { protected NicVO() { } diff --git a/server/src/com/cloud/vm/UserVmManager.java b/server/src/com/cloud/vm/UserVmManager.java index 11d2c64016f..3e4a2dbf27f 100755 --- a/server/src/com/cloud/vm/UserVmManager.java +++ b/server/src/com/cloud/vm/UserVmManager.java @@ -21,6 +21,7 @@ import java.util.List; import java.util.Map; import com.cloud.agent.api.VmStatsEntry; +import com.cloud.api.query.vo.UserVmJoinVO; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.ResourceUnavailableException; @@ -96,9 +97,9 @@ public interface UserVmManager extends VirtualMachineGuru, UserVmServi * @param listAll TODO * @param listProjectResourcesCriteria TODO * @param tags TODO - * @return List of UserVMs. + * @return List of UserVMs + count */ - List searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags); + Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags); String getChecksum(Long hostId, String templatePath); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index e0454c32270..0317643b65f 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -32,28 +32,20 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; -import org.apache.cloudstack.engine.cloud.entity.api.VirtualMachineEntity; -import org.apache.cloudstack.engine.service.api.OrchestrationService; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; import org.apache.commons.codec.binary.Base64; import org.apache.log4j.Logger; import org.springframework.stereotype.Component; -import com.cloud.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.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; @@ -61,23 +53,19 @@ import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.manager.Commands; import com.cloud.alert.AlertManager; import com.cloud.api.ApiDBUtils; -import com.cloud.api.BaseCmd; -import com.cloud.api.commands.AssignVMCmd; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.CreateVMGroupCmd; -import com.cloud.api.commands.DeleteVMGroupCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DestroyVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.ListVMsCmd; -import com.cloud.api.commands.RebootVMCmd; -import com.cloud.api.commands.RecoverVMCmd; -import com.cloud.api.commands.ResetVMPasswordCmd; -import com.cloud.api.commands.RestoreVMCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpdateVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import com.cloud.api.query.dao.UserVmJoinDao; +import com.cloud.api.query.vo.UserVmJoinVO; + +import org.apache.cloudstack.api.BaseCmd; +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.user.vm.DeployVMCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import com.cloud.async.AsyncJobExecutor; import com.cloud.async.AsyncJobManager; import com.cloud.async.AsyncJobVO; @@ -102,37 +90,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; @@ -145,7 +114,6 @@ import com.cloud.network.security.SecurityGroupManager; import com.cloud.network.security.dao.SecurityGroupDao; import com.cloud.network.security.dao.SecurityGroupVMMapDao; import com.cloud.network.vpc.VpcManager; -import com.cloud.network.vpc.VpcVO; import com.cloud.network.vpc.dao.VpcDao; import com.cloud.offering.NetworkOffering; import com.cloud.offering.NetworkOffering.Availability; @@ -159,55 +127,20 @@ import com.cloud.projects.ProjectManager; import com.cloud.resource.ResourceManager; import com.cloud.resource.ResourceState; import com.cloud.server.Criteria; -import com.cloud.server.ResourceTag.TaggedResourceType; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; -import com.cloud.storage.DiskOfferingVO; -import com.cloud.storage.GuestOSCategoryVO; -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.GuestOSCategoryDao; -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.ResourceTagVO; 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; @@ -215,7 +148,6 @@ import com.cloud.uservm.UserVm; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.PasswordGenerator; -import com.cloud.utils.Ternary; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; import com.cloud.utils.concurrency.NamedThreadFactory; @@ -223,21 +155,16 @@ import com.cloud.utils.crypt.RSAHelper; import com.cloud.utils.db.DB; import com.cloud.utils.db.Filter; import com.cloud.utils.db.GlobalLock; -import com.cloud.utils.db.JoinBuilder; import com.cloud.utils.db.SearchBuilder; import com.cloud.utils.db.SearchCriteria; import com.cloud.utils.db.Transaction; +import com.cloud.utils.db.SearchCriteria.Func; import com.cloud.utils.exception.CloudRuntimeException; 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.*; @Component @Local(value = { UserVmManager.class, UserVmService.class }) @@ -267,6 +194,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Inject protected UserVmDao _vmDao = null; @Inject + protected UserVmJoinDao _vmJoinDao = null; + @Inject protected VolumeDao _volsDao = null; @Inject protected DataCenterDao _dcDao = null; @@ -1850,12 +1779,8 @@ 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(), origTemplateInstallPath, - templateId, name, - _createprivatetemplatefromsnapshotwait); + 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); if (volume == null) { @@ -1881,11 +1806,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( @@ -2111,7 +2032,8 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager @Override @ActionEvent(eventType = EventTypes.EVENT_VM_UPDATE, eventDescription = "updating Vm") - public UserVm updateVirtualMachine(UpdateVMCmd cmd) { + public UserVm updateVirtualMachine(UpdateVMCmd cmd) + throws ResourceUnavailableException, InsufficientCapacityException { String displayName = cmd.getDisplayName(); String group = cmd.getGroup(); Boolean ha = cmd.getHaEnable(); @@ -2160,9 +2082,13 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager + " is not in the right state"); } + boolean updateUserdata = false; if (userData != null) { + // check and replace newlines + userData = userData.replace("\\n", ""); validateUserData(userData); // update userData on domain router. + updateUserdata = true; } else { userData = vmInstance.getUserData(); } @@ -2194,9 +2120,43 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager _vmDao.updateVM(id, displayName, ha, osTypeId, userData); + if (updateUserdata) { + boolean result = updateUserDataInternal(_vmDao.findById(id)); + if (result) { + s_logger.debug("User data successfully updated for vm id="+id); + } else { + throw new CloudRuntimeException("Failed to reset userdata for the virtual machine "); + } + } + return _vmDao.findById(id); } + private boolean updateUserDataInternal(UserVm vm) + throws ResourceUnavailableException, InsufficientCapacityException { + VMTemplateVO template = _templateDao.findByIdIncludingRemoved(vm.getTemplateId()); + Nic defaultNic = _networkMgr.getDefaultNic(vm.getId()); + if (defaultNic == null) { + s_logger.error("Unable to update userdata for vm id=" + vm.getId() + " as the instance doesn't have default nic"); + return false; + } + + Network defaultNetwork = _networkDao.findById(defaultNic.getNetworkId()); + NicProfile defaultNicProfile = new NicProfile(defaultNic, defaultNetwork, null, null, null, + _networkMgr.isSecurityGroupSupportedInNetwork(defaultNetwork), + _networkMgr.getNetworkTag(template.getHypervisorType(), defaultNetwork)); + + VirtualMachineProfile vmProfile = new VirtualMachineProfileImpl((VMInstanceVO)vm); + + UserDataServiceProvider element = _networkMgr.getUserDataUpdateProvider(defaultNetwork); + if (element == null) { + throw new CloudRuntimeException("Can't find network element for " + Service.UserData.getName() + " provider needed for UserData update"); + } + boolean result = element.saveUserData(defaultNetwork, defaultNicProfile, vmProfile); + + return true; + } + @Override @ActionEvent(eventType = EventTypes.EVENT_VM_START, eventDescription = "starting Vm", async = true) public UserVm startVirtualMachine(StartVMCmd cmd) @@ -2571,9 +2531,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); @@ -2583,33 +2541,25 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager + networkIdList.get(0).longValue()); } - boolean isSecurityGroupEnabled = _networkMgr - .isSecurityGroupSupportedInNetwork(network); - if (isSecurityGroupEnabled && networkIdList.size() > 1) { - throw new InvalidParameterValueException( - "Can't create a vm with multiple networks one of which is Security Group enabled"); - } - - 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"); - } - - // 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"); - } + boolean isSecurityGroupEnabled = _networkMgr.isSecurityGroupSupportedInNetwork(network); + if (isSecurityGroupEnabled) { + if (networkIdList.size() > 1) { + throw new InvalidParameterValueException("Can't create a vm with multiple networks one of" + + " which is Security Group enabled"); + } + + isSecurityGroupEnabledNetworkUsed = true; + } + + 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.getAclType() == ACLType.Account) { + _accountMgr.checkAccess(caller, AccessType.UseNetwork, false, network); + } networkList.add(network); } } @@ -2694,10 +2644,7 @@ 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); - + List virtualNetworks = _networkMgr.listNetworksForAccount(owner.getId(), zone.getId(), Network.GuestType.Isolated); if (virtualNetworks.isEmpty()) { long physicalNetworkId = _networkMgr.findPhysicalNetworkId( zone.getId(), requiredOfferings.get(0).getTags(), @@ -2727,7 +2674,7 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager "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( @@ -3383,7 +3330,6 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager "unable to find a virtual machine with id " + vmId); } - _accountMgr.checkAccess(caller, null, true, vm); UserVO user = _userDao.findById(userId); try { @@ -3409,8 +3355,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager if (ip != null && ip.getSystem()) { UserContext ctx = UserContext.current(); try { - _rulesMgr.disableStaticNat(ip.getId(), ctx.getCaller(), - ctx.getCallerUserId(), true); + 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 " @@ -3628,78 +3577,17 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } } - @Override - public List searchForUserVMs(ListVMsCmd cmd) { - Account caller = UserContext.current().getCaller(); - List permittedAccounts = new ArrayList(); - String hypervisor = cmd.getHypervisor(); - boolean listAll = cmd.listAll(); - Long id = cmd.getId(); - Map tags = cmd.getTags(); - Ternary domainIdRecursiveListProject = new Ternary( - cmd.getDomainId(), cmd.isRecursive(), null); - _accountMgr.buildACLSearchParameters(caller, id, cmd.getAccountName(), - cmd.getProjectId(), permittedAccounts, - domainIdRecursiveListProject, listAll, false); - Long domainId = domainIdRecursiveListProject.first(); - Boolean isRecursive = domainIdRecursiveListProject.second(); - ListProjectResourcesCriteria listProjectResourcesCriteria = domainIdRecursiveListProject - .third(); - Criteria c = new Criteria("id", Boolean.TRUE, cmd.getStartIndex(), - cmd.getPageSizeVal()); - c.addCriteria(Criteria.KEYWORD, cmd.getKeyword()); - c.addCriteria(Criteria.ID, cmd.getId()); - c.addCriteria(Criteria.NAME, cmd.getInstanceName()); - c.addCriteria(Criteria.STATE, cmd.getState()); - c.addCriteria(Criteria.DATACENTERID, cmd.getZoneId()); - c.addCriteria(Criteria.GROUPID, cmd.getGroupId()); - c.addCriteria(Criteria.FOR_VIRTUAL_NETWORK, cmd.getForVirtualNetwork()); - c.addCriteria(Criteria.NETWORKID, cmd.getNetworkId()); - c.addCriteria(Criteria.TEMPLATE_ID, cmd.getTemplateId()); - c.addCriteria(Criteria.ISO_ID, cmd.getIsoId()); - c.addCriteria(Criteria.VPC_ID, cmd.getVpcId()); + @Override + public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, + List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + Filter searchFilter = new Filter(UserVmJoinVO.class, c.getOrderBy(), c.getAscending(), c.getOffset(), c.getLimit()); - if (domainId != null) { - c.addCriteria(Criteria.DOMAINID, domainId); - } - - if (HypervisorType.getType(hypervisor) != HypervisorType.None) { - c.addCriteria(Criteria.HYPERVISOR, hypervisor); - } else if (hypervisor != null) { - throw new InvalidParameterValueException("Invalid HypervisorType " - + hypervisor); - } - - // ignore these search requests if it's not an admin - if (_accountMgr.isAdmin(caller.getType())) { - c.addCriteria(Criteria.PODID, cmd.getPodId()); - c.addCriteria(Criteria.HOSTID, cmd.getHostId()); - c.addCriteria(Criteria.STORAGE_ID, cmd.getStorageId()); - } - - if (!permittedAccounts.isEmpty()) { - c.addCriteria(Criteria.ACCOUNTID, permittedAccounts.toArray()); - } - c.addCriteria(Criteria.ISADMIN, _accountMgr.isAdmin(caller.getType())); - - return searchForUserVMs(c, caller, domainId, isRecursive, - permittedAccounts, listAll, listProjectResourcesCriteria, tags); - } - - @Override - public List searchForUserVMs(Criteria c, Account caller, - Long domainId, boolean isRecursive, List permittedAccounts, - boolean listAll, - ListProjectResourcesCriteria listProjectResourcesCriteria, - Map tags) { - Filter searchFilter = new Filter(UserVmVO.class, c.getOrderBy(), - c.getAscending(), c.getOffset(), c.getLimit()); - - SearchBuilder sb = _vmDao.createSearchBuilder(); - _accountMgr.buildACLSearchBuilder(sb, domainId, isRecursive, - permittedAccounts, listProjectResourcesCriteria); + //first search distinct vm id by using query criteria and pagination + SearchBuilder sb = _vmJoinDao.createSearchBuilder(); + sb.select(null, Func.DISTINCT, sb.entity().getId()); // select distinct ids + _accountMgr.buildACLViewSearchBuilder(sb, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); Object id = c.getCriteria(Criteria.ID); Object name = c.getCriteria(Criteria.NAME); @@ -3727,125 +3615,61 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sb.and("stateEQ", sb.entity().getState(), SearchCriteria.Op.EQ); sb.and("stateNEQ", sb.entity().getState(), SearchCriteria.Op.NEQ); sb.and("stateNIN", sb.entity().getState(), SearchCriteria.Op.NIN); - sb.and("dataCenterId", sb.entity().getDataCenterIdToDeployIn(), - SearchCriteria.Op.EQ); - sb.and("podId", sb.entity().getPodIdToDeployIn(), SearchCriteria.Op.EQ); - sb.and("hypervisorType", sb.entity().getHypervisorType(), - SearchCriteria.Op.EQ); + sb.and("dataCenterId", sb.entity().getDataCenterId(), SearchCriteria.Op.EQ); + sb.and("podId", sb.entity().getPodId(), SearchCriteria.Op.EQ); + sb.and("hypervisorType", sb.entity().getHypervisorType(), SearchCriteria.Op.EQ); sb.and("hostIdEQ", sb.entity().getHostId(), SearchCriteria.Op.EQ); - sb.and("hostIdIN", sb.entity().getHostId(), SearchCriteria.Op.IN); + sb.and("hostName", sb.entity().getHostName(), SearchCriteria.Op.LIKE); sb.and("templateId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); - sb.and("isoId", sb.entity().getTemplateId(), SearchCriteria.Op.EQ); + sb.and("isoId", sb.entity().getIsoId(), SearchCriteria.Op.EQ); + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); - if (groupId != null && (Long) groupId == -1) { - SearchBuilder vmSearch = _groupVMMapDao - .createSearchBuilder(); - vmSearch.and("instanceId", vmSearch.entity().getInstanceId(), - SearchCriteria.Op.EQ); - sb.join("vmSearch", vmSearch, sb.entity().getId(), vmSearch - .entity().getInstanceId(), JoinBuilder.JoinType.LEFTOUTER); - } else if (groupId != null) { - SearchBuilder groupSearch = _groupVMMapDao - .createSearchBuilder(); - groupSearch.and("groupId", groupSearch.entity().getGroupId(), - SearchCriteria.Op.EQ); - sb.join("groupSearch", groupSearch, sb.entity().getId(), - groupSearch.entity().getInstanceId(), - JoinBuilder.JoinType.INNER); - } + if (groupId != null && (Long) groupId != -1) { + sb.and("instanceGroupId", sb.entity().getInstanceGroupId(), SearchCriteria.Op.EQ); + } - if (tags != null && !tags.isEmpty()) { - SearchBuilder tagSearch = _resourceTagDao - .createSearchBuilder(); - for (int count = 0; count < tags.size(); count++) { - tagSearch.or().op("key" + String.valueOf(count), - tagSearch.entity().getKey(), SearchCriteria.Op.EQ); - tagSearch.and("value" + String.valueOf(count), tagSearch - .entity().getValue(), SearchCriteria.Op.EQ); - tagSearch.cp(); - } - tagSearch.and("resourceType", tagSearch.entity().getResourceType(), - SearchCriteria.Op.EQ); - sb.groupBy(sb.entity().getId()); - sb.join("tagSearch", tagSearch, sb.entity().getId(), tagSearch - .entity().getResourceId(), JoinBuilder.JoinType.INNER); - } + if (tags != null && !tags.isEmpty()) { + for (int count=0; count < tags.size(); count++) { + sb.or().op("key" + String.valueOf(count), sb.entity().getTagKey(), SearchCriteria.Op.EQ); + sb.and("value" + String.valueOf(count), sb.entity().getTagValue(), SearchCriteria.Op.EQ); + sb.cp(); + } + } - if (networkId != null) { - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); - nicSearch.and("networkId", nicSearch.entity().getNetworkId(), - SearchCriteria.Op.EQ); + if (networkId != null) { + sb.and("networkId", sb.entity().getNetworkId(), SearchCriteria.Op.EQ); + } - SearchBuilder networkSearch = _networkDao - .createSearchBuilder(); - networkSearch.and("networkId", networkSearch.entity().getId(), - SearchCriteria.Op.EQ); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity() - .getNetworkId(), networkSearch.entity().getId(), - JoinBuilder.JoinType.INNER); + if(vpcId != null && networkId == null){ + sb.and("vpcId", sb.entity().getVpcId(), SearchCriteria.Op.EQ); + } - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch - .entity().getInstanceId(), JoinBuilder.JoinType.INNER); - } + if (storageId != null) { + sb.and("poolId", sb.entity().getPoolId(), SearchCriteria.Op.EQ); + } - if (vpcId != null && networkId == null) { - SearchBuilder nicSearch = _nicDao.createSearchBuilder(); + // populate the search criteria with the values passed in + SearchCriteria sc = sb.create(); - SearchBuilder networkSearch = _networkDao - .createSearchBuilder(); - nicSearch.join("networkSearch", networkSearch, nicSearch.entity() - .getNetworkId(), networkSearch.entity().getId(), - JoinBuilder.JoinType.INNER); + // building ACL condition + _accountMgr.buildACLViewSearchCriteria(sc, domainId, isRecursive, permittedAccounts, listProjectResourcesCriteria); - SearchBuilder vpcSearch = _vpcDao.createSearchBuilder(); - vpcSearch.and("vpcId", vpcSearch.entity().getId(), - SearchCriteria.Op.EQ); - networkSearch.join("vpcSearch", vpcSearch, networkSearch.entity() - .getVpcId(), vpcSearch.entity().getId(), - JoinBuilder.JoinType.INNER); - - sb.join("nicSearch", nicSearch, sb.entity().getId(), nicSearch - .entity().getInstanceId(), JoinBuilder.JoinType.INNER); - } - - if (storageId != null) { - SearchBuilder volumeSearch = _volsDao - .createSearchBuilder(); - volumeSearch.and("poolId", volumeSearch.entity().getPoolId(), - SearchCriteria.Op.EQ); - sb.join("volumeSearch", volumeSearch, sb.entity().getId(), - volumeSearch.entity().getInstanceId(), - JoinBuilder.JoinType.INNER); - } - - // populate the search criteria with the values passed in - SearchCriteria sc = sb.create(); - _accountMgr.buildACLSearchCriteria(sc, domainId, isRecursive, - permittedAccounts, listProjectResourcesCriteria); - - if (tags != null && !tags.isEmpty()) { - int count = 0; - sc.setJoinParameters("tagSearch", "resourceType", - TaggedResourceType.UserVm.toString()); - for (String key : tags.keySet()) { - sc.setJoinParameters("tagSearch", - "key" + String.valueOf(count), key); - sc.setJoinParameters("tagSearch", - "value" + String.valueOf(count), tags.get(key)); + if (tags != null && !tags.isEmpty()) { + int count = 0; + for (String key : tags.keySet()) { + sc.setParameters("key" + String.valueOf(count), key); + sc.setParameters("value" + String.valueOf(count), tags.get(key)); count++; } } - if (groupId != null && (Long) groupId == -1) { - sc.setJoinParameters("vmSearch", "instanceId", (Object) null); - } else if (groupId != null) { - sc.setJoinParameters("groupSearch", "groupId", groupId); + if (groupId != null && (Long)groupId != -1) { + sc.setParameters("instanceGroupId", groupId); } if (keyword != null) { - SearchCriteria ssc = _vmDao.createSearchCriteria(); - ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword - + "%"); + SearchCriteria ssc = _vmJoinDao.createSearchCriteria(); + ssc.addOr("displayName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("hostName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); ssc.addOr("instanceName", SearchCriteria.Op.LIKE, "%" + keyword + "%"); @@ -3867,11 +3691,11 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager } if (networkId != null) { - sc.setJoinParameters("nicSearch", "networkId", networkId); + sc.setParameters("networkId", networkId); } - if (vpcId != null && networkId == null) { - sc.setJoinParameters("vpcSearch", "vpcId", vpcId); + if(vpcId != null && networkId == null){ + sc.setParameters("vpcId", vpcId); } if (name != null) { @@ -3897,10 +3721,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); @@ -3914,26 +3734,29 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager sc.setParameters("hostIdEQ", hostId); } else { if (hostName != null) { - List hosts = _resourceMgr - .listHostsByNameLike((String) hostName); - if (hosts != null & !hosts.isEmpty()) { - Long[] hostIds = new Long[hosts.size()]; - for (int i = 0; i < hosts.size(); i++) { - HostVO host = hosts.get(i); - hostIds[i] = host.getId(); - } - sc.setParameters("hostIdIN", (Object[]) hostIds); - } else { - return new ArrayList(); - } + sc.setParameters("hostName", hostName); } } if (storageId != null) { - sc.setJoinParameters("volumeSearch", "poolId", storageId); + sc.setParameters("poolId", storageId); + } + + // search vm details by ids + Pair, Integer> uniqueVmPair = _vmJoinDao.searchAndCount(sc, searchFilter); + Integer count = uniqueVmPair.second(); + if ( count.intValue() == 0 ){ + // handle empty result cases + return uniqueVmPair; } - s_logger.debug("THE WHERE CLAUSE IS:" + sc.getWhereClause()); - return _vmDao.search(sc, searchFilter); + List uniqueVms = uniqueVmPair.first(); + Long[] vmIds = new Long[uniqueVms.size()]; + int i = 0; + for (UserVmJoinVO v : uniqueVms ){ + vmIds[i++] = v.getId(); + } + List vms = _vmJoinDao.searchByIds(vmIds); + return new Pair, Integer>(vms, count); } @Override @@ -4464,11 +4287,7 @@ 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); - + List virtualNetworks = _networkMgr.listNetworksForAccount(newAccount.getId(), zone.getId(), Network.GuestType.Isolated); if (virtualNetworks.isEmpty()) { long physicalNetworkId = _networkMgr .findPhysicalNetworkId(zone.getId(), @@ -4479,38 +4298,21 @@ public class UserVmManagerImpl implements UserVmManager, UserVmService, Manager PhysicalNetwork physicalNetwork = _physicalNetworkDao .findById(physicalNetworkId); 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(), - newAccount.getAccountName() - + "-network", - newAccount.getAccountName() - + "-network", null, null, - null, null, newAccount, null, - physicalNetwork, zone.getId(), - ACLType.Account, null, null); - defaultNetwork = _networkDao.findById(newNetwork - .getId()); + 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(), + newAccount.getAccountName() + "-network", newAccount.getAccountName() + "-network", null, null, + null, null, newAccount, null, physicalNetwork, zone.getId(), ACLType.Account, null, null); + defaultNetwork = _networkDao.findById(newNetwork.getId()); } else if (virtualNetworks.size() > 1) { 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( diff --git a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java index 68ad1d3d12d..2eb49598cd8 100755 --- a/server/src/com/cloud/vm/VirtualMachineManagerImpl.java +++ b/server/src/com/cloud/vm/VirtualMachineManagerImpl.java @@ -766,7 +766,7 @@ public class VirtualMachineManagerImpl implements VirtualMachineManager, Listene VirtualMachineTO vmTO = hvGuru.implement(vmProfile); cmds = new Commands(OnError.Stop); - cmds.addCommand(new StartCommand(vmTO)); + cmds.addCommand(new StartCommand(vmTO, dest.getHost())); vmGuru.finalizeDeployment(cmds, vmProfile, dest, ctx); diff --git a/server/src/com/cloud/vm/dao/DomainRouterDao.java b/server/src/com/cloud/vm/dao/DomainRouterDao.java index 01e32588007..95d1ea6ca14 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDao.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDao.java @@ -61,7 +61,24 @@ public interface DomainRouterDao extends GenericDao { */ public List listByHostId(Long hostId); public List listByLastHostId(Long hostId); - + + /** + * list virtual machine routers by pod id. pass in null to get all + * virtual machine routers. + * @param podId id of the pod. null if to get all. + * @return list of DomainRouterVO + */ + public List listByPodId(Long podId); + + /** + * list virtual machine routers by pod id. pass in null to get all + * virtual machine routers. + * @param podId id of the pod. null if to get all. + * @param state state of the domain router. null if to get all. + * @return list of DomainRouterVO + */ + public List listByPodIdAndStates(Long podId, State... states); + /** * list virtual machine routers by host id. * pass in null to get all diff --git a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java index 028c472c8e6..40c97e1e278 100755 --- a/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java +++ b/server/src/com/cloud/vm/dao/DomainRouterDaoImpl.java @@ -44,6 +44,7 @@ import com.cloud.utils.db.SearchCriteria.Op; import com.cloud.utils.db.Transaction; import com.cloud.utils.db.UpdateBuilder; import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; @Component @@ -74,6 +75,7 @@ public class DomainRouterDaoImpl extends GenericDaoBase im AllFieldsSearch.and("host", AllFieldsSearch.entity().getHostId(), Op.EQ); AllFieldsSearch.and("lastHost", AllFieldsSearch.entity().getLastHostId(), Op.EQ); AllFieldsSearch.and("state", AllFieldsSearch.entity().getState(), Op.EQ); + AllFieldsSearch.and("states", AllFieldsSearch.entity().getState(), Op.IN); SearchBuilder joinRouterNetwork = _routerNetworkDao.createSearchBuilder(); joinRouterNetwork.and("networkId", joinRouterNetwork.entity().getNetworkId(), Op.EQ); AllFieldsSearch.join("networkRouter", joinRouterNetwork, joinRouterNetwork.entity().getRouterId(), AllFieldsSearch.entity().getId(), JoinType.INNER); @@ -185,6 +187,21 @@ public class DomainRouterDaoImpl extends GenericDaoBase im return listBy(sc); } + @Override + public List listByPodId(Long podId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("podId", podId); + return listBy(sc); + } + + @Override + public List listByPodIdAndStates(Long podId, State... states) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("podId", podId); + sc.setParameters("states", (Object[]) states); + return listBy(sc); + } + @Override public List listIsolatedByHostId(Long hostId) { SearchCriteria sc = HostUpSearch.create(); 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 e09b0abff51..02630d3c665 100644 --- a/server/src/com/cloud/vm/dao/NicDaoImpl.java +++ b/server/src/com/cloud/vm/dao/NicDaoImpl.java @@ -53,6 +53,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); @@ -202,4 +203,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/src/com/cloud/vm/dao/UserVmData.java b/server/src/com/cloud/vm/dao/UserVmData.java index 82c737c0e5b..674fc005a85 100644 --- a/server/src/com/cloud/vm/dao/UserVmData.java +++ b/server/src/com/cloud/vm/dao/UserVmData.java @@ -21,7 +21,7 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import com.cloud.api.response.SecurityGroupRuleResponse; +import org.apache.cloudstack.api.response.SecurityGroupRuleResponse; public class UserVmData { private Long id; diff --git a/server/src/com/cloud/vm/dao/VMInstanceDao.java b/server/src/com/cloud/vm/dao/VMInstanceDao.java index 8939ff54cd9..3293f61651a 100644 --- a/server/src/com/cloud/vm/dao/VMInstanceDao.java +++ b/server/src/com/cloud/vm/dao/VMInstanceDao.java @@ -47,6 +47,13 @@ public interface VMInstanceDao extends GenericDao, StateDao< */ List listByZoneId(long zoneId); + /** + * List VMs by pod ID + * @param podId + * @return list of VMInstanceVO in the specified pod + */ + List listByPodId(long podId); + /** * Lists non-expunged VMs by zone ID and templateId * @param zoneId @@ -77,7 +84,7 @@ public interface VMInstanceDao extends GenericDao, StateDao< List listUpByHostId(Long hostId); List listByLastHostId(Long hostId); - List listByTypeAndState(State state, VirtualMachine.Type type); + List listByTypeAndState(VirtualMachine.Type type, State state); List listByAccountId(long accountId); public Long countAllocatedVirtualRoutersForAccount(long accountId); diff --git a/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java b/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java index 952827fe404..d5693da9d0c 100644 --- a/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/server/src/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -240,6 +240,13 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listBy(sc); } + @Override + public List listByPodId(long podId) { + SearchCriteria sc = AllFieldsSearch.create(); + sc.setParameters("pod", podId); + return listBy(sc); + } + @Override public List listByClusterId(long clusterId) { SearchCriteria sc = VMClusterSearch.create(); @@ -247,7 +254,6 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listBy(sc); } - @Override public List listLHByClusterId(long clusterId) { SearchCriteria sc = LHVMClusterSearch.create(); @@ -318,7 +324,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem } @Override - public List listByTypeAndState(State state, VirtualMachine.Type type) { + public List listByTypeAndState(VirtualMachine.Type type, State state) { SearchCriteria sc = AllFieldsSearch.create(); sc.setParameters("type", type); sc.setParameters("state", state); diff --git a/server/test/com/cloud/api/APITest.java b/server/test/com/cloud/api/APITest.java new file mode 100644 index 00000000000..69c488f5a10 --- /dev/null +++ b/server/test/com/cloud/api/APITest.java @@ -0,0 +1,189 @@ +// 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 com.cloud.api; + +import java.io.BufferedReader; +import java.io.EOFException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.math.BigInteger; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Iterator; + +import com.cloud.utils.exception.CloudRuntimeException; +import com.google.gson.Gson; + +/** + * Base class for API Test + * + * @author Min Chen + * + */ +public abstract class APITest { + + protected String rootUrl = "http://localhost:8080/client/api"; + protected String sessionKey = null; + protected String cookieToSent = null; + + + /** + * Sending an api request through Http GET + * @param command command name + * @param params command query parameters in a HashMap + * @return http request response string + */ + protected String sendRequest(String command, HashMap params){ + try { + // Construct query string + StringBuilder sBuilder = new StringBuilder(); + sBuilder.append("command="); + sBuilder.append(command); + if ( params != null && params.size() > 0){ + Iterator keys = params.keySet().iterator(); + while (keys.hasNext()){ + String key = keys.next(); + sBuilder.append("&"); + sBuilder.append(key); + sBuilder.append("="); + sBuilder.append(URLEncoder.encode(params.get(key), "UTF-8")); + } + } + + // Construct request url + String reqUrl = rootUrl + "?" + sBuilder.toString(); + + // Send Http GET request + URL url = new URL(reqUrl); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + + if ( !command.equals("login") && cookieToSent != null){ + // add the cookie to a request + conn.setRequestProperty("Cookie", cookieToSent); + } + conn.connect(); + + + if ( command.equals("login")){ + // if it is login call, store cookie + String headerName=null; + for (int i=1; (headerName = conn.getHeaderFieldKey(i))!=null; i++) { + if (headerName.equals("Set-Cookie")) { + String cookie = conn.getHeaderField(i); + cookie = cookie.substring(0, cookie.indexOf(";")); + String cookieName = cookie.substring(0, cookie.indexOf("=")); + String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length()); + cookieToSent = cookieName + "=" + cookieValue; + } + } + } + + // Get the response + StringBuilder response = new StringBuilder(); + BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); + String line; + try { + while ((line = rd.readLine()) != null) { + response.append(line); + } + } catch (EOFException ex) { + // ignore this exception + System.out.println("EOF exception due to java bug"); + } + rd.close(); + + + + return response.toString(); + + } catch (Exception e) { + throw new CloudRuntimeException("Problem with sending api request", e); + } + } + + protected String createMD5String(String password) { + MessageDigest md5; + try { + md5 = MessageDigest.getInstance("MD5"); + } catch (NoSuchAlgorithmException e) { + throw new CloudRuntimeException("Error", e); + } + + md5.reset(); + BigInteger pwInt = new BigInteger(1, md5.digest(password.getBytes())); + + // make sure our MD5 hash value is 32 digits long... + StringBuffer sb = new StringBuffer(); + String pwStr = pwInt.toString(16); + int padding = 32 - pwStr.length(); + for (int i = 0; i < padding; i++) { + sb.append('0'); + } + sb.append(pwStr); + return sb.toString(); + } + + + protected Object fromSerializedString(String result, Class repCls) { + try { + if (result != null && !result.isEmpty()) { + + // get real content + int start = result.indexOf('{', result.indexOf('{') + 1); // find the second { + if ( start < 0 ){ + throw new CloudRuntimeException("Response format is wrong: " + result); + } + int end = result.lastIndexOf('}', result.lastIndexOf('}')-1); // find the second } backwards + if ( end < 0 ){ + throw new CloudRuntimeException("Response format is wrong: " + result); + } + String content = result.substring(start, end+1); + Gson gson = ApiGsonHelper.getBuilder().create(); + return gson.fromJson(content, repCls); + } + return null; + } catch (RuntimeException e) { + throw new CloudRuntimeException("Caught runtime exception when doing GSON deserialization on: " + result, e); + } + } + + /** + * Login call + * @param username user name + * @param password password (plain password, we will do MD5 hash here for you) + * @return login response string + */ + protected void login(String username, String password) + { + //String md5Psw = createMD5String(password); + // send login request + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("username", username); + params.put("password", password); + String result = this.sendRequest("login", params); + LoginResponse loginResp = (LoginResponse)fromSerializedString(result, LoginResponse.class); + sessionKey = loginResp.getSessionkey(); + + } +} diff --git a/server/test/com/cloud/api/ListPerfTest.java b/server/test/com/cloud/api/ListPerfTest.java new file mode 100644 index 00000000000..7402cea711a --- /dev/null +++ b/server/test/com/cloud/api/ListPerfTest.java @@ -0,0 +1,151 @@ +// 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 com.cloud.api; + +import java.util.HashMap; + +import org.junit.Before; +import org.junit.Test; + + +/** + * Test fixture to do performance test for list command + * Currently we commented out this test suite since it requires a real MS and Db running. + * + * @author Min Chen + * + */ +public class ListPerfTest extends APITest { + + + + @Before + public void setup(){ + // always login for each testcase + login("admin", "password"); + } + + @Test + public void testListVM(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVirtualMachines", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list VM: " + (after - before) + " ms"); + + } + + @Test + public void testListVMXML(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVirtualMachines", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list VM: " + (after - before) + " ms"); + + } + + @Test + public void testListRouter(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listRouters", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Routers: " + (after - before) + " ms"); + + } + + @Test + public void testListRouterXML(){ + // issue list VM calls + HashMap params = new HashMap(); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listRouters", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Routers: " + (after - before) + " ms"); + + } + + @Test + public void testListHosts(){ + // issue list Hosts calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listHosts", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Hosts: " + (after - before) + " ms"); + + } + + @Test + public void testListVolumes(){ + // issue list Volumes calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listVolumes", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Volumes: " + (after - before) + " ms"); + + } + + @Test + public void testListAccounts(){ + // issue list Accounts calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listAccounts", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Accounts: " + (after - before) + " ms"); + + } + + @Test + public void testListUsers(){ + // issue list Users calls + HashMap params = new HashMap(); + params.put("response", "json"); + params.put("listAll", "true"); + params.put("sessionkey", sessionKey); + long before = System.currentTimeMillis(); + String result = this.sendRequest("listUsers", params); + long after = System.currentTimeMillis(); + System.out.println("Time taken to list Users: " + (after - before) + " ms"); + + } +} diff --git a/server/test/com/cloud/api/LoginResponse.java b/server/test/com/cloud/api/LoginResponse.java new file mode 100644 index 00000000000..097ae42c999 --- /dev/null +++ b/server/test/com/cloud/api/LoginResponse.java @@ -0,0 +1,142 @@ +// 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 com.cloud.api; + +import org.apache.cloudstack.api.BaseResponse; + +import com.cloud.serializer.Param; +import com.google.gson.annotations.SerializedName; + +/** + * Login Response object + * + * @author Min Chen + * + */ +public class LoginResponse extends BaseResponse { + + @SerializedName("timeout") + @Param(description = "session timeout period") + private String timeout; + + @SerializedName("sessionkey") + @Param(description = "login session key") + private String sessionkey; + + @SerializedName("username") + @Param(description = "login username") + private String username; + + @SerializedName("userid") + @Param(description = "login user internal uuid") + private String userid; + + @SerializedName("firstname") + @Param(description = "login user firstname") + private String firstname; + + @SerializedName("lastname") + @Param(description = "login user lastname") + private String lastname; + + @SerializedName("account") + @Param(description = "login user account type") + private String account; + + @SerializedName("domainid") + @Param(description = "login user domain id") + private String domainid; + + @SerializedName("type") + @Param(description = "login user type") + private int type; + + public String getTimeout() { + return timeout; + } + + public void setTimeout(String timeout) { + this.timeout = timeout; + } + + public String getSessionkey() { + return sessionkey; + } + + public void setSessionkey(String sessionkey) { + this.sessionkey = sessionkey; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getUserid() { + return userid; + } + + public void setUserid(String userid) { + this.userid = userid; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getAccount() { + return account; + } + + public void setAccount(String account) { + this.account = account; + } + + public String getDomainid() { + return domainid; + } + + public void setDomainid(String domainid) { + this.domainid = domainid; + } + + public int getType() { + return type; + } + + public void setType(int type) { + this.type = type; + } + + + +} diff --git a/server/test/com/cloud/async/TestSyncQueueManager.java b/server/test/com/cloud/async/TestSyncQueueManager.java index f8be9b696b6..2bbf7bcc8bd 100644 --- a/server/test/com/cloud/async/TestSyncQueueManager.java +++ b/server/test/com/cloud/async/TestSyncQueueManager.java @@ -32,178 +32,178 @@ public class TestSyncQueueManager extends ComponentTestCase { private volatile int count = 0; private volatile long expectingCurrent = 1; - public void leftOverItems() { - SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - List l = mgr.getActiveQueueItems(1L, false); - if(l != null && l.size() > 0) { - for(SyncQueueItemVO item : l) { - s_logger.info("Left over item: " + item.toString()); - mgr.purgeItem(item.getId()); - } - } - } - - public void dequeueFromOneQueue() { - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - final int totalRuns = 5000; - final SyncQueueVO queue = mgr.queue("vm_instance", 1L, "Async-job", 1); - for(int i = 1; i < totalRuns; i++) - mgr.queue("vm_instance", 1L, "Async-job", i+1); - - count = 0; - expectingCurrent = 1; - Thread thread1 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns) { - SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); - if(item != null) { - s_logger.info("Thread 1 process item: " + item.toString()); - - Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); - expectingCurrent++; - count++; - - mgr.purgeItem(item.getId()); - } - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - Thread thread2 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns) { - SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); - if(item != null) { - s_logger.info("Thread 2 process item: " + item.toString()); - - Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); - expectingCurrent++; - count++; - mgr.purgeItem(item.getId()); - } - - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - thread1.start(); - thread2.start(); - try { - thread1.join(); - } catch (InterruptedException e) { - } - try { - thread2.join(); - } catch (InterruptedException e) { - } - - Assert.assertEquals(totalRuns, count); - } - - public void dequeueFromAnyQueue() { - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - - // simulate 30 queues - final int queues = 30; - final int totalRuns = 100; - final int itemsPerRun = 20; - for(int q = 1; q <= queues; q++) - for(int i = 0; i < totalRuns; i++) - mgr.queue("vm_instance", q, "Async-job", i+1); - - count = 0; - Thread thread1 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns*queues) { - List l = mgr.dequeueFromAny(1L, itemsPerRun); - if(l != null && l.size() > 0) { - s_logger.info("Thread 1 get " + l.size() + " dequeued items"); - - for(SyncQueueItemVO item : l) { - s_logger.info("Thread 1 process item: " + item.toString()); - count++; - - mgr.purgeItem(item.getId()); - } - } - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - Thread thread2 = new Thread(new Runnable() { - public void run() { - while(count < totalRuns*queues) { - List l = mgr.dequeueFromAny(1L, itemsPerRun); - if(l != null && l.size() > 0) { - s_logger.info("Thread 2 get " + l.size() + " dequeued items"); - - for(SyncQueueItemVO item : l) { - s_logger.info("Thread 2 process item: " + item.toString()); - count++; - mgr.purgeItem(item.getId()); - } - } - - try { - Thread.sleep(getRandomMilliseconds(1, 10)); - } catch (InterruptedException e) { - } - } - } - } - ); - - thread1.start(); - thread2.start(); - try { - thread1.join(); - } catch (InterruptedException e) { - } - try { - thread2.join(); - } catch (InterruptedException e) { - } - Assert.assertEquals(queues*totalRuns, count); - } - - public void testPopulateQueueData() { - final int queues = 30000; - final int totalRuns = 100; - - final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( - SyncQueueManager.class); - for(int q = 1; q <= queues; q++) - for(int i = 0; i < totalRuns; i++) - mgr.queue("vm_instance", q, "Async-job", i+1); + public void leftOverItems() { + SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + List l = mgr.getActiveQueueItems(1L, false); + if(l != null && l.size() > 0) { + for(SyncQueueItemVO item : l) { + s_logger.info("Left over item: " + item.toString()); + mgr.purgeItem(item.getId()); + } + } + } + + public void dequeueFromOneQueue() { + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + final int totalRuns = 5000; + final SyncQueueVO queue = mgr.queue("vm_instance", 1L, "Async-job", 1, 1); + for(int i = 1; i < totalRuns; i++) + mgr.queue("vm_instance", 1L, "Async-job", i+1, 1); + + count = 0; + expectingCurrent = 1; + Thread thread1 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns) { + SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); + if(item != null) { + s_logger.info("Thread 1 process item: " + item.toString()); + + Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); + expectingCurrent++; + count++; + + mgr.purgeItem(item.getId()); + } + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + Thread thread2 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns) { + SyncQueueItemVO item = mgr.dequeueFromOne(queue.getId(), 1L); + if(item != null) { + s_logger.info("Thread 2 process item: " + item.toString()); + + Assert.assertEquals(expectingCurrent, item.getContentId().longValue()); + expectingCurrent++; + count++; + mgr.purgeItem(item.getId()); + } + + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + thread1.start(); + thread2.start(); + try { + thread1.join(); + } catch (InterruptedException e) { + } + try { + thread2.join(); + } catch (InterruptedException e) { + } + + Assert.assertEquals(totalRuns, count); + } + + public void dequeueFromAnyQueue() { + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + + // simulate 30 queues + final int queues = 30; + final int totalRuns = 100; + final int itemsPerRun = 20; + for(int q = 1; q <= queues; q++) + for(int i = 0; i < totalRuns; i++) + mgr.queue("vm_instance", q, "Async-job", i+1, 1); + + count = 0; + Thread thread1 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns*queues) { + List l = mgr.dequeueFromAny(1L, itemsPerRun); + if(l != null && l.size() > 0) { + s_logger.info("Thread 1 get " + l.size() + " dequeued items"); + + for(SyncQueueItemVO item : l) { + s_logger.info("Thread 1 process item: " + item.toString()); + count++; + + mgr.purgeItem(item.getId()); + } + } + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + Thread thread2 = new Thread(new Runnable() { + public void run() { + while(count < totalRuns*queues) { + List l = mgr.dequeueFromAny(1L, itemsPerRun); + if(l != null && l.size() > 0) { + s_logger.info("Thread 2 get " + l.size() + " dequeued items"); + + for(SyncQueueItemVO item : l) { + s_logger.info("Thread 2 process item: " + item.toString()); + count++; + mgr.purgeItem(item.getId()); + } + } + + try { + Thread.sleep(getRandomMilliseconds(1, 10)); + } catch (InterruptedException e) { + } + } + } + } + ); + + thread1.start(); + thread2.start(); + try { + thread1.join(); + } catch (InterruptedException e) { + } + try { + thread2.join(); + } catch (InterruptedException e) { + } + Assert.assertEquals(queues*totalRuns, count); + } + + public void testPopulateQueueData() { + final int queues = 30000; + final int totalRuns = 100; + + final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( + SyncQueueManager.class); + for(int q = 1; q <= queues; q++) + for(int i = 0; i < totalRuns; i++) + mgr.queue("vm_instance", q, "Async-job", i+1, 1); } public void testSyncQueue() { final SyncQueueManager mgr = ComponentLocator.getCurrentLocator().getManager( SyncQueueManager.class); - mgr.queue("vm_instance", 1, "Async-job", 1); - mgr.queue("vm_instance", 1, "Async-job", 2); - mgr.queue("vm_instance", 1, "Async-job", 3); + mgr.queue("vm_instance", 1, "Async-job", 1, 1); + mgr.queue("vm_instance", 1, "Async-job", 2, 1); + mgr.queue("vm_instance", 1, "Async-job", 3, 1); mgr.dequeueFromAny(100L, 1); List l = mgr.getBlockedQueueItems(100000, false); diff --git a/server/test/com/cloud/keystore/KeystoreTest.java b/server/test/com/cloud/keystore/KeystoreTest.java index e0e21268184..47212c12cca 100644 --- a/server/test/com/cloud/keystore/KeystoreTest.java +++ b/server/test/com/cloud/keystore/KeystoreTest.java @@ -16,34 +16,22 @@ // under the License. package com.cloud.keystore; -import java.security.KeyStore; -import java.util.Date; -import java.util.HashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import junit.framework.TestCase; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; -import com.cloud.api.ApiResponseHelper; import com.cloud.api.ApiSerializerHelper; -import com.cloud.api.response.AlertResponse; -import com.cloud.api.response.ApiResponseSerializer; -import com.cloud.api.response.UserVmResponse; -import com.cloud.configuration.DefaultInterceptorLibrary; -import com.cloud.utils.component.ComponentLocator; -import com.cloud.utils.component.MockComponentLocator; -import com.cloud.utils.security.CertificateHelper; +import org.apache.cloudstack.api.response.AlertResponse; +import org.apache.cloudstack.api.response.UserVmResponse; public class KeystoreTest extends TestCase { private final static Logger s_logger = Logger.getLogger(KeystoreTest.class); - private String keyContent = - "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALV5vGlkiWwoZX4hTRplPXP8qtST\n" + - "hwZhko8noeY5vf8ECwmd+vrCTw/JvnOtkx/8oYNbg/SeUt1EfOsk6gqJdBblGFBZRMcUJlIpqE9z\n" + + private String keyContent = + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALV5vGlkiWwoZX4hTRplPXP8qtST\n" + + "hwZhko8noeY5vf8ECwmd+vrCTw/JvnOtkx/8oYNbg/SeUt1EfOsk6gqJdBblGFBZRMcUJlIpqE9z\n" + "uv68U9G8Gfi/qvRSY336hibw0J5bZ4vn1QqmyHDB+Czea9AjFUV7AEVG15+vED7why+/AgMBAAEC\n" + "gYBmFBPnNKYYMKDmUdUNA+WNWJK/ADzzWe8WlzR6TACTcbLDthl289WFC/YVG42mcHRpbxDKiEQU\n" + "MnIR0rHTO34Qb/2HcuyweStU2gqR6omxBvMnFpJr90nD1HcOMJzeLHsphau0/EmKKey+gk4PyieD\n" + @@ -54,8 +42,8 @@ public class KeystoreTest extends TestCase { "/DURBUn+1l5pyCKrZnDbvaALSLATLvjmFTuGjoHszy2OeKnOZmEqExWnKKE/VYuPyhy6V7i3TwJA\n" + "f8skDgtPK0OsBCa6IljPaHoWBjPc4kFkSTSS1d56hUcWSikTmiuKdLyBb85AADSZYsvHWrte4opN\n" + "dhNukMJuRA==\n"; - - private String certContent = + + private String certContent = "-----BEGIN CERTIFICATE-----\n" + "MIIE3jCCA8agAwIBAgIFAqv56tIwDQYJKoZIhvcNAQEFBQAwgcoxCzAJBgNVBAYT\n" + "AlVTMRAwDgYDVQQIEwdBcml6b25hMRMwEQYDVQQHEwpTY290dHNkYWxlMRowGAYD\n" + @@ -85,27 +73,27 @@ public class KeystoreTest extends TestCase { "k0fLF4+i/pt9hVCz0QrZ28RUhXf825+EOL0Gw+Uzt+7RV2cCaJrlu4cDrDom2FRy\n" + "E8I=\n" + "-----END CERTIFICATE-----\n"; - + @Override @Before public void setUp() { -/* +/* MockComponentLocator locator = new MockComponentLocator("management-server"); locator.addDao("keystoreDao", KeystoreDaoImpl.class); locator.addManager("KeystoreManager", KeystoreManagerImpl.class); locator.makeActive(new DefaultInterceptorLibrary()); -*/ +*/ } - + @Override @After public void tearDown() throws Exception { } -/* +/* public void testKeystoreSave() throws Exception { KeystoreVO ksVo; - + ComponentLocator locator = ComponentLocator.getCurrentLocator(); KeystoreDao ksDao = locator.getDao(KeystoreDao.class); @@ -115,18 +103,18 @@ public class KeystoreTest extends TestCase { assertTrue(ksVo.getCertificate().equals("CPVMCertificate")); assertTrue(ksVo.getKey().equals("KeyForCertificate")); assertTrue(ksVo.getDomainSuffix().equals("realhostip.com")); - + ksDao.save("CPVMCertificate", "CPVMCertificate Again", "KeyForCertificate Again", "again.realhostip.com"); - + ksVo = ksDao.findByName("CPVMCertificate"); assertTrue(ksVo != null); assertTrue(ksVo.getCertificate().equals("CPVMCertificate Again")); assertTrue(ksVo.getKey().equals("KeyForCertificate Again")); assertTrue(ksVo.getDomainSuffix().equals("again.realhostip.com")); - + ksDao.expunge(ksVo.getId()); } - + public void testStripeKey() throws Exception { Pattern regex = Pattern.compile("(^[\\-]+[^\\-]+[\\-]+[\\n]?)([^\\-]+)([\\-]+[^\\-]+[\\-]+$)"); Matcher m = regex.matcher("-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAm4bLUORp9oM65GV9XrPrbs+K563DjUR1M8mP1HaE+Y4lX5pk\nvQjC/xoEqSs5pxDDWXAkoexvxij8A4AWcsKU1Q+ep2E+GcytBoz8XINGvgb8cQNn\n/4PlVWKp7j5SDDNCfleYvmiRn8k6P4mxVJOHKzwb/IwQcKghyqAF1w==\n-----END RSA PRIVATE KEY-----"); @@ -138,19 +126,19 @@ public class KeystoreTest extends TestCase { assertTrue(false); } } - + public void testKeystoreManager() throws Exception { ComponentLocator locator = ComponentLocator.getCurrentLocator(); - + KeystoreManagerImpl ksMgr = ComponentLocator.inject(KeystoreManagerImpl.class); assertTrue(ksMgr.configure("TaskManager", new HashMap())); assertTrue(ksMgr.start()); - + ksMgr.saveCertificate("CPVMCertificate", certContent, keyContent, "realhostip.com"); - + byte[] ksBits = ksMgr.getKeystoreBits("CPVMCertificate", "realhostip", "vmops.com"); assertTrue(ksBits != null); - + try { KeyStore ks = CertificateHelper.loadKeystore(ksBits, "vmops.com"); assertTrue(ks != null); @@ -162,11 +150,11 @@ public class KeystoreTest extends TestCase { KeystoreVO ksVo = ksDao.findByName("CPVMCertificate"); ksDao.expunge(ksVo.getId()); } -*/ +*/ public void testUuid() { UserVmResponse vm = new UserVmResponse(); - vm.setId(3L); -/* + vm.setId(Long.toString(3L)); +/* vm.setAccountName("admin"); vm.setName("i-2-3-KY"); vm.setDisplayName("i-2-3-KY"); @@ -177,18 +165,18 @@ public class KeystoreTest extends TestCase { vm.setZoneId(1L); vm.setZoneName("KY"); vm.setHostId(1L); - + vm.setObjectName("virtualmachine"); -*/ +*/ String result = ApiSerializerHelper.toSerializedStringOld(vm); - // String result = "com.cloud.api.response.UserVmResponse/virtualmachine/{\"id\":{\"_tableName\":\"vm_instance\",\"_value\":3},\"name\":\"i-2-3-KY\",\"displayname\":\"i-2-3-KY\",\"account\":\"admin\",\"projectid\":{\"_tableName\":\"projects\"},\"domainid\":{\"_tableName\":\"domain\",\"_value\":1},\"domain\":\"ROOT\",\"created\":\"2011-11-02T21:54:07-0700\",\"state\":\"Running\",\"haenable\":false,\"groupid\":{\"_tableName\":\"instance_group\"},\"zoneid\":{\"_tableName\":\"data_center\",\"_value\":1},\"zonename\":\"KY\",\"hostid\":{\"_tableName\":\"host\",\"_value\":1},\"hostname\":\"xenserver-basic\",\"templateid\":{\"_tableName\":\"vm_template\",\"_value\":2},\"templatename\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"templatedisplaytext\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"passwordenabled\":false,\"isoid\":{\"_tableName\":\"vm_template\"},\"serviceofferingid\":{\"_tableName\":\"disk_offering\",\"_value\":7},\"serviceofferingname\":\"Small Instance\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"guestosid\":{\"_tableName\":\"guest_os\",\"_value\":12},\"rootdeviceid\":0,\"rootdevicetype\":\"NetworkFilesystem\",\"securitygroup\":[],\"jobid\":{\"_tableName\":\"async_job\"},\"nic\":[{\"id\":7,\"networkid\":200,\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\",\"ipaddress\":\"10.1.1.116\",\"isolationuri\":\"vlan://1699\",\"broadcasturi\":\"vlan://1699\",\"traffictype\":\"Guest\",\"type\":\"Virtual\",\"isdefault\":true,\"macaddress\":\"02:00:39:a7:00:01\"}],\"hypervisor\":\"XenServer\"}"; + // String result = "org.apache.cloudstack.api.response.UserVmResponse/virtualmachine/{\"id\":{\"_tableName\":\"vm_instance\",\"_value\":3},\"name\":\"i-2-3-KY\",\"displayname\":\"i-2-3-KY\",\"account\":\"admin\",\"projectid\":{\"_tableName\":\"projects\"},\"domainid\":{\"_tableName\":\"domain\",\"_value\":1},\"domain\":\"ROOT\",\"created\":\"2011-11-02T21:54:07-0700\",\"state\":\"Running\",\"haenable\":false,\"groupid\":{\"_tableName\":\"instance_group\"},\"zoneid\":{\"_tableName\":\"data_center\",\"_value\":1},\"zonename\":\"KY\",\"hostid\":{\"_tableName\":\"host\",\"_value\":1},\"hostname\":\"xenserver-basic\",\"templateid\":{\"_tableName\":\"vm_template\",\"_value\":2},\"templatename\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"templatedisplaytext\":\"CentOS 5.3(64-bit) no GUI (XenServer)\",\"passwordenabled\":false,\"isoid\":{\"_tableName\":\"vm_template\"},\"serviceofferingid\":{\"_tableName\":\"disk_offering\",\"_value\":7},\"serviceofferingname\":\"Small Instance\",\"cpunumber\":1,\"cpuspeed\":500,\"memory\":512,\"guestosid\":{\"_tableName\":\"guest_os\",\"_value\":12},\"rootdeviceid\":0,\"rootdevicetype\":\"NetworkFilesystem\",\"securitygroup\":[],\"jobid\":{\"_tableName\":\"async_job\"},\"nic\":[{\"id\":7,\"networkid\":200,\"netmask\":\"255.255.255.0\",\"gateway\":\"10.1.1.1\",\"ipaddress\":\"10.1.1.116\",\"isolationuri\":\"vlan://1699\",\"broadcasturi\":\"vlan://1699\",\"traffictype\":\"Guest\",\"type\":\"Virtual\",\"isdefault\":true,\"macaddress\":\"02:00:39:a7:00:01\"}],\"hypervisor\":\"XenServer\"}"; System.out.println(result); //Object obj = ApiSerializerHelper.fromSerializedString(result); AlertResponse alert = new AlertResponse(); - alert.setId(100L); + alert.setId("100"); alert.setDescription("Hello"); - + result = ApiSerializerHelper.toSerializedStringOld(alert); System.out.println(result); ApiSerializerHelper.fromSerializedString(result); diff --git a/server/test/com/cloud/network/MockNetworkManagerImpl.java b/server/test/com/cloud/network/MockNetworkManagerImpl.java index c2ae1bfd29c..26a6e60f714 100755 --- a/server/test/com/cloud/network/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/network/MockNetworkManagerImpl.java @@ -16,31 +16,18 @@ // 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 com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +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.ListNetworksCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan; 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; @@ -48,12 +35,16 @@ import com.cloud.network.Network.Provider; import com.cloud.network.Network.Service; import com.cloud.network.Networks.TrafficType; import com.cloud.network.addr.PublicIp; +import com.cloud.network.element.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; 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.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; @@ -61,13 +52,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 { @@ -441,7 +433,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { + public Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { // TODO Auto-generated method stub return null; } @@ -477,7 +469,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { + public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { // TODO Auto-generated method stub return null; } @@ -537,7 +529,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } @Override - public List listTrafficTypes(Long physicalNetworkId) { + public Pair, Integer> listTrafficTypes(Long physicalNetworkId) { // TODO Auto-generated method stub return null; } @@ -615,6 +607,12 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS return null; } + @Override + public UserDataServiceProvider getUserDataUpdateProvider(Network network) { + // TODO Auto-generated method stub + return null; + } + @Override public PhysicalNetworkServiceProvider updateNetworkServiceProvider(Long id, String state, List enabledServices) { // TODO Auto-generated method stub @@ -790,10 +788,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; } @@ -933,7 +931,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } /* (non-Javadoc) -<<<<<<< HEAD * @see com.cloud.network.NetworkManager#getDefaultPublicTrafficLabel(long, com.cloud.hypervisor.Hypervisor.HypervisorType) */ @Override @@ -944,9 +941,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 { @@ -1001,7 +995,6 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS } /* (non-Javadoc) -<<<<<<< HEAD * @see com.cloud.network.NetworkManager#getSite2SiteVpnElements() */ @Override @@ -1012,9 +1005,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) { @@ -1141,4 +1131,35 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager, NetworkS // TODO Auto-generated method stub return 0; } + + @Override + public boolean isNetworkInlineMode(Network network) { + // TODO Auto-generated method stub + return false; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public List getProvidersForServiceInNetwork(Network network, + Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRuleCountForIp(Long addressId, Purpose purpose, State state) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } } diff --git a/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java b/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java index c4b4e94a60f..461bde0b95d 100644 --- a/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java +++ b/server/test/com/cloud/network/security/SecurityGroupManagerImpl2Test.java @@ -28,6 +28,7 @@ import org.junit.Before; import org.junit.Ignore; import com.cloud.agent.MockAgentManagerImpl; +import com.cloud.api.query.dao.SecurityGroupJoinDaoImpl; import com.cloud.configuration.DefaultInterceptorLibrary; import com.cloud.configuration.dao.ConfigurationDaoImpl; import com.cloud.domain.dao.DomainDaoImpl; @@ -66,6 +67,7 @@ public class SecurityGroupManagerImpl2Test extends TestCase { locator.addDao("SecurityGroupDao", SecurityGroupDaoImpl.class); locator.addDao("SecurityGroupRuleDao", SecurityGroupRuleDaoImpl.class); + locator.addDao("SecurityGroupJoinDao", SecurityGroupJoinDaoImpl.class); locator.addDao("SecurityGroupVMMapDao", SecurityGroupVMMapDaoImpl.class); locator.addDao("SecurityGroupRulesDao", SecurityGroupRulesDaoImpl.class); locator.addDao("UserVmDao", UserVmDaoImpl.class); diff --git a/server/test/com/cloud/projects/MockProjectManagerImpl.java b/server/test/com/cloud/projects/MockProjectManagerImpl.java index 0fbcf9c1a1d..309fa45d660 100644 --- a/server/test/com/cloud/projects/MockProjectManagerImpl.java +++ b/server/test/com/cloud/projects/MockProjectManagerImpl.java @@ -22,12 +22,18 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; + +import com.cloud.api.query.vo.ProjectAccountJoinVO; +import com.cloud.api.query.vo.ProjectInvitationJoinVO; +import com.cloud.api.query.vo.ProjectJoinVO; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceAllocationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.projects.ProjectAccount.Role; import com.cloud.user.Account; import com.cloud.utils.component.Manager; +import com.cloud.utils.Pair; + @Local(value = { ProjectManager.class }) public class MockProjectManagerImpl implements ProjectManager, Manager { @@ -103,21 +109,6 @@ public class MockProjectManagerImpl implements ProjectManager, Manager { return false; } - @Override - public List listProjectAccounts(long projectId, - String accountName, String role, Long startIndex, Long pageSizeVal) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List listProjectInvitations(Long id, - Long projectId, String accountName, Long domainId, String state, - boolean activeOnly, Long startIndex, Long pageSizeVal, - boolean isRecursive, boolean listAll) { - // TODO Auto-generated method stub - return null; - } @Override public boolean updateInvitation(long projectId, String accountName, @@ -219,16 +210,16 @@ public class MockProjectManagerImpl implements ProjectManager, Manager { return false; } - /* (non-Javadoc) - * @see com.cloud.projects.ProjectService#listProjects(java.lang.Long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Long, java.lang.String, java.lang.Long, java.lang.Long, boolean, boolean, java.util.Map) - */ + + @Override - public List listProjects(Long id, String name, String displayText, String state, String accountName, Long domainId, String keyword, Long startIndex, Long pageSize, boolean listAll, - boolean isRecursive, Map tags) { + public long getInvitationTimeout() { // TODO Auto-generated method stub - return null; + return 0; } - + + + @Override public Project findByProjectAccountIdIncludingRemoved(long projectAccountId) { return null; diff --git a/server/test/com/cloud/user/MockAccountManagerImpl.java b/server/test/com/cloud/user/MockAccountManagerImpl.java index 0d15cd7de0a..ae5d0e5de4b 100644 --- a/server/test/com/cloud/user/MockAccountManagerImpl.java +++ b/server/test/com/cloud/user/MockAccountManagerImpl.java @@ -22,14 +22,15 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.acl.ControlledEntity; -import com.cloud.acl.SecurityChecker.AccessType; -import com.cloud.api.commands.DeleteUserCmd; -import com.cloud.api.commands.ListAccountsCmd; -import com.cloud.api.commands.ListUsersCmd; -import com.cloud.api.commands.RegisterCmd; -import com.cloud.api.commands.UpdateAccountCmd; -import com.cloud.api.commands.UpdateUserCmd; +import org.apache.cloudstack.acl.ControlledEntity; +import org.apache.cloudstack.acl.SecurityChecker.AccessType; +import com.cloud.api.query.vo.ControlledViewEntity; + +import org.apache.cloudstack.api.command.admin.user.DeleteUserCmd; +import org.apache.cloudstack.api.command.admin.user.RegisterCmd; +import org.apache.cloudstack.api.command.admin.account.UpdateAccountCmd; +import org.apache.cloudstack.api.command.admin.user.UpdateUserCmd; + import com.cloud.domain.Domain; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.PermissionDeniedException; @@ -297,18 +298,6 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS return null; } - @Override - public List searchForAccounts(ListAccountsCmd cmd) { - // TODO Auto-generated method stub - return null; - } - - @Override - public List searchForUsers(ListUsersCmd cmd) throws PermissionDeniedException { - // TODO Auto-generated method stub - return null; - } - @Override public boolean enableAccount(long accountId) { // TODO Auto-generated method stub @@ -319,14 +308,14 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS public void buildACLSearchBuilder(SearchBuilder sb, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { // TODO Auto-generated method stub - + } @Override public void buildACLSearchCriteria(SearchCriteria sc, Long domainId, boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { // TODO Auto-generated method stub - + } @Override @@ -334,6 +323,18 @@ public class MockAccountManagerImpl implements Manager, AccountManager, AccountS // TODO Auto-generated method stub } + @Override + public void buildACLViewSearchBuilder(SearchBuilder sb, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + + @Override + public void buildACLViewSearchCriteria(SearchCriteria sc, Long domainId, + boolean isRecursive, List permittedAccounts, ListProjectResourcesCriteria listProjectResourcesCriteria) { + // TODO Auto-generated method stub + } + /* (non-Javadoc) * @see com.cloud.user.AccountService#getUserByApiKey(java.lang.String) */ diff --git a/server/test/com/cloud/user/MockDomainManagerImpl.java b/server/test/com/cloud/user/MockDomainManagerImpl.java index e99e4d94265..6dc4d075b9e 100644 --- a/server/test/com/cloud/user/MockDomainManagerImpl.java +++ b/server/test/com/cloud/user/MockDomainManagerImpl.java @@ -23,12 +23,13 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.ListDomainChildrenCmd; -import com.cloud.api.commands.ListDomainsCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainChildrenCmd; +import org.apache.cloudstack.api.command.admin.domain.ListDomainsCmd; import com.cloud.domain.Domain; import com.cloud.domain.DomainVO; import com.cloud.exception.PermissionDeniedException; import com.cloud.utils.component.Manager; +import com.cloud.utils.Pair; @Local(value = { DomainManager.class }) public class MockDomainManagerImpl implements Manager, DomainManager { @@ -58,14 +59,14 @@ public class MockDomainManagerImpl implements Manager, DomainManager { } @Override - public List searchForDomains(ListDomainsCmd cmd) + public Pair, Integer> searchForDomains(ListDomainsCmd cmd) throws PermissionDeniedException { // TODO Auto-generated method stub return null; } @Override - public List searchForDomainChildren( + public Pair, Integer> searchForDomainChildren( ListDomainChildrenCmd cmd) throws PermissionDeniedException { // TODO Auto-generated method stub return null; diff --git a/server/test/com/cloud/vm/MockUserVmManagerImpl.java b/server/test/com/cloud/vm/MockUserVmManagerImpl.java index efc6916ab40..27508b14c5b 100644 --- a/server/test/com/cloud/vm/MockUserVmManagerImpl.java +++ b/server/test/com/cloud/vm/MockUserVmManagerImpl.java @@ -28,22 +28,24 @@ import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.manager.Commands; -import com.cloud.api.commands.AssignVMCmd; -import com.cloud.api.commands.AttachVolumeCmd; -import com.cloud.api.commands.CreateTemplateCmd; -import com.cloud.api.commands.CreateVMGroupCmd; -import com.cloud.api.commands.DeleteVMGroupCmd; -import com.cloud.api.commands.DeployVMCmd; -import com.cloud.api.commands.DestroyVMCmd; -import com.cloud.api.commands.DetachVolumeCmd; -import com.cloud.api.commands.ListVMsCmd; -import com.cloud.api.commands.RebootVMCmd; -import com.cloud.api.commands.RecoverVMCmd; -import com.cloud.api.commands.ResetVMPasswordCmd; -import com.cloud.api.commands.RestoreVMCmd; -import com.cloud.api.commands.StartVMCmd; -import com.cloud.api.commands.UpdateVMCmd; -import com.cloud.api.commands.UpgradeVMCmd; +import com.cloud.api.query.vo.UserVmJoinVO; + +import org.apache.cloudstack.api.command.admin.vm.AssignVMCmd; +import org.apache.cloudstack.api.command.admin.vm.RecoverVMCmd; +import org.apache.cloudstack.api.command.user.vm.*; +import org.apache.cloudstack.api.command.user.vmgroup.DeleteVMGroupCmd; +import org.apache.cloudstack.api.command.user.volume.AttachVolumeCmd; +import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd; +import org.apache.cloudstack.api.command.user.template.CreateTemplateCmd; +import org.apache.cloudstack.api.command.user.vmgroup.CreateVMGroupCmd; +import org.apache.cloudstack.api.command.user.vm.DestroyVMCmd; +import org.apache.cloudstack.api.command.user.vm.ListVMsCmd; +import org.apache.cloudstack.api.command.user.vm.RebootVMCmd; +import org.apache.cloudstack.api.command.user.vm.ResetVMPasswordCmd; +import org.apache.cloudstack.api.command.user.vm.RestoreVMCmd; +import org.apache.cloudstack.api.command.user.vm.StartVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpdateVMCmd; +import org.apache.cloudstack.api.command.user.vm.UpgradeVMCmd; import com.cloud.dc.DataCenter; import com.cloud.deploy.DeployDestination; import com.cloud.exception.ConcurrentOperationException; @@ -192,7 +194,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana } @Override - public List searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { + public Pair, Integer> searchForUserVMs(Criteria c, Account caller, Long domainId, boolean isRecursive, List permittedAccounts, boolean listAll, ListProjectResourcesCriteria listProjectResourcesCriteria, Map tags) { // TODO Auto-generated method stub return null; } @@ -400,11 +402,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana return null; } - @Override - public List searchForUserVMs(ListVMsCmd cmd) { - // TODO Auto-generated method stub - return null; - } + @Override public Pair> startVirtualMachine(long vmId, Long hostId, Map additionalParams) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { @@ -415,7 +413,7 @@ public class MockUserVmManagerImpl implements UserVmManager, UserVmService, Mana @Override public void prepareStop(VirtualMachineProfile profile) { // TODO Auto-generated method stub - + } /* (non-Javadoc) diff --git a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java index 9752e303a2d..18cce843166 100644 --- a/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java +++ b/server/test/com/cloud/vpc/MockConfigurationManagerImpl.java @@ -25,26 +25,24 @@ import javax.inject.Inject; import javax.naming.ConfigurationException; import javax.naming.NamingException; -import com.cloud.api.commands.CreateDiskOfferingCmd; -import com.cloud.api.commands.CreateNetworkOfferingCmd; -import com.cloud.api.commands.CreateServiceOfferingCmd; -import com.cloud.api.commands.CreateVlanIpRangeCmd; -import com.cloud.api.commands.CreateZoneCmd; -import com.cloud.api.commands.DeleteDiskOfferingCmd; -import com.cloud.api.commands.DeleteNetworkOfferingCmd; -import com.cloud.api.commands.DeletePodCmd; -import com.cloud.api.commands.DeleteServiceOfferingCmd; -import com.cloud.api.commands.DeleteVlanIpRangeCmd; -import com.cloud.api.commands.DeleteZoneCmd; -import com.cloud.api.commands.LDAPConfigCmd; -import com.cloud.api.commands.LDAPRemoveCmd; -import com.cloud.api.commands.ListNetworkOfferingsCmd; -import com.cloud.api.commands.UpdateCfgCmd; -import com.cloud.api.commands.UpdateDiskOfferingCmd; -import com.cloud.api.commands.UpdateNetworkOfferingCmd; -import com.cloud.api.commands.UpdatePodCmd; -import com.cloud.api.commands.UpdateServiceOfferingCmd; -import com.cloud.api.commands.UpdateZoneCmd; +import org.apache.cloudstack.api.command.admin.offering.*; +import org.apache.cloudstack.api.command.admin.config.UpdateCfgCmd; +import org.apache.cloudstack.api.command.admin.network.CreateNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.offering.CreateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.vlan.CreateVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.offering.UpdateServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.UpdatePodCmd; +import org.apache.cloudstack.api.command.admin.vlan.DeleteVlanIpRangeCmd; +import org.apache.cloudstack.api.command.admin.zone.CreateZoneCmd; +import org.apache.cloudstack.api.command.admin.network.DeleteNetworkOfferingCmd; +import org.apache.cloudstack.api.command.admin.pod.DeletePodCmd; +import org.apache.cloudstack.api.command.admin.offering.DeleteServiceOfferingCmd; +import org.apache.cloudstack.api.command.admin.zone.DeleteZoneCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPConfigCmd; +import org.apache.cloudstack.api.command.admin.ldap.LDAPRemoveCmd; +import org.apache.cloudstack.api.command.admin.zone.UpdateZoneCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworkOfferingsCmd; +import org.apache.cloudstack.api.command.admin.network.UpdateNetworkOfferingCmd; import com.cloud.configuration.Configuration; import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationService; @@ -84,7 +82,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi NetworkOfferingDao _ntwkOffDao; /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateConfiguration(com.cloud.api.commands.UpdateCfgCmd) + * @see com.cloud.configuration.ConfigurationService#updateConfiguration(org.apache.cloudstack.api.commands.UpdateCfgCmd) */ @Override public Configuration updateConfiguration(UpdateCfgCmd cmd) { @@ -93,7 +91,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createServiceOffering(com.cloud.api.commands.CreateServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createServiceOffering(org.apache.cloudstack.api.commands.CreateServiceOfferingCmd) */ @Override public ServiceOffering createServiceOffering(CreateServiceOfferingCmd cmd) { @@ -102,7 +100,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateServiceOffering(com.cloud.api.commands.UpdateServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateServiceOffering(org.apache.cloudstack.api.commands.UpdateServiceOfferingCmd) */ @Override public ServiceOffering updateServiceOffering(UpdateServiceOfferingCmd cmd) { @@ -111,7 +109,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteServiceOffering(com.cloud.api.commands.DeleteServiceOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteServiceOffering(org.apache.cloudstack.api.commands.DeleteServiceOfferingCmd) */ @Override public boolean deleteServiceOffering(DeleteServiceOfferingCmd cmd) { @@ -120,7 +118,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateDiskOffering(com.cloud.api.commands.UpdateDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateDiskOffering(org.apache.cloudstack.api.commands.UpdateDiskOfferingCmd) */ @Override public DiskOffering updateDiskOffering(UpdateDiskOfferingCmd cmd) { @@ -129,7 +127,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteDiskOffering(com.cloud.api.commands.DeleteDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteDiskOffering(org.apache.cloudstack.api.commands.DeleteDiskOfferingCmd) */ @Override public boolean deleteDiskOffering(DeleteDiskOfferingCmd cmd) { @@ -138,7 +136,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createDiskOffering(com.cloud.api.commands.CreateDiskOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createDiskOffering(org.apache.cloudstack.api.commands.CreateDiskOfferingCmd) */ @Override public DiskOffering createDiskOffering(CreateDiskOfferingCmd cmd) { @@ -156,7 +154,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#editPod(com.cloud.api.commands.UpdatePodCmd) + * @see com.cloud.configuration.ConfigurationService#editPod(org.apache.cloudstack.api.commands.UpdatePodCmd) */ @Override public Pod editPod(UpdatePodCmd cmd) { @@ -165,7 +163,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deletePod(com.cloud.api.commands.DeletePodCmd) + * @see com.cloud.configuration.ConfigurationService#deletePod(org.apache.cloudstack.api.commands.DeletePodCmd) */ @Override public boolean deletePod(DeletePodCmd cmd) { @@ -174,7 +172,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createZone(com.cloud.api.commands.CreateZoneCmd) + * @see com.cloud.configuration.ConfigurationService#createZone(org.apache.cloudstack.api.commands.CreateZoneCmd) */ @Override public DataCenter createZone(CreateZoneCmd cmd) { @@ -183,7 +181,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#editZone(com.cloud.api.commands.UpdateZoneCmd) + * @see com.cloud.configuration.ConfigurationService#editZone(org.apache.cloudstack.api.commands.UpdateZoneCmd) */ @Override public DataCenter editZone(UpdateZoneCmd cmd) { @@ -192,7 +190,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteZone(com.cloud.api.commands.DeleteZoneCmd) + * @see com.cloud.configuration.ConfigurationService#deleteZone(org.apache.cloudstack.api.commands.DeleteZoneCmd) */ @Override public boolean deleteZone(DeleteZoneCmd cmd) { @@ -201,7 +199,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createVlanAndPublicIpRange(com.cloud.api.commands.CreateVlanIpRangeCmd) + * @see com.cloud.configuration.ConfigurationService#createVlanAndPublicIpRange(org.apache.cloudstack.api.commands.CreateVlanIpRangeCmd) */ @Override public Vlan createVlanAndPublicIpRange(CreateVlanIpRangeCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceUnavailableException, ResourceAllocationException { @@ -219,7 +217,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteVlanIpRange(com.cloud.api.commands.DeleteVlanIpRangeCmd) + * @see com.cloud.configuration.ConfigurationService#deleteVlanIpRange(org.apache.cloudstack.api.commands.DeleteVlanIpRangeCmd) */ @Override public boolean deleteVlanIpRange(DeleteVlanIpRangeCmd cmd) { @@ -228,7 +226,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#createNetworkOffering(com.cloud.api.commands.CreateNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#createNetworkOffering(org.apache.cloudstack.api.commands.CreateNetworkOfferingCmd) */ @Override public NetworkOffering createNetworkOffering(CreateNetworkOfferingCmd cmd) { @@ -237,7 +235,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateNetworkOffering(com.cloud.api.commands.UpdateNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#updateNetworkOffering(org.apache.cloudstack.api.commands.UpdateNetworkOfferingCmd) */ @Override public NetworkOffering updateNetworkOffering(UpdateNetworkOfferingCmd cmd) { @@ -246,7 +244,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#searchForNetworkOfferings(com.cloud.api.commands.ListNetworkOfferingsCmd) + * @see com.cloud.configuration.ConfigurationService#searchForNetworkOfferings(org.apache.cloudstack.api.commands.ListNetworkOfferingsCmd) */ @Override public List searchForNetworkOfferings(ListNetworkOfferingsCmd cmd) { @@ -255,7 +253,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#deleteNetworkOffering(com.cloud.api.commands.DeleteNetworkOfferingCmd) + * @see com.cloud.configuration.ConfigurationService#deleteNetworkOffering(org.apache.cloudstack.api.commands.DeleteNetworkOfferingCmd) */ @Override public boolean deleteNetworkOffering(DeleteNetworkOfferingCmd cmd) { @@ -344,7 +342,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#updateLDAP(com.cloud.api.commands.LDAPConfigCmd) + * @see com.cloud.configuration.ConfigurationService#updateLDAP(org.apache.cloudstack.api.commands.LDAPConfigCmd) */ @Override public boolean updateLDAP(LDAPConfigCmd cmd) throws NamingException { @@ -353,7 +351,7 @@ public class MockConfigurationManagerImpl implements ConfigurationManager, Confi } /* (non-Javadoc) - * @see com.cloud.configuration.ConfigurationService#removeLDAP(com.cloud.api.commands.LDAPRemoveCmd) + * @see com.cloud.configuration.ConfigurationService#removeLDAP(org.apache.cloudstack.api.commands.LDAPRemoveCmd) */ @Override public boolean removeLDAP(LDAPRemoveCmd cmd) { diff --git a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java index 95c6ee9df14..4403d75fbd0 100644 --- a/server/test/com/cloud/vpc/MockNetworkManagerImpl.java +++ b/server/test/com/cloud/vpc/MockNetworkManagerImpl.java @@ -26,51 +26,39 @@ import javax.ejb.Local; import javax.inject.Inject; import javax.naming.ConfigurationException; +import org.apache.cloudstack.api.command.admin.usage.ListTrafficTypeImplementorsCmd; +import org.apache.cloudstack.api.command.user.network.ListNetworksCmd; import org.apache.log4j.Logger; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.CreateNetworkCmd; -import com.cloud.api.commands.ListNetworksCmd; -import com.cloud.api.commands.ListTrafficTypeImplementorsCmd; -import com.cloud.api.commands.RestartNetworkCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.user.network.CreateNetworkCmd; +import org.apache.cloudstack.api.command.user.network.RestartNetworkCmd; import com.cloud.dc.DataCenter; import com.cloud.dc.Vlan; 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.LoadBalancingServiceProvider; import com.cloud.network.element.NetworkElement; 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.guru.NetworkGuru; import com.cloud.network.rules.FirewallRule; +import com.cloud.network.rules.FirewallRule.Purpose; +import com.cloud.network.rules.FirewallRule.State; import com.cloud.network.rules.StaticNat; import com.cloud.offering.NetworkOffering; import com.cloud.offerings.NetworkOfferingVO; @@ -80,13 +68,7 @@ import com.cloud.user.User; import com.cloud.utils.Pair; import com.cloud.utils.component.Adapters; 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; @Local(value = { NetworkManager.class, NetworkService.class }) @@ -122,7 +104,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#createGuestNetwork(com.cloud.api.commands.CreateNetworkCmd) + * @see com.cloud.network.NetworkService#createGuestNetwork(org.apache.cloudstack.api.commands.CreateNetworkCmd) */ @Override public Network createGuestNetwork(CreateNetworkCmd cmd) throws InsufficientCapacityException, ConcurrentOperationException, ResourceAllocationException { @@ -131,7 +113,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#searchForNetworks(com.cloud.api.commands.ListNetworksCmd) + * @see com.cloud.network.NetworkService#searchForNetworks(org.apache.cloudstack.api.commands.ListNetworksCmd) */ @Override public List searchForNetworks(ListNetworksCmd cmd) { @@ -149,7 +131,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#restartNetwork(com.cloud.api.commands.RestartNetworkCmd, boolean) + * @see com.cloud.network.NetworkService#restartNetwork(org.apache.cloudstack.api.commands.RestartNetworkCmd, boolean) */ @Override public boolean restartNetwork(RestartNetworkCmd cmd, boolean cleanup) throws ConcurrentOperationException, ResourceUnavailableException, InsufficientCapacityException { @@ -269,7 +251,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ * @see com.cloud.network.NetworkService#searchPhysicalNetworks(java.lang.Long, java.lang.Long, java.lang.String, java.lang.Long, java.lang.Long, java.lang.String) */ @Override - public List searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { + public Pair, Integer> searchPhysicalNetworks(Long id, Long zoneId, String keyword, Long startIndex, Long pageSize, String name) { // TODO Auto-generated method stub return null; } @@ -323,7 +305,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ * @see com.cloud.network.NetworkService#listNetworkServiceProviders(java.lang.Long, java.lang.String, java.lang.String, java.lang.Long, java.lang.Long) */ @Override - public List listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { + public Pair, Integer> listNetworkServiceProviders(Long physicalNetworkId, String name, String state, Long startIndex, Long pageSize) { // TODO Auto-generated method stub return null; } @@ -431,7 +413,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ * @see com.cloud.network.NetworkService#listTrafficTypes(java.lang.Long) */ @Override - public List listTrafficTypes(Long physicalNetworkId) { + public Pair, Integer> listTrafficTypes(Long physicalNetworkId) { // TODO Auto-generated method stub return null; } @@ -455,7 +437,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkService#listTrafficTypeImplementor(com.cloud.api.commands.ListTrafficTypeImplementorsCmd) + * @see com.cloud.network.NetworkService#listTrafficTypeImplementor(org.apache.cloudstack.api.commands.ListTrafficTypeImplementorsCmd) */ @Override public List> listTrafficTypeImplementor(ListTrafficTypeImplementorsCmd cmd) { @@ -555,7 +537,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkManager#setupNetwork(com.cloud.user.Account, com.cloud.offerings.NetworkOfferingVO, com.cloud.network.Network, com.cloud.deploy.DeploymentPlan, java.lang.String, java.lang.String, boolean, java.lang.Long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) + * @see com.cloud.network.NetworkManager#setupNetwork(com.cloud.user.Account, com.cloud.offerings.NetworkOfferingVO, com.cloud.network.Network, com.cloud.deploy.DeploymentPlan, java.lang.String, java.lang.String, boolean, java.lang.Long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) */ @Override public List setupNetwork(Account owner, NetworkOfferingVO offering, Network predefined, DeploymentPlan plan, String name, String displayText, boolean errorIfAlreadySetup, Long domainId, ACLType aclType, @@ -747,7 +729,7 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.NetworkManager#createGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) + * @see com.cloud.network.NetworkManager#createGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, java.lang.Long) */ @Override public Network createGuestNetwork(long networkOfferingId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, Long domainId, @@ -811,6 +793,12 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ return null; } + @Override + public UserDataServiceProvider getUserDataUpdateProvider(Network network) { + // TODO Auto-generated method stub + return null; + } + /* (non-Javadoc) * @see com.cloud.network.NetworkManager#networkIsConfiguredForExternalNetworking(long, long) */ @@ -1488,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; } @@ -1503,4 +1491,33 @@ public class MockNetworkManagerImpl implements NetworkManager, Manager{ return 0; } + @Override + public boolean isNetworkInlineMode(Network network) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List getProvidersForServiceInNetwork(Network network, Service service) { + // TODO Auto-generated method stub + return null; + } + + @Override + public StaticNatServiceProvider getStaticNatProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } + + @Override + public int getRuleCountForIp(Long addressId, Purpose purpose, State state) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public LoadBalancingServiceProvider getLoadBalancingProviderForNetwork(Network network) { + // TODO Auto-generated method stub + return null; + } } diff --git a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java index cb052ed64e4..a0c7b70190c 100644 --- a/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java +++ b/server/test/com/cloud/vpc/MockResourceLimitManagerImpl.java @@ -70,6 +70,13 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag return 0; } + + @Override + public long findCorrectResourceLimitForAccount(short accountType, Long limit, ResourceType type) { + // TODO Auto-generated method stub + return 0; + } + /* (non-Javadoc) * @see com.cloud.user.ResourceLimitService#findCorrectResourceLimitForDomain(com.cloud.domain.Domain, com.cloud.configuration.Resource.ResourceType) */ @@ -85,7 +92,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void incrementResourceCount(long accountId, ResourceType type, Long... delta) { // TODO Auto-generated method stub - + } /* (non-Javadoc) @@ -94,7 +101,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void decrementResourceCount(long accountId, ResourceType type, Long... delta) { // TODO Auto-generated method stub - + } /* (non-Javadoc) @@ -103,7 +110,7 @@ public class MockResourceLimitManagerImpl implements ResourceLimitService, Manag @Override public void checkResourceLimit(Account account, ResourceType type, long... count) throws ResourceAllocationException { // TODO Auto-generated method stub - + } /* (non-Javadoc) diff --git a/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java b/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java index 4cd742ca4a3..c112f31f73b 100644 --- a/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java +++ b/server/test/com/cloud/vpc/MockSite2SiteVpnManagerImpl.java @@ -22,17 +22,16 @@ import java.util.Map; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.api.commands.CreateVpnConnectionCmd; -import com.cloud.api.commands.CreateVpnCustomerGatewayCmd; -import com.cloud.api.commands.CreateVpnGatewayCmd; -import com.cloud.api.commands.DeleteVpnConnectionCmd; -import com.cloud.api.commands.DeleteVpnCustomerGatewayCmd; -import com.cloud.api.commands.DeleteVpnGatewayCmd; -import com.cloud.api.commands.ListVpnConnectionsCmd; -import com.cloud.api.commands.ListVpnCustomerGatewaysCmd; -import com.cloud.api.commands.ListVpnGatewaysCmd; -import com.cloud.api.commands.ResetVpnConnectionCmd; -import com.cloud.api.commands.UpdateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.*; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.CreateVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnConnectionCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnCustomerGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.DeleteVpnGatewayCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnConnectionsCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnCustomerGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.ListVpnGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpn.UpdateVpnCustomerGatewayCmd; import com.cloud.exception.NetworkRuleConflictException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.Site2SiteCustomerGateway; @@ -41,6 +40,7 @@ import com.cloud.network.Site2SiteVpnConnectionVO; import com.cloud.network.Site2SiteVpnGateway; import com.cloud.network.vpn.Site2SiteVpnManager; import com.cloud.network.vpn.Site2SiteVpnService; +import com.cloud.utils.Pair; import com.cloud.utils.component.Manager; import com.cloud.vm.DomainRouterVO; @@ -48,7 +48,7 @@ import com.cloud.vm.DomainRouterVO; public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2SiteVpnService, Manager{ /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnGateway(com.cloud.api.commands.CreateVpnGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnGateway(org.apache.cloudstack.api.commands.CreateVpnGatewayCmd) */ @Override public Site2SiteVpnGateway createVpnGateway(CreateVpnGatewayCmd cmd) { @@ -57,7 +57,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createCustomerGateway(com.cloud.api.commands.CreateVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createCustomerGateway(org.apache.cloudstack.api.commands.CreateVpnCustomerGatewayCmd) */ @Override public Site2SiteCustomerGateway createCustomerGateway(CreateVpnCustomerGatewayCmd cmd) { @@ -84,7 +84,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnConnection(com.cloud.api.commands.CreateVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#createVpnConnection(org.apache.cloudstack.api.commands.CreateVpnConnectionCmd) */ @Override public Site2SiteVpnConnection createVpnConnection(CreateVpnConnectionCmd cmd) throws NetworkRuleConflictException { @@ -93,7 +93,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteCustomerGateway(com.cloud.api.commands.DeleteVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteCustomerGateway(org.apache.cloudstack.api.commands.DeleteVpnCustomerGatewayCmd) */ @Override public boolean deleteCustomerGateway(DeleteVpnCustomerGatewayCmd deleteVpnCustomerGatewayCmd) { @@ -102,7 +102,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnGateway(com.cloud.api.commands.DeleteVpnGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnGateway(org.apache.cloudstack.api.commands.DeleteVpnGatewayCmd) */ @Override public boolean deleteVpnGateway(DeleteVpnGatewayCmd deleteVpnGatewayCmd) { @@ -111,7 +111,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnConnection(com.cloud.api.commands.DeleteVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#deleteVpnConnection(org.apache.cloudstack.api.commands.DeleteVpnConnectionCmd) */ @Override public boolean deleteVpnConnection(DeleteVpnConnectionCmd deleteVpnConnectionCmd) throws ResourceUnavailableException { @@ -120,7 +120,7 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#resetVpnConnection(com.cloud.api.commands.ResetVpnConnectionCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#resetVpnConnection(org.apache.cloudstack.api.commands.ResetVpnConnectionCmd) */ @Override public Site2SiteVpnConnection resetVpnConnection(ResetVpnConnectionCmd resetVpnConnectionCmd) throws ResourceUnavailableException { @@ -129,34 +129,34 @@ public class MockSite2SiteVpnManagerImpl implements Site2SiteVpnManager, Site2Si } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForCustomerGateways(com.cloud.api.commands.ListVpnCustomerGatewaysCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForCustomerGateways(org.apache.cloudstack.api.commands.ListVpnCustomerGatewaysCmd) */ @Override - public List searchForCustomerGateways(ListVpnCustomerGatewaysCmd listVpnCustomerGatewaysCmd) { + public Pair, Integer> searchForCustomerGateways(ListVpnCustomerGatewaysCmd listVpnCustomerGatewaysCmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnGateways(com.cloud.api.commands.ListVpnGatewaysCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnGateways(org.apache.cloudstack.api.commands.ListVpnGatewaysCmd) */ @Override - public List searchForVpnGateways(ListVpnGatewaysCmd listVpnGatewaysCmd) { + public Pair, Integer> searchForVpnGateways(ListVpnGatewaysCmd listVpnGatewaysCmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnConnections(com.cloud.api.commands.ListVpnConnectionsCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#searchForVpnConnections(org.apache.cloudstack.api.commands.ListVpnConnectionsCmd) */ @Override - public List searchForVpnConnections(ListVpnConnectionsCmd listVpnConnectionsCmd) { + public Pair, Integer> searchForVpnConnections(ListVpnConnectionsCmd listVpnConnectionsCmd) { // TODO Auto-generated method stub return null; } /* (non-Javadoc) - * @see com.cloud.network.vpn.Site2SiteVpnService#updateCustomerGateway(com.cloud.api.commands.UpdateVpnCustomerGatewayCmd) + * @see com.cloud.network.vpn.Site2SiteVpnService#updateCustomerGateway(org.apache.cloudstack.api.commands.UpdateVpnCustomerGatewayCmd) */ @Override public Site2SiteCustomerGateway updateCustomerGateway(UpdateVpnCustomerGatewayCmd updateVpnCustomerGatewayCmd) { diff --git a/server/test/com/cloud/vpc/MockVpcManagerImpl.java b/server/test/com/cloud/vpc/MockVpcManagerImpl.java index fc10a466087..25799d19b9e 100644 --- a/server/test/com/cloud/vpc/MockVpcManagerImpl.java +++ b/server/test/com/cloud/vpc/MockVpcManagerImpl.java @@ -23,9 +23,9 @@ import java.util.Set; import javax.ejb.Local; import javax.naming.ConfigurationException; -import com.cloud.acl.ControlledEntity.ACLType; -import com.cloud.api.commands.ListPrivateGatewaysCmd; -import com.cloud.api.commands.ListStaticRoutesCmd; +import org.apache.cloudstack.acl.ControlledEntity.ACLType; +import org.apache.cloudstack.api.command.user.vpc.ListPrivateGatewaysCmd; +import org.apache.cloudstack.api.command.user.vpc.ListStaticRoutesCmd; import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.InsufficientAddressCapacityException; import com.cloud.exception.InsufficientCapacityException; @@ -49,6 +49,7 @@ import com.cloud.network.vpc.VpcService; import com.cloud.offering.NetworkOffering; import com.cloud.user.Account; import com.cloud.user.User; +import com.cloud.utils.Pair; import com.cloud.utils.component.ComponentLocator; import com.cloud.utils.component.Manager; import com.cloud.vm.DomainRouterVO; @@ -241,10 +242,10 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcService#listPrivateGateway(com.cloud.api.commands.ListPrivateGatewaysCmd) + * @see com.cloud.network.vpc.VpcService#listPrivateGateway(org.apache.cloudstack.api.commands.ListPrivateGatewaysCmd) */ @Override - public List listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd) { + public Pair, Integer> listPrivateGateway(ListPrivateGatewaysCmd listPrivateGatewaysCmd) { // TODO Auto-generated method stub return null; } @@ -286,10 +287,10 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcService#listStaticRoutes(com.cloud.api.commands.ListStaticRoutesCmd) + * @see com.cloud.network.vpc.VpcService#listStaticRoutes(org.apache.cloudstack.api.commands.ListStaticRoutesCmd) */ @Override - public List listStaticRoutes(ListStaticRoutesCmd cmd) { + public Pair, Integer> listStaticRoutes(ListStaticRoutesCmd cmd) { // TODO Auto-generated method stub return null; } @@ -343,7 +344,7 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ * @see com.cloud.network.vpc.VpcManager#destroyVpc(com.cloud.network.vpc.Vpc) */ @Override - public boolean destroyVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean destroyVpc(Vpc vpc, Account caller, Long callerUserId) throws ConcurrentOperationException, ResourceUnavailableException { // TODO Auto-generated method stub return false; } @@ -394,7 +395,7 @@ public class MockVpcManagerImpl implements VpcManager, Manager{ } /* (non-Javadoc) - * @see com.cloud.network.vpc.VpcManager#createVpcGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, com.cloud.acl.ControlledEntity.ACLType, java.lang.Boolean, long, com.cloud.user.Account) + * @see com.cloud.network.vpc.VpcManager#createVpcGuestNetwork(long, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, com.cloud.user.Account, java.lang.Long, com.cloud.network.PhysicalNetwork, long, org.apache.cloudstack.acl.ControlledEntity.ACLType, java.lang.Boolean, long, com.cloud.user.Account) */ @Override public Network createVpcGuestNetwork(long ntwkOffId, String name, String displayText, String gateway, String cidr, String vlanId, String networkDomain, Account owner, Long domainId, PhysicalNetwork pNtwk, diff --git a/server/test/com/cloud/vpc/VpcApiUnitTest.java b/server/test/com/cloud/vpc/VpcApiUnitTest.java index ad323d29e5b..5cc325ffac0 100644 --- a/server/test/com/cloud/vpc/VpcApiUnitTest.java +++ b/server/test/com/cloud/vpc/VpcApiUnitTest.java @@ -193,7 +193,7 @@ public class VpcApiUnitTest extends TestCase{ protected void destroyVpc() { try { - _vpcService.destroyVpc(_vpcService.getVpc(1)); + _vpcService.destroyVpc(_vpcService.getVpc(1), new AccountVO(), 1L); } catch (Exception ex) { s_logger.error("Destroy VPC TEST FAILED due to exc ", ex); } diff --git a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java index 2a675b3a217..7c9a5823516 100644 --- a/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java +++ b/server/test/com/cloud/vpc/dao/MockNetworkDaoImpl.java @@ -342,4 +342,19 @@ 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; + } + + @Override + public List listRedundantNetworks() { + // TODO Auto-generated method stub + return null; + } + } diff --git a/server/test/com/cloud/vpc/dao/MockVpcVirtualRouterElement.java b/server/test/com/cloud/vpc/dao/MockVpcVirtualRouterElement.java index 5d759b8aa3a..8b9d362276d 100644 --- a/server/test/com/cloud/vpc/dao/MockVpcVirtualRouterElement.java +++ b/server/test/com/cloud/vpc/dao/MockVpcVirtualRouterElement.java @@ -20,10 +20,11 @@ import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ResourceUnavailableException; import com.cloud.network.element.VpcVirtualRouterElement; import com.cloud.network.vpc.Vpc; +import com.cloud.vm.ReservationContext; public class MockVpcVirtualRouterElement extends VpcVirtualRouterElement{ @Override - public boolean shutdownVpc(Vpc vpc) throws ConcurrentOperationException, ResourceUnavailableException { + public boolean shutdownVpc(Vpc vpc, ReservationContext context) throws ConcurrentOperationException, ResourceUnavailableException { return true; } diff --git a/setup/apidoc/generatetoc_footer.xsl b/setup/apidoc/generatetoc_footer.xsl deleted file mode 100644 index 5bc2cf46659..00000000000 --- a/setup/apidoc/generatetoc_footer.xsl +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - diff --git a/setup/bindir/cloud-set-guest-password.in b/setup/bindir/cloud-set-guest-password.in index 97e6e3d7bee..321589466c4 100755 --- a/setup/bindir/cloud-set-guest-password.in +++ b/setup/bindir/cloud-set-guest-password.in @@ -27,7 +27,7 @@ user=root # Add your DHCP lease folders here -DHCP_FOLDERS="/var/lib/dhclient/* /var/lib/dhcp3/*" +DHCP_FOLDERS="/var/lib/dhclient/* /var/lib/dhcp3/* /var/lib/dhcp/*" password_received=0 file_count=0 error_count=0 @@ -39,7 +39,7 @@ do file_count=$((file_count+1)) PASSWORD_SERVER_IP=$(grep dhcp-server-identifier $DHCP_FILE | tail -1 | awk '{print $NF}' | tr -d '\;') - if [ -n $PASSWORD_SERVER_IP ] + if [ -n "$PASSWORD_SERVER_IP" ] then logger -t "cloud" "Found password server IP $PASSWORD_SERVER_IP in $DHCP_FILE" logger -t "cloud" "Sending request to password server at $PASSWORD_SERVER_IP" @@ -95,7 +95,7 @@ then fi logger -t "cloud" "Changing password ..." -echo $password | passwd --stdin $user +echo $user:$password | chpasswd if [ $? -gt 0 ] then diff --git a/setup/bindir/cloud-set-guest-sshkey.in b/setup/bindir/cloud-set-guest-sshkey.in index 69124dca4c1..15008b8d514 100755 --- a/setup/bindir/cloud-set-guest-sshkey.in +++ b/setup/bindir/cloud-set-guest-sshkey.in @@ -40,7 +40,7 @@ do file_count=$((file_count+1)) SSHKEY_SERVER_IP=$(grep dhcp-server-identifier $DHCP_FILE | tail -1 | awk '{print $NF}' | tr -d '\;') - if [ -n $SSHKEY_SERVER_IP ] + if [ -n "$SSHKEY_SERVER_IP" ] then logger -t "cloud" "Sending request to ssh key server at $SSHKEY_SERVER_IP" diff --git a/setup/bindir/cloud-setup-databases.in b/setup/bindir/cloud-setup-databases.in index 040be5b06bf..e50aa29aa62 100755 --- a/setup/bindir/cloud-setup-databases.in +++ b/setup/bindir/cloud-setup-databases.in @@ -77,12 +77,12 @@ class DBDeployer(object): def backUpDbDotProperties(): dbpPath = os.path.join(self.dbConfPath, 'db.properties') copyPath = os.path.join(self.dbConfPath, 'db.properties.origin') - + if os.path.isfile(dbpPath): shutil.copy2(dbpPath, copyPath) - + backUpDbDotProperties() - + def postRun(self): def cleanOrRecoverDbDotProperties(): dbpPath = os.path.join(self.dbConfPath, 'db.properties') @@ -91,24 +91,24 @@ class DBDeployer(object): if not self.success: shutil.copy2(copyPath, dbpPath) os.remove(copyPath) - + cleanOrRecoverDbDotProperties() if os.path.exists(self.tmpMysqlFile): os.remove(self.tmpMysqlFile) - - + + def info(self, msg, result=None): output = "" if msg is not None: output = "%-80s"%msg - + if result is True: output += "[ \033[92m%-2s\033[0m ]\n"%"OK" elif result is False: output += "[ \033[91m%-6s\033[0m ]\n"%"FAILED" sys.stdout.write(output) sys.stdout.flush() - + def debug(self, msg): msg = "DEBUG:%s"%msg sys.stdout.write(msg) @@ -121,13 +121,13 @@ class DBDeployer(object): else: self.dbDotProperties[key] = (value, self.dbDotPropertiesIndex) self.dbDotPropertiesIndex += 1 - + def getDbProperty(self, key): if not self.dbDotProperties.has_key(key): return None (value, index) = self.dbDotProperties[key] return value - + def runMysql(self, text, table, isRoot=False): kwargs = {} if not isRoot: @@ -136,7 +136,7 @@ class DBDeployer(object): else: kwargs['user'] = self.rootuser if self.rootpassword != '': kwargs['passwd'] = self.rootpassword - + kwargs['port'] = self.port kwargs['host'] = self.host @@ -148,7 +148,7 @@ class DBDeployer(object): mysqlCmds.append('<') mysqlCmds.append(self.tmpMysqlFile) runCmd(mysqlCmds) - + except Exception, e: err = '''Encountering an error when executing mysql script ---------------------------------------------------------------------- @@ -163,13 +163,13 @@ Sql parameters: ---------------------------------------------------------------------- '''%(table, e.__str__(), kwargs) self.errorAndExit(err) - + def errorAndExit(self, msg): self.postRun() err = '''\n\nWe apologize for below error: -*************************************************************** +*************************************************************** %s -*************************************************************** +*************************************************************** Please run: cloud-setup-database -h @@ -184,7 +184,7 @@ for full help if not self.rootuser: self.info("No mysql root user specified, will not create Cloud DB schema\n", None) return - + replacements = ( ("CREATE USER cloud identified by 'cloud';", "CREATE USER %s@`localhost` identified by '%s'; CREATE USER %s@`%%` identified by '%s';"%( @@ -211,8 +211,8 @@ for full help ("CALL `test`.`drop_user_if_exists`() ;", ""), ) - - for f in ["create-database","create-schema","create-database-premium","create-schema-premium"]: + + for f in ["create-database","create-schema", "create-database-premium","create-schema-premium", "create-schema-view"]: p = os.path.join(self.dbFilesPath,"%s.sql"%f) if not os.path.exists(p): continue text = file(p).read() @@ -220,7 +220,7 @@ for full help self.info("Applying %s"%p) self.runMysql(text, p, True) self.info(None, True) - + if self.serversetup: conf = os.path.join(self.dbConfPath, 'db.properties') pcp = os.path.pathsep.join( glob.glob( os.path.join ( r"@PREMIUMJAVADIR@" , "*" ) ) ) @@ -243,21 +243,21 @@ for full help self.info("Applying %s"%p) self.runMysql(text, p, True) self.info(None, True) - + for f in ["templates","create-index-fk"]: p = os.path.join(self.dbFilesPath,"%s.sql"%f) text = file(p).read() self.info("Applying %s"%p) self.runMysql(text, p, True) self.info(None, True) - + p = os.path.join(self.dbFilesPath,"schema-level.sql") if os.path.isfile(p): text = file(p).read() self.info("Applying %s"%p) self.runMysql(text, p, True) self.info(None, True) - + awsApiDbDir = '/usr/share/cloud/setup/bridge/db' for f in ["cloudbridge_db.sql"]: p = os.path.join(awsApiDbDir,f) @@ -277,7 +277,7 @@ for full help self.info("Applying %s"%p) self.runMysql(text, p, True) self.info(None, True) - + def prepareDBFiles(self): def prepareDBDotProperties(): dbpPath = os.path.join(self.dbConfPath, 'db.properties') @@ -289,7 +289,7 @@ for full help line = line.strip() if line.startswith("#"): key = line; value = ''; passed = True if line == '' or line == '\n': key = self.magicString + str(emptyLine); value = ''; emptyLine += 1; passed = True - + try: if not passed: (key, value) = line.split('=', 1) @@ -312,9 +312,9 @@ for example: self.errorAndExit(err) self.putDbProperty(key, value) self.info("Preparing %s"%dbpPath, True) - + prepareDBDotProperties() - + def finalize(self): def finalizeDbProperties(): entries = [] @@ -327,12 +327,12 @@ for example: else: entries.insert(index, "%s=%s"%(key, value)) file(os.path.join(self.dbConfPath, 'db.properties'), 'w').write('\n'.join(entries)) - + self.info("Finalizing setup ...", None) finalizeDbProperties() self.info(None, True) self.success = True # At here, we have done successfully and nothing more after this flag is set - + def grabSystemInfo(self): def getIpAddr(): try: @@ -346,10 +346,11 @@ for example: return '127.0.0.1' except Exception, e: return "127.0.0.1" - - self.ip = getIpAddr() - self.info("Detected local IP address as %s, will use as cluster management server node IP"%self.ip, True) - + + if not self.ip: + self.ip = getIpAddr() + self.info("Detected local IP address as %s, will use as cluster management server node IP" % self.ip, True) + def checkSystemSetup(self): def checkCloudDbFiles(): self.info("Checking Cloud database files ...", None) @@ -357,25 +358,25 @@ for example: for dbf in dbfpaths: if not os.path.exists(dbf): self.errorAndExit("Cannot find %s"%dbf) - - coreSchemas = ['create-database.sql', 'create-schema.sql', 'templates.sql', 'create-index-fk.sql'] + + coreSchemas = ['create-database.sql', 'create-schema.sql', 'create-schema-view.sql', 'templates.sql', 'create-index-fk.sql'] if not self.serversetup: coreSchemas.append('server-setup.sql') - + checkingList = [os.path.join(self.dbFilesPath, x) for x in coreSchemas] checkingList.append(self.encryptionJarPath) for f in checkingList: if not os.path.isfile(f): self.errorAndExit("Cloud DB required file %s was not found"%f) self.info(None, True) - + def checkDbserverHostname(): self.info("Checking mysql server hostname ...", None) if resolves_to_ipv6(self, self.port): err = "%s resolves to an IPv6 address. The CloudStack does not support IPv6 yet.\nPlease fix this issue in either /etc/hosts or your DNS configuration.\n"%self.host self.errorAndExit(err) self.info(None, True) - + def checkHostName(): self.info("Checking local machine hostname ...", None) try: @@ -384,7 +385,7 @@ for example: err = "The host name of this computer does not resolve to an IP address.\nPlease use your operating system's network setup tools to fix this ('hostname --fqdn' %s).\n"%e.__str__() self.errorAndExit(err) self.info(None, True) - + def checkSELinux(): self.info("Checking SELinux setup ...", None) try: @@ -395,54 +396,54 @@ for example: if e.errno == 2: pass else: self.errorAndExit(e.__str__()) self.info(None, True) - + checkCloudDbFiles() checkHostName() checkSELinux() - + def processEncryptionStuff(self): def encrypt(input): cmd = ['java','-classpath',self.encryptionJarPath,'org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI', 'encrypt.sh', 'input=%s'%input, 'password=%s'%self.mgmtsecretkey,'verbose=false'] return runCmd(cmd).strip('\n') - + def saveMgmtServerSecretKey(): if self.encryptiontype == 'file': file(self.encryptionKeyFile, 'w').write(self.mgmtsecretkey) - + def formatEncryptResult(value): return 'ENC(%s)'%value - + def encryptDBSecretKey(): self.putDbProperty('db.cloud.encrypt.secret', formatEncryptResult(encrypt(self.dbsecretkey))) - + def encryptDBPassword(): dbPassword = self.getDbProperty('db.cloud.password') if dbPassword == '': return # Don't encrypt empty password if dbPassword == None: self.errorAndExit('Cannot find db.cloud.password in %s'%os.path.join(self.dbConfPath, 'db.properties')) self.putDbProperty('db.cloud.password', formatEncryptResult(encrypt(dbPassword))) - + usagePassword = self.getDbProperty('db.usage.password') if usagePassword == '': return # Don't encrypt empty password if usagePassword == None: self.errorAndExit('Cannot find db.usage.password in %s'%os.path.join(self.dbConfPath, 'db.properties')) self.putDbProperty('db.usage.password', formatEncryptResult(encrypt(usagePassword))) - + self.info("Processing encryption ...", None) self.putDbProperty("db.cloud.encryption.type", self.encryptiontype) saveMgmtServerSecretKey() encryptDBSecretKey() encryptDBPassword() self.info(None, True) - + def parseOptions(self): def parseOtherOptions(): if self.options.rootcreds: self.rootuser,self.rootpassword = parseUserAndPassword(self.options.rootcreds) if self.rootuser == self.user: self.errorAndExit("--deploy-as= user name cannot be the user name supplied for the connection credentials") - + self.info("Mysql root user name:%s"%self.rootuser, True) self.info("Mysql root user password:%s"%self.rootpassword, True) - + if self.options.serversetup: if not self.options.rootcreds: self.errorAndExit("--auto= requires valid --deploy-as= credentials") @@ -450,12 +451,16 @@ for example: self.errorAndExit("%s is not a valid file"%self.options.serversetup) self.serversetup = self.options.serversetup self.info("User specified server-setup.sql file at %s"%self.serversetup, True) - + + if self.options.mshostip: + self.ip = self.options.mshostip + self.info("Using specified cluster management server node IP %s" % self.options.mshostip, True) + self.encryptiontype = self.options.encryptiontype self.mgmtsecretkey = self.options.mgmtsecretkey self.dbsecretkey = self.options.dbsecretkey self.isDebug = self.options.debug - + def parseUserAndPassword(cred): stuff = cred.split(':') if len(stuff) != 1 and len(stuff) != 2: @@ -467,13 +472,13 @@ for example: password = '' else: password = stuff[1] - + forbidden = "' \\`" for f in forbidden: if f in user: self.errorAndExit("User name cannot have the %r characters"%f) if f in password: self.errorAndExit("Password cannot have the %r characters"%f) return user, password - + def parseCasualCredit(): def parseHostInfo(info): stuff = info.split(":") @@ -488,18 +493,26 @@ for example: else: self.errorAndExit("Invalid host and port format, it must be in format of host:port (%s)"%info) return host, port - + if len(self.args) == 0: self.errorAndExit("Please specify user:password@hostname") if len(self.args) > 1: self.errorAndExit("There are more than one parameters for user:password@hostname (%s)"%self.args) - + arg = self.args[0] - stuff = arg.split("@", 1) - if len(stuff) == 1: stuff.append("localhost") + try: + try: + splitIndex = arg.rindex('@') + except ValueError: + # If it failed to find @, use host=localhost + splitIndex = len(arg) + arg += "@localhost" + finally: + stuff = [arg[:splitIndex], arg[splitIndex+1:]] + self.user,self.password = parseUserAndPassword(stuff[0]) self.host,self.port = parseHostInfo(stuff[1]) - + self.info("Mysql user name:%s"%self.user, True) if self.password: self.info("Mysql user password:%s"%self.password, True) @@ -507,32 +520,32 @@ for example: self.info("Mysql user password:", True) self.info("Mysql server ip:%s"%self.host, True) self.info("Mysql server port:%s"%self.port, True) - + def validateParameters(): if self.encryptiontype != 'file' and self.encryptiontype != 'web': self.errorAndExit('Wrong encryption type %s, --encrypt-type can only be "file" or "web'%self.encryptiontype) - + #---------------------- option parsing and command line checks ------------------------ usage = """%prog user:[password]@mysqlhost:[port] [--deploy-as=rootuser:[rootpassword]] [--auto=/path/to/server-setup.xml] [-e ENCRYPTIONTYPE] [-m MGMTSECRETKEY] [-k DBSECRETKEY] [--debug] - + This command sets up the CloudStack Management Server and CloudStack Usage Server database configuration (connection credentials and host information) based on the first argument. - + If the the --deploy-as option is present, this command will also connect to the database using the administrative credentials specified as the value for the --deploy-as argument, construct the database environment needed to run the CloudStack Management Server, and alter the password specified for the user in the first argument. In this case, the user name specified in --deploy-as= cannot be the same as the user name specified for the connection credentials that the CloudStack Management Server will be set up with. - + If a server-setup.xml cloud setup information file is specified with the --auto option, this command will also construct a customized database environment according to the cloud setup information in the file. - + The port and the password are optional and can be left out.. If host is omitted altogether, it will default to localhost. - + Examples: - - %prog cloud:secret + + %prog cloud:secret sets user cloud and password 'secret' up in @MSCONF@/db.properties, using localhost as the database server - - %prog sheng:rules@192.168.1.1 + + %prog sheng:rules@192.168.1.1 sets these credentials up in @MSCONF@/db.properties - + %prog alex:founder@1.2.3.4 --deploy-as=root:nonsense sets alex up as the MySQL user, then connects as the root user with password 'nonsense', and recreates the databases, creating @@ -542,7 +555,7 @@ for example: In addition actions performing in above example, using 'password' as management server encryption key and 'dbpassword' as database encryption key, saving management server encryption key to a file as the encryption type specified by -e is file. - + %prog alena:tests@5.6.7.8 --deploy-as=root:nonsense --auto=/root/server-setup.xml sets alena up as the MySQL user, then connects as the root user with password 'nonsense' to server 5.6.7.8, then recreates the @@ -562,12 +575,14 @@ for example: help="Secret key used to encrypt confidential parameters in db.properties. A string, default is password") self.parser.add_option("-k", "--database-secretkey", action="store", type="string", dest="dbsecretkey", default="password", help="Secret key used to encrypt sensitive database values. A string, default is password") - + self.parser.add_option("-i", "--mshost", action="store", type="string", dest="mshostip", default="", + help="Cluster management server host IP. A string, by default it will try to detect a local IP") + (self.options, self.args) = self.parser.parse_args() parseCasualCredit() parseOtherOptions() validateParameters() - + def run(self): try: self.preRun() @@ -580,7 +595,7 @@ for example: self.finalize() finally: self.postRun() - + print '' print "CloudStack has successfully initialized database, you can check your database configuration in %s"%os.path.join(self.dbConfPath, 'db.properties') print '' @@ -588,4 +603,4 @@ for example: if __name__ == "__main__": o = DBDeployer() o.run() - + diff --git a/setup/db/clouddev.sql b/setup/db/clouddev.sql deleted file mode 100644 index 10ad3b2513e..00000000000 --- a/setup/db/clouddev.sql +++ /dev/null @@ -1,33 +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. - - -UPDATE `cloud`.`configuration` SET value = 'true' where name = 'use.local.storage'; -UPDATE `cloud`.`configuration` SET value = 'true' where name = 'system.vm.use.local.storage'; -INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, use_local_storage, type) VALUES (17, 'tinyOffering', UUID(), 'tinyOffering', NOW(), 1, 'Service'); -INSERT INTO `cloud`.`service_offering` (id, cpu, speed, ram_size) VALUES (17, 1, 100, 100); -INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, type, disk_size) VALUES (18, 'tinyDiskOffering', UUID(), 'tinyDiskOffering', NOW(), 'Disk', 1073741824); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('router.ram.size', '100'); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('router.cpu.mhz','100'); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('console.ram.size','100'); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('console.cpu.mhz', '100'); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('ssvm.ram.size','100'); -INSERT INTO `cloud`.`configuration` (name,value) VALUE('ssvm.cpu.mhz','100'); -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'; -UPDATE `cloud`.`vm_template` SET unique_name="tiny Linux",name="tiny Linux",url="http://nfs1.lab.vmops.com/templates/ttylinux_pv.vhd",checksum="046e134e642e6d344b34648223ba4bc1",display_text="tiny Linux" where id=5; 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..facfefc5e75 100644 --- a/setup/db/create-schema-simulator.sql +++ b/setup/db/create-schema-simulator.sql @@ -14,6 +14,7 @@ -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. +use simulator; DROP TABLE IF EXISTS `simulator`.`mockhost`; DROP TABLE IF EXISTS `simulator`.`mocksecstorage`; @@ -76,6 +77,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-view.sql b/setup/db/create-schema-view.sql new file mode 100755 index 00000000000..f502c88a90d --- /dev/null +++ b/setup/db/create-schema-view.sql @@ -0,0 +1,784 @@ +-- 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. +use cloud; + +--- DB views for list api --- +DROP VIEW IF EXISTS `cloud`.`user_vm_view`; +CREATE VIEW `cloud`.`user_vm_view` AS +select +vm_instance.id id, +vm_instance.name name, +user_vm.display_name display_name, +user_vm.user_data user_data, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +instance_group.id instance_group_id, +instance_group.uuid instance_group_uuid, +instance_group.name instance_group_name, +vm_instance.uuid uuid, +vm_instance.last_host_id last_host_id, +vm_instance.vm_type type, +vm_instance.vnc_password vnc_password, +vm_instance.limit_cpu_use limit_cpu_use, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.ha_enabled ha_enabled, +vm_instance.hypervisor_type hypervisor_type, +vm_instance.instance_name instance_name, +vm_instance.guest_os_id guest_os_id, +guest_os.uuid guest_os_uuid, +vm_instance.pod_id pod_id, +host_pod_ref.uuid pod_uuid, +vm_instance.private_ip_address private_ip_address, +vm_instance.private_mac_address private_mac_address, +vm_instance.vm_type vm_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.is_security_group_enabled security_group_enabled, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.name template_name, +vm_template.display_text template_display_text, +vm_template.enable_password password_enabled, +iso.id iso_id, +iso.uuid iso_uuid, +iso.name iso_name, +iso.display_text iso_display_text, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +service_offering.cpu cpu, +service_offering.speed speed, +service_offering.ram_size ram_size, +disk_offering.name service_offering_name, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.pool_type pool_type, +volumes.id volume_id, +volumes.uuid volume_uuid, +volumes.device_id volume_device_id, +volumes.volume_type volume_type, +security_group.id security_group_id, +security_group.uuid security_group_uuid, +security_group.name security_group_name, +security_group.description security_group_description, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +user_ip_address.id public_ip_id, +user_ip_address.uuid public_ip_uuid, +user_ip_address.public_ip_address public_ip_address, +ssh_keypairs.keypair_name keypair_name, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user_vm +inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join guest_os on vm_instance.guest_os_id = guest_os.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id +left join instance_group on instance_group_vm_map.group_id=instance_group.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join vm_template iso on iso.id=user_vm.iso_id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id +left join security_group on security_group_vm_map.security_group_id=security_group.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join user_ip_address on user_ip_address.vm_id=vm_instance.id +left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" +left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value +left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`domain_router_view`; +CREATE VIEW domain_router_view AS +select +vm_instance.id id, +vm_instance.name name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +vm_instance.uuid uuid, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.pod_id pod_id, +vm_instance.instance_name instance_name, +host_pod_ref.uuid pod_uuid, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.dns1 dns1, +data_center.dns2 dns2, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +disk_offering.name service_offering_name, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.name network_name, +networks.network_domain network_domain, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id, +domain_router.template_version template_version, +domain_router.scripts_version scripts_version, +domain_router.is_redundant_router is_redundant_router, +domain_router.redundant_state redundant_state, +domain_router.stop_pending stop_pending +from domain_router +inner join vm_instance on vm_instance.id = domain_router.id +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`security_group_view`; +CREATE VIEW security_group_view AS +select +security_group.id id, +security_group.name name, +security_group.description description, +security_group.uuid uuid, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +security_group_rule.id rule_id, +security_group_rule.uuid rule_uuid, +security_group_rule.type rule_type, +security_group_rule.start_port rule_start_port, +security_group_rule.end_port rule_end_port, +security_group_rule.protocol rule_protocol, +security_group_rule.allowed_network_id rule_allowed_network_id, +security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, +security_group_rule.create_status rule_create_status, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from security_group +left join security_group_rule on security_group.id = security_group_rule.security_group_id +inner join account on security_group.account_id=account.id +inner join domain on security_group.domain_id=domain.id +left join projects on projects.project_account_id = security_group.account_id +left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" +left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; +CREATE VIEW resource_tag_view AS +select +resource_tags.id, +resource_tags.uuid, +resource_tags.key, +resource_tags.value, +resource_tags.resource_id, +resource_tags.resource_uuid, +resource_tags.resource_type, +resource_tags.customer, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from resource_tags +inner join account on resource_tags.account_id=account.id +inner join domain on resource_tags.domain_id=domain.id +left join projects on projects.project_account_id = resource_tags.account_id; + + +DROP VIEW IF EXISTS `cloud`.`event_view`; +CREATE VIEW event_view AS +select +event.id, +event.uuid, +event.type, +event.state, +event.description, +event.created, +event.level, +event.parameters, +event.start_id, +eve.uuid start_uuid, +event.user_id, +user.username user_name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from event +inner join account on event.account_id=account.id +inner join domain on event.domain_id=domain.id +inner join user on event.user_id = user.id +left join projects on projects.project_account_id = event.account_id +left join event eve on event.start_id = eve.id; + +DROP VIEW IF EXISTS `cloud`.`instance_group_view`; +CREATE VIEW instance_group_view AS +select +instance_group.id, +instance_group.uuid, +instance_group.name, +instance_group.removed, +instance_group.created, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from instance_group +inner join account on instance_group.account_id=account.id +inner join domain on account.domain_id=domain.id +left join projects on projects.project_account_id = instance_group.account_id; + +DROP VIEW IF EXISTS `cloud`.`user_view`; +CREATE VIEW user_view AS +select +user.id, +user.uuid, +user.username, +user.password, +user.firstname, +user.lastname, +user.email, +user.state, +user.api_key, +user.secret_key, +user.created, +user.removed, +user.timezone, +user.registration_token, +user.is_registered, +user.incorrect_login_attempts, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user +inner join account on user.account_id = account.id +inner join domain on account.domain_id=domain.id +left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; + + + + +DROP VIEW IF EXISTS `cloud`.`project_view`; +CREATE VIEW project_view AS +select +projects.id, +projects.uuid, +projects.name, +projects.display_text, +projects.state, +projects.removed, +projects.created, +account.account_name owner, +pacct.account_id, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer +from projects +inner join domain on projects.domain_id=domain.id +inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" +inner join account on account.id = project_account.account_id +left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" +left join project_account pacct on projects.id = pacct.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_account_view`; +CREATE VIEW project_account_view AS +select +project_account.id, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +project_account.account_role, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_account +inner join account on project_account.account_id = account.id +inner join domain on account.domain_id=domain.id +inner join projects on projects.id = project_account.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; +CREATE VIEW project_invitation_view AS +select +project_invitations.id, +project_invitations.uuid, +project_invitations.email, +project_invitations.created, +project_invitations.state, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_invitations +left join account on project_invitations.account_id = account.id +left join domain on project_invitations.domain_id=domain.id +left join projects on projects.id = project_invitations.project_id; + +DROP VIEW IF EXISTS `cloud`.`host_view`; +CREATE VIEW host_view AS +select +host.id, +host.uuid, +host.name, +host.status, +host.disconnected, +host.type, +host.private_ip_address, +host.version, +host.hypervisor_type, +host.hypervisor_version, +host.capabilities, +host.last_ping, +host.created, +host.removed, +host.resource_state, +host.mgmt_server_id, +host.cpus, +host.speed, +host.ram, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +host_tags.tag, +guest_os_category.id guest_os_category_id, +guest_os_category.uuid guest_os_category_uuid, +guest_os_category.name guest_os_category_name, +mem_caps.used_capacity memory_used_capacity, +mem_caps.reserved_capacity memory_reserved_capacity, +cpu_caps.used_capacity cpu_used_capacity, +cpu_caps.reserved_capacity cpu_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from host +left join cluster on host.cluster_id = cluster.id +left join data_center on host.data_center_id = data_center.id +left join host_pod_ref on host.pod_id = host_pod_ref.id +left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" +left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) +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; + +DROP VIEW IF EXISTS `cloud`.`volume_view`; +CREATE VIEW volume_view AS +select +volumes.id, +volumes.uuid, +volumes.name, +volumes.device_id, +volumes.volume_type, +volumes.size, +volumes.created, +volumes.state, +volumes.attached, +volumes.removed, +volumes.pod_id, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +vm_instance.id vm_id, +vm_instance.uuid vm_uuid, +vm_instance.name vm_name, +vm_instance.state vm_state, +vm_instance.vm_type, +user_vm.display_name vm_display_name, +volume_host_ref.size volume_host_size, +volume_host_ref.created volume_host_created, +volume_host_ref.format, +volume_host_ref.download_pct, +volume_host_ref.download_state, +volume_host_ref.error_str, +disk_offering.id disk_offering_id, +disk_offering.uuid disk_offering_uuid, +disk_offering.name disk_offering_name, +disk_offering.display_text disk_offering_display_text, +disk_offering.use_local_storage, +disk_offering.system_use, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.name pool_name, +cluster.hypervisor_type, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.extractable, +vm_template.type template_type, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from volumes +inner join account on volumes.account_id=account.id +inner join domain on volumes.domain_id=domain.id +left join projects on projects.project_account_id = account.id +left join data_center on volumes.data_center_id = data_center.id +left join vm_instance on volumes.instance_id = vm_instance.id +left join user_vm on user_vm.id = vm_instance.id +left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id +left join disk_offering on volumes.disk_offering_id = disk_offering.id +left join storage_pool on volumes.pool_id = storage_pool.id +left join cluster on storage_pool.cluster_id = cluster.id +left join vm_template on volumes.template_id = vm_template.id +left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" +left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; +CREATE VIEW account_netstats_view AS +SELECT account_id, +sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, +sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent +FROM user_statistics +group by account_id; + + +DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; +CREATE VIEW account_vmstats_view AS +SELECT account_id, state, count(*) as vmcount +from vm_instance +group by account_id, state; + +DROP VIEW IF EXISTS `cloud`.`free_ip_view`; +CREATE VIEW free_ip_view AS +select count(user_ip_address.id) free_ip +from user_ip_address +inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" +where state = "Free"; + +DROP VIEW IF EXISTS `cloud`.`account_view`; +CREATE VIEW account_view AS +select +account.id, +account.uuid, +account.account_name, +account.type, +account.state, +account.removed, +account.cleanup_needed, +account.network_domain, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +account_netstats_view.bytesReceived, +account_netstats_view.bytesSent, +vmlimit.max vmLimit, +vmcount.count vmTotal, +runningvm.vmcount runningVms, +stoppedvm.vmcount stoppedVms, +iplimit.max ipLimit, +ipcount.count ipTotal, +free_ip_view.free_ip ipFree, +volumelimit.max volumeLimit, +volumecount.count volumeTotal, +snapshotlimit.max snapshotLimit, +snapshotcount.count snapshotTotal, +templatelimit.max templateLimit, +templatecount.count templateTotal, +vpclimit.max vpcLimit, +vpccount.count vpcTotal, +projectlimit.max projectLimit, +projectcount.count projectTotal, +networklimit.max networkLimit, +networkcount.count networkTotal, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from free_ip_view, account +inner join domain on account.domain_id=domain.id +left join data_center on account.default_zone_id = data_center.id +left join account_netstats_view on account.id = account_netstats_view.account_id +left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" +left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" +left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" +left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" +left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" +left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" +left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" +left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" +left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" +left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" +left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" +left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" +left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" +left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" +left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" +left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" +left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" +left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" +left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`async_job_view`; +CREATE VIEW async_job_view AS +select +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +user.id user_id, +user.uuid user_uuid, +async_job.id, +async_job.uuid, +async_job.job_cmd, +async_job.job_status, +async_job.job_process_status, +async_job.job_result_code, +async_job.job_result, +async_job.created, +async_job.removed, +async_job.instance_type, +async_job.instance_id, +CASE +WHEN async_job.instance_type = 'Volume' THEN volumes.uuid +WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid +WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid +WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid +WHEN async_job.instance_type = 'Host' THEN host.uuid +WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid +WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid +WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid +WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid +WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid +WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid +WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid +WHEN async_job.instance_type = 'Account' THEN acct.uuid +WHEN async_job.instance_type = 'User' THEN us.uuid +WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid +WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid +WHEN async_job.instance_type = 'Counter' THEN counter.uuid +WHEN async_job.instance_type = 'Condition' THEN conditions.uuid +WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid +WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid +WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid +ELSE null +END instance_uuid +from async_job +left join account on async_job.account_id = account.id +left join domain on domain.id = account.domain_id +left join user on async_job.user_id = user.id +left join volumes on async_job.instance_id = volumes.id +left join vm_template on async_job.instance_id = vm_template.id +left join vm_instance on async_job.instance_id = vm_instance.id +left join snapshots on async_job.instance_id = snapshots.id +left join host on async_job.instance_id = host.id +left join storage_pool on async_job.instance_id = storage_pool.id +left join user_ip_address on async_job.instance_id = user_ip_address.id +left join security_group on async_job.instance_id = security_group.id +left join physical_network on async_job.instance_id = physical_network.id +left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id +left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id +left join firewall_rules on async_job.instance_id = firewall_rules.id +left join account acct on async_job.instance_id = acct.id +left join user us on async_job.instance_id = us.id +left join static_routes on async_job.instance_id = static_routes.id +left join vpc_gateways on async_job.instance_id = vpc_gateways.id +left join counter on async_job.instance_id = counter.id +left join conditions on async_job.instance_id = conditions.id +left join autoscale_policies on async_job.instance_id = autoscale_policies.id +left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id +left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; + diff --git a/setup/db/create-schema.sql b/setup/db/create-schema.sql index aa8aeb8e326..3a55751bd72 100755 --- a/setup/db/create-schema.sql +++ b/setup/db/create-schema.sql @@ -146,6 +146,16 @@ 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`; +DROP TABLE IF EXISTS `cloud`.`autoscale_vmgroups`; +DROP TABLE IF EXISTS `cloud`.`autoscale_vmprofiles`; +DROP TABLE IF EXISTS `cloud`.`autoscale_policies`; +DROP TABLE IF EXISTS `cloud`.`counter`; +DROP TABLE IF EXISTS `cloud`.`conditions`; CREATE TABLE `cloud`.`version` ( `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', @@ -156,7 +166,8 @@ CREATE TABLE `cloud`.`version` ( INDEX `i_version__version`(`version`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -INSERT INTO `version` (`version`, `updated`, `step`) VALUES('@VERSION@', now(), 'Complete'); + +INSERT INTO `version` (`version`, `updated`, `step`) VALUES('4.1.0', now(), 'Complete'); CREATE TABLE `cloud`.`op_it_work` ( `id` char(40) COMMENT 'reservation id', @@ -295,8 +306,10 @@ 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', + `inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering LB provider is in inline mode', PRIMARY KEY (`id`), INDEX `i_network_offerings__system_only`(`system_only`), INDEX `i_network_offerings__removed`(`removed`), @@ -471,12 +484,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; @@ -732,12 +747,10 @@ CREATE TABLE `cloud`.`load_balancer_stickiness_policies` ( CREATE TABLE `cloud`.`inline_load_balancer_nic_map` ( `id` bigint unsigned NOT NULL auto_increment, - `load_balancer_id` bigint unsigned NOT NULL, `public_ip_address` char(40) NOT NULL, `nic_id` bigint unsigned NULL COMMENT 'nic id', PRIMARY KEY (`id`), UNIQUE KEY (`nic_id`), - CONSTRAINT `fk_inline_load_balancer_nic_map__load_balancer_id` FOREIGN KEY(`load_balancer_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE, CONSTRAINT `fk_inline_load_balancer_nic_map__nic_id` FOREIGN KEY(`nic_id`) REFERENCES `nics`(`id`) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; @@ -1108,6 +1121,7 @@ CREATE TABLE `cloud`.`upload` ( `id` bigint unsigned NOT NULL auto_increment, `host_id` bigint unsigned NOT NULL, `type_id` bigint unsigned NOT NULL, + `uuid` varchar(40), `type` varchar(255), `mode` varchar(255), `created` DATETIME NOT NULL, @@ -1330,7 +1344,7 @@ CREATE TABLE `cloud`.`async_job` ( `session_key` varchar(64) COMMENT 'all async-job manage to apply session based security enforcement', `instance_type` varchar(64) COMMENT 'instance_type and instance_id work together to allow attaching an instance object to a job', `instance_id` bigint unsigned, - `job_cmd` varchar(64) NOT NULL COMMENT 'command name', + `job_cmd` varchar(255) NOT NULL COMMENT 'command name', `job_cmd_originator` varchar(64) COMMENT 'command originator', `job_cmd_info` text COMMENT 'command parameter info', `job_cmd_ver` int(1) COMMENT 'command version', @@ -1363,16 +1377,15 @@ CREATE TABLE `cloud`.`sync_queue` ( `id` bigint unsigned NOT NULL auto_increment, `sync_objtype` varchar(64) NOT NULL, `sync_objid` bigint unsigned NOT NULL, - `queue_proc_msid` bigint, `queue_proc_number` bigint COMMENT 'process number, increase 1 for each iteration', - `queue_proc_time` datetime COMMENT 'last time to process the queue', `created` datetime COMMENT 'date created', `last_updated` datetime COMMENT 'date created', + `queue_size` smallint DEFAULT 0 COMMENT 'number of items being processed by the queue', + `queue_size_limit` smallint DEFAULT 1 COMMENT 'max number of items the queue can process concurrently', PRIMARY KEY (`id`), UNIQUE `i_sync_queue__objtype__objid`(`sync_objtype`, `sync_objid`), INDEX `i_sync_queue__created`(`created`), - INDEX `i_sync_queue__last_updated`(`last_updated`), - INDEX `i_sync_queue__queue_proc_time`(`queue_proc_time`) + INDEX `i_sync_queue__last_updated`(`last_updated`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`stack_maid` ( @@ -1393,13 +1406,15 @@ CREATE TABLE `cloud`.`sync_queue_item` ( `content_id` bigint, `queue_proc_msid` bigint COMMENT 'owner msid when the queue item is being processed', `queue_proc_number` bigint COMMENT 'used to distinguish raw items and items being in process', + `queue_proc_time` datetime COMMENT 'when processing started for the item', `created` datetime COMMENT 'time created', PRIMARY KEY (`id`), CONSTRAINT `fk_sync_queue_item__queue_id` FOREIGN KEY `fk_sync_queue_item__queue_id` (`queue_id`) REFERENCES `sync_queue` (`id`) ON DELETE CASCADE, INDEX `i_sync_queue_item__queue_id`(`queue_id`), INDEX `i_sync_queue_item__created`(`created`), INDEX `i_sync_queue_item__queue_proc_number`(`queue_proc_number`), - INDEX `i_sync_queue_item__queue_proc_msid`(`queue_proc_msid`) + INDEX `i_sync_queue_item__queue_proc_msid`(`queue_proc_msid`), + INDEX `i_sync_queue__queue_proc_time`(`queue_proc_time`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `cloud`.`disk_offering` ( @@ -1841,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', @@ -2032,7 +2077,6 @@ CREATE TABLE `cloud`.`external_load_balancer_devices` ( `device_state` varchar(32) NOT NULL DEFAULT 'Disabled' COMMENT 'state (enabled/disabled/shutdown) of the device', `allocation_state` varchar(32) NOT NULL DEFAULT 'Free' COMMENT 'Allocation state (Free/Shared/Dedicated/Provider) of the device', `is_dedicated` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if device/appliance is provisioned for dedicated use only', - `is_inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if load balancer will be used in in-line configuration with firewall', `is_managed` int(1) unsigned NOT NULL DEFAULT 0 COMMENT '1 if load balancer appliance is provisioned and its life cycle is managed by by cloudstack', `host_id` bigint unsigned NOT NULL COMMENT 'host id coresponding to the external load balancer device', `parent_host_id` bigint unsigned COMMENT 'if the load balancer appliance is cloudstack managed, then host id on which this appliance is provisioned', @@ -2371,5 +2415,135 @@ CREATE TABLE `cloud`.`nicira_nvp_nic_map` ( PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `cloud`.`nicira_nvp_router_map` ( + `id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', + `logicalrouter_uuid` varchar(255) NOT NULL UNIQUE COMMENT 'nicira uuid of logical router', + `network_id` bigint unsigned NOT NULL UNIQUE COMMENT 'cloudstack id of the network', + PRIMARY KEY (`id`), + CONSTRAINT `fk_nicira_nvp_router_map__network_id` FOREIGN KEY (`network_id`) REFERENCES `networks`(`id`) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`counter` ( + `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', + `uuid` varchar(40), + `source` varchar(255) NOT NULL COMMENT 'source e.g. netscaler, snmp', + `name` varchar(255) NOT NULL COMMENT 'Counter name', + `value` varchar(255) NOT NULL COMMENT 'Value in case of source=snmp', + `removed` datetime COMMENT 'date removed if not null', + `created` datetime NOT NULL COMMENT 'date created', + PRIMARY KEY (`id`), + CONSTRAINT `uc_counter__uuid` UNIQUE (`uuid`), + INDEX `i_counter__removed`(`removed`), + INDEX `i_counter__source`(`source`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`conditions` ( + `id` bigint unsigned NOT NULL UNIQUE AUTO_INCREMENT COMMENT 'id', + `uuid` varchar(40), + `counter_id` bigint unsigned NOT NULL COMMENT 'Counter Id', + `threshold` bigint unsigned NOT NULL COMMENT 'threshold value for the given counter', + `relational_operator` char(2) COMMENT 'relational operator to be used upon the counter and condition', + `domain_id` bigint unsigned NOT NULL COMMENT 'domain the Condition belongs to', + `account_id` bigint unsigned NOT NULL COMMENT 'owner of this Condition', + `removed` datetime COMMENT 'date removed if not null', + `created` datetime NOT NULL COMMENT 'date created', + PRIMARY KEY (`id`), + CONSTRAINT `fk_conditions__counter_id` FOREIGN KEY `fk_condition__counter_id`(`counter_id`) REFERENCES `counter`(`id`), + CONSTRAINT `fk_conditions__account_id` FOREIGN KEY `fk_condition__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_conditions__domain_id` FOREIGN KEY `fk_condition__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, + CONSTRAINT `uc_conditions__uuid` UNIQUE (`uuid`), + INDEX `i_conditions__removed`(`removed`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`autoscale_vmprofiles` ( + `id` bigint unsigned NOT NULL auto_increment, + `uuid` varchar(40), + `zone_id` bigint unsigned NOT NULL, + `domain_id` bigint unsigned NOT NULL, + `account_id` bigint unsigned NOT NULL, + `autoscale_user_id` bigint unsigned NOT NULL, + `service_offering_id` bigint unsigned NOT NULL, + `template_id` bigint unsigned NOT NULL, + `other_deploy_params` varchar(1024) COMMENT 'other deployment parameters that is in addition to zoneid,serviceofferingid,domainid', + `destroy_vm_grace_period` int unsigned COMMENT 'the time allowed for existing connections to get closed before a vm is destroyed', + `counter_params` varchar(1024) COMMENT 'the parameters for the counter to be used to get metric information from VMs', + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_autoscale_vmprofiles__domain_id` FOREIGN KEY `fk_autoscale_vmprofiles__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmprofiles__account_id` FOREIGN KEY `fk_autoscale_vmprofiles__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmprofiles__autoscale_user_id` FOREIGN KEY `fk_autoscale_vmprofiles__autoscale_user_id` (`autoscale_user_id`) REFERENCES `user`(`id`) ON DELETE CASCADE, + CONSTRAINT `uc_autoscale_vmprofiles__uuid` UNIQUE (`uuid`), + INDEX `i_autoscale_vmprofiles__removed`(`removed`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`autoscale_policies` ( + `id` bigint unsigned NOT NULL auto_increment, + `uuid` varchar(40), + `domain_id` bigint unsigned NOT NULL, + `account_id` bigint unsigned NOT NULL, + `duration` int unsigned NOT NULL, + `quiet_time` int unsigned NOT NULL, + `action` varchar(15), + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_autoscale_policies__domain_id` FOREIGN KEY `fk_autoscale_policies__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_policies__account_id` FOREIGN KEY `fk_autoscale_policies__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `uc_autoscale_policies__uuid` UNIQUE (`uuid`), + INDEX `i_autoscale_policies__removed`(`removed`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`autoscale_vmgroups` ( + `id` bigint unsigned NOT NULL auto_increment, + `uuid` varchar(40), + `zone_id` bigint unsigned NOT NULL, + `domain_id` bigint unsigned NOT NULL, + `account_id` bigint unsigned NOT NULL, + `load_balancer_id` bigint unsigned NOT NULL, + `min_members` int unsigned DEFAULT 1, + `max_members` int unsigned NOT NULL, + `member_port` int unsigned NOT NULL, + `interval` int unsigned NOT NULL, + `profile_id` bigint unsigned NOT NULL, + `state` varchar(255) NOT NULL COMMENT 'enabled or disabled, a vmgroup is disabled to stop autoscaling activity', + `created` datetime NOT NULL COMMENT 'date created', + `removed` datetime COMMENT 'date removed if not null', + PRIMARY KEY (`id`), + CONSTRAINT `fk_autoscale_vmgroup__autoscale_vmprofile_id` FOREIGN KEY(`profile_id`) REFERENCES `autoscale_vmprofiles`(`id`), + CONSTRAINT `fk_autoscale_vmgroup__load_balancer_id` FOREIGN KEY(`load_balancer_id`) REFERENCES `load_balancing_rules`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmgroups__domain_id` FOREIGN KEY `fk_autoscale_vmgroups__domain_id` (`domain_id`) REFERENCES `domain`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmgroups__account_id` FOREIGN KEY `fk_autoscale_vmgroups__account_id` (`account_id`) REFERENCES `account`(`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmgroups__zone_id` FOREIGN KEY `fk_autoscale_vmgroups__zone_id`(`zone_id`) REFERENCES `data_center`(`id`), + CONSTRAINT `uc_autoscale_vmgroups__uuid` UNIQUE (`uuid`), + INDEX `i_autoscale_vmgroups__removed`(`removed`), + INDEX `i_autoscale_vmgroups__load_balancer_id`(`load_balancer_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`autoscale_policy_condition_map` ( + `id` bigint unsigned NOT NULL auto_increment, + `policy_id` bigint unsigned NOT NULL, + `condition_id` bigint unsigned NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_autoscale_policy_condition_map__policy_id` FOREIGN KEY `fk_autoscale_policy_condition_map__policy_id` (`policy_id`) REFERENCES `autoscale_policies` (`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_policy_condition_map__condition_id` FOREIGN KEY `fk_autoscale_policy_condition_map__condition_id` (`condition_id`) REFERENCES `conditions` (`id`), + INDEX `i_autoscale_policy_condition_map__policy_id`(`policy_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +CREATE TABLE `cloud`.`autoscale_vmgroup_policy_map` ( + `id` bigint unsigned NOT NULL auto_increment, + `vmgroup_id` bigint unsigned NOT NULL, + `policy_id` bigint unsigned NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_autoscale_vmgroup_policy_map__vmgroup_id` FOREIGN KEY `fk_autoscale_vmgroup_policy_map__vmgroup_id` (`vmgroup_id`) REFERENCES `autoscale_vmgroups` (`id`) ON DELETE CASCADE, + CONSTRAINT `fk_autoscale_vmgroup_policy_map__policy_id` FOREIGN KEY `fk_autoscale_vmgroup_policy_map__policy_id` (`policy_id`) REFERENCES `autoscale_policies` (`id`), + INDEX `i_autoscale_vmgroup_policy_map__vmgroup_id`(`vmgroup_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (1,'snmp','Linux User CPU - percentage', '1.3.6.1.4.1.2021.11.9.0', now()); +INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (2,'snmp','Linux System CPU - percentage', '1.3.6.1.4.1.2021.11.10.0', now()); +INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (3,'snmp','Linux CPU Idle - percentage', '1.3.6.1.4.1.2021.11.11.0', now()); +INSERT INTO `cloud`.`counter` (id, source, name, value,created) VALUES (100,'netscaler','Response Time - microseconds', 'RESPTIME', now()); + SET foreign_key_checks = 1; 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 new file mode 100644 index 00000000000..11423200c86 --- /dev/null +++ b/setup/db/db/schema-40to410.sql @@ -0,0 +1,907 @@ +-- 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. + +--; +-- Schema upgrade from 4.0.0 to 4.1.0; +--; + +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__swift_id`(`s3_id`), + INDEX `i_template_s3_ref__template_id`(`template_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', 's3.enable', 'false', 'enable s3'); + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'NetworkManager', 'router.check.poolsize' , '10', 'Numbers of threads using to check redundant router status.'); + +ALTER TABLE `cloud`.`snapshots` ADD COLUMN `s3_id` bigint unsigned COMMENT 'S3 to which this snapshot will be stored'; + +ALTER TABLE `cloud`.`snapshots` ADD CONSTRAINT `fk_snapshots__s3_id` FOREIGN KEY `fk_snapshots__s3_id` (`s3_id`) REFERENCES `s3` (`id`); + +ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `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.' AFTER `elastic_ip_service`; +ALTER TABLE `cloud`.`network_offerings` ADD COLUMN `inline` int(1) unsigned NOT NULL DEFAULT 0 COMMENT 'Is this network offering LB provider is in inline mode'; + +ALTER TABLE `cloud`.`external_load_balancer_devices` DROP COLUMN `is_inline`; + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Network','DEFAULT','NetworkManager','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.'); + +ALTER TABLE `sync_queue` ADD `queue_size` SMALLINT NOT NULL DEFAULT '0' COMMENT 'number of items being processed by the queue'; + +ALTER TABLE `sync_queue` ADD `queue_size_limit` SMALLINT NOT NULL DEFAULT '1' COMMENT 'max number of items the queue can process concurrently'; + +ALTER TABLE `sync_queue_item` ADD `queue_proc_time` DATETIME NOT NULL COMMENT 'when processing started for the item' AFTER `queue_proc_number`; + +ALTER TABLE `cloud`.`inline_load_balancer_nic_map` DROP FOREIGN KEY fk_inline_load_balancer_nic_map__load_balancer_id; + +ALTER TABLE `cloud`.`inline_load_balancer_nic_map` DROP COLUMN load_balancer_id; + +ALTER TABLE upload ADD uuid VARCHAR(40); +ALTER TABLE async_job modify job_cmd VARCHAR(255); + +-- populate uuid column with db id if uuid is null +UPDATE `cloud`.`account` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`alert` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`async_job` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`cluster` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`data_center` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`disk_offering` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`domain` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`event` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_firewall_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_load_balancer_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`external_nicira_nvp_devices` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`firewall_rules` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`guest_os` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`guest_os_category` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`host` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`host_pod_ref` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`hypervisor_capabilities` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`instance_group` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`load_balancer_stickiness_policies` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_external_firewall_device_map` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_external_lb_device_map` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`network_offerings` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`networks` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`nics` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network_service_providers` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`physical_network_traffic_types` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`port_profile` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`project_invitations` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`projects` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`resource_tags` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_customer_gateway` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_vpn_connection` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`s2s_vpn_gateway` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`security_group` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`security_group_rule` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`snapshot_schedule` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`snapshots` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`static_routes` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`storage_pool` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`swift` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`upload` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user_ip_address` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`user_vm_temp` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`virtual_router_providers` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`virtual_supervisor_module` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vlan` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vm_instance` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vm_template` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc_gateways` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpc_offerings` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`vpn_users` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`volumes` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_vmgroups` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_vmprofiles` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`autoscale_policies` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`counter` set uuid=id WHERE uuid is NULL; +UPDATE `cloud`.`conditions` set uuid=id WHERE uuid is NULL; + +INSERT IGNORE INTO `cloud`.`configuration` VALUES ('Advanced', 'DEFAULT', 'management-server', '"detail.batch.query.size"', '2000', 'Default entity detail batch query size for listing'); + +--- DB views for list api --- +DROP VIEW IF EXISTS `cloud`.`user_vm_view`; +CREATE VIEW `cloud`.`user_vm_view` AS +select +vm_instance.id id, +vm_instance.name name, +user_vm.display_name display_name, +user_vm.user_data user_data, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +instance_group.id instance_group_id, +instance_group.uuid instance_group_uuid, +instance_group.name instance_group_name, +vm_instance.uuid uuid, +vm_instance.last_host_id last_host_id, +vm_instance.vm_type type, +vm_instance.vnc_password vnc_password, +vm_instance.limit_cpu_use limit_cpu_use, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.ha_enabled ha_enabled, +vm_instance.hypervisor_type hypervisor_type, +vm_instance.instance_name instance_name, +vm_instance.guest_os_id guest_os_id, +guest_os.uuid guest_os_uuid, +vm_instance.pod_id pod_id, +host_pod_ref.uuid pod_uuid, +vm_instance.private_ip_address private_ip_address, +vm_instance.private_mac_address private_mac_address, +vm_instance.vm_type vm_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.is_security_group_enabled security_group_enabled, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.name template_name, +vm_template.display_text template_display_text, +vm_template.enable_password password_enabled, +iso.id iso_id, +iso.uuid iso_uuid, +iso.name iso_name, +iso.display_text iso_display_text, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +service_offering.cpu cpu, +service_offering.speed speed, +service_offering.ram_size ram_size, +disk_offering.name service_offering_name, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.pool_type pool_type, +volumes.id volume_id, +volumes.uuid volume_uuid, +volumes.device_id volume_device_id, +volumes.volume_type volume_type, +security_group.id security_group_id, +security_group.uuid security_group_uuid, +security_group.name security_group_name, +security_group.description security_group_description, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +user_ip_address.id public_ip_id, +user_ip_address.uuid public_ip_uuid, +user_ip_address.public_ip_address public_ip_address, +ssh_keypairs.keypair_name keypair_name, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user_vm +inner join vm_instance on vm_instance.id = user_vm.id and vm_instance.removed is NULL +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join guest_os on vm_instance.guest_os_id = guest_os.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join instance_group_vm_map on vm_instance.id=instance_group_vm_map.instance_id +left join instance_group on instance_group_vm_map.group_id=instance_group.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join vm_template iso on iso.id=user_vm.iso_id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join security_group_vm_map on vm_instance.id=security_group_vm_map.instance_id +left join security_group on security_group_vm_map.security_group_id=security_group.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join user_ip_address on user_ip_address.vm_id=vm_instance.id +left join user_vm_details on user_vm_details.vm_id=vm_instance.id and user_vm_details.name = "SSH.PublicKey" +left join ssh_keypairs on ssh_keypairs.public_key = user_vm_details.value +left join resource_tags on resource_tags.resource_id = vm_instance.id and resource_tags.resource_type = "UserVm" +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "VirtualMachine" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`domain_router_view`; +CREATE VIEW domain_router_view AS +select +vm_instance.id id, +vm_instance.name name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +vm_instance.uuid uuid, +vm_instance.created created, +vm_instance.state state, +vm_instance.removed removed, +vm_instance.pod_id pod_id, +vm_instance.instance_name instance_name, +host_pod_ref.uuid pod_uuid, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +data_center.dns1 dns1, +data_center.dns2 dns2, +host.id host_id, +host.uuid host_uuid, +host.name host_name, +vm_template.id template_id, +vm_template.uuid template_uuid, +service_offering.id service_offering_id, +disk_offering.uuid service_offering_uuid, +disk_offering.name service_offering_name, +nics.id nic_id, +nics.uuid nic_uuid, +nics.network_id network_id, +nics.ip4_address ip_address, +nics.default_nic is_default_nic, +nics.gateway gateway, +nics.netmask netmask, +nics.mac_address mac_address, +nics.broadcast_uri broadcast_uri, +nics.isolation_uri isolation_uri, +vpc.id vpc_id, +vpc.uuid vpc_uuid, +networks.uuid network_uuid, +networks.name network_name, +networks.network_domain network_domain, +networks.traffic_type traffic_type, +networks.guest_type guest_type, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id, +domain_router.template_version template_version, +domain_router.scripts_version scripts_version, +domain_router.is_redundant_router is_redundant_router, +domain_router.redundant_state redundant_state, +domain_router.stop_pending stop_pending +from domain_router +inner join vm_instance on vm_instance.id = domain_router.id +inner join account on vm_instance.account_id=account.id +inner join domain on vm_instance.domain_id=domain.id +left join host_pod_ref on vm_instance.pod_id = host_pod_ref.id +left join projects on projects.project_account_id = account.id +left join data_center on vm_instance.data_center_id=data_center.id +left join host on vm_instance.host_id=host.id +left join vm_template on vm_instance.vm_template_id=vm_template.id +left join service_offering on vm_instance.service_offering_id=service_offering.id +left join disk_offering on vm_instance.service_offering_id=disk_offering.id +left join volumes on vm_instance.id=volumes.instance_id +left join storage_pool on volumes.pool_id=storage_pool.id +left join nics on vm_instance.id=nics.instance_id +left join networks on nics.network_id=networks.id +left join vpc on networks.vpc_id = vpc.id +left join async_job on async_job.instance_id = vm_instance.id and async_job.instance_type = "DomainRouter" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`security_group_view`; +CREATE VIEW security_group_view AS +select +security_group.id id, +security_group.name name, +security_group.description description, +security_group.uuid uuid, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +security_group_rule.id rule_id, +security_group_rule.uuid rule_uuid, +security_group_rule.type rule_type, +security_group_rule.start_port rule_start_port, +security_group_rule.end_port rule_end_port, +security_group_rule.protocol rule_protocol, +security_group_rule.allowed_network_id rule_allowed_network_id, +security_group_rule.allowed_ip_cidr rule_allowed_ip_cidr, +security_group_rule.create_status rule_create_status, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from security_group +left join security_group_rule on security_group.id = security_group_rule.security_group_id +inner join account on security_group.account_id=account.id +inner join domain on security_group.domain_id=domain.id +left join projects on projects.project_account_id = security_group.account_id +left join resource_tags on resource_tags.resource_id = security_group.id and resource_tags.resource_type = "SecurityGroup" +left join async_job on async_job.instance_id = security_group.id and async_job.instance_type = "SecurityGroup" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`resource_tag_view`; +CREATE VIEW resource_tag_view AS +select +resource_tags.id, +resource_tags.uuid, +resource_tags.key, +resource_tags.value, +resource_tags.resource_id, +resource_tags.resource_uuid, +resource_tags.resource_type, +resource_tags.customer, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from resource_tags +inner join account on resource_tags.account_id=account.id +inner join domain on resource_tags.domain_id=domain.id +left join projects on projects.project_account_id = resource_tags.account_id; + + +DROP VIEW IF EXISTS `cloud`.`event_view`; +CREATE VIEW event_view AS +select +event.id, +event.uuid, +event.type, +event.state, +event.description, +event.created, +event.level, +event.parameters, +event.start_id, +eve.uuid start_uuid, +event.user_id, +user.username user_name, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from event +inner join account on event.account_id=account.id +inner join domain on event.domain_id=domain.id +inner join user on event.user_id = user.id +left join projects on projects.project_account_id = event.account_id +left join event eve on event.start_id = eve.id; + +DROP VIEW IF EXISTS `cloud`.`instance_group_view`; +CREATE VIEW instance_group_view AS +select +instance_group.id, +instance_group.uuid, +instance_group.name, +instance_group.removed, +instance_group.created, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name +from instance_group +inner join account on instance_group.account_id=account.id +inner join domain on account.domain_id=domain.id +left join projects on projects.project_account_id = instance_group.account_id; + +DROP VIEW IF EXISTS `cloud`.`user_view`; +CREATE VIEW user_view AS +select +user.id, +user.uuid, +user.username, +user.password, +user.firstname, +user.lastname, +user.email, +user.state, +user.api_key, +user.secret_key, +user.created, +user.removed, +user.timezone, +user.registration_token, +user.is_registered, +user.incorrect_login_attempts, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from user +inner join account on user.account_id = account.id +inner join domain on account.domain_id=domain.id +left join async_job on async_job.instance_id = user.id and async_job.instance_type = "User" and async_job.job_status = 0; + + +DROP VIEW IF EXISTS `cloud`.`project_view`; +CREATE VIEW project_view AS +select +projects.id, +projects.uuid, +projects.name, +projects.display_text, +projects.state, +projects.removed, +projects.created, +account.account_name owner, +pacct.account_id, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer +from projects +inner join domain on projects.domain_id=domain.id +inner join project_account on projects.id = project_account.project_id and project_account.account_role = "Admin" +inner join account on account.id = project_account.account_id +left join resource_tags on resource_tags.resource_id = projects.id and resource_tags.resource_type = "Project" +left join project_account pacct on projects.id = pacct.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_account_view`; +CREATE VIEW project_account_view AS +select +project_account.id, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +project_account.account_role, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_account +inner join account on project_account.account_id = account.id +inner join domain on account.domain_id=domain.id +inner join projects on projects.id = project_account.project_id; + +DROP VIEW IF EXISTS `cloud`.`project_invitation_view`; +CREATE VIEW project_invitation_view AS +select +project_invitations.id, +project_invitations.uuid, +project_invitations.email, +project_invitations.created, +project_invitations.state, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +account.id account_id, +account.uuid account_uuid, +account.account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path +from project_invitations +left join account on project_invitations.account_id = account.id +left join domain on project_invitations.domain_id=domain.id +left join projects on projects.id = project_invitations.project_id; + +DROP VIEW IF EXISTS `cloud`.`host_view`; +CREATE VIEW host_view AS +select +host.id, +host.uuid, +host.name, +host.status, +host.disconnected, +host.type, +host.private_ip_address, +host.version, +host.hypervisor_type, +host.hypervisor_version, +host.capabilities, +host.last_ping, +host.created, +host.removed, +host.resource_state, +host.mgmt_server_id, +host.cpus, +host.speed, +host.ram, +cluster.id cluster_id, +cluster.uuid cluster_uuid, +cluster.name cluster_name, +cluster.cluster_type, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +host_pod_ref.id pod_id, +host_pod_ref.uuid pod_uuid, +host_pod_ref.name pod_name, +host_tags.tag, +guest_os_category.id guest_os_category_id, +guest_os_category.uuid guest_os_category_uuid, +guest_os_category.name guest_os_category_name, +mem_caps.used_capacity memory_used_capacity, +mem_caps.reserved_capacity memory_reserved_capacity, +cpu_caps.used_capacity cpu_used_capacity, +cpu_caps.reserved_capacity cpu_reserved_capacity, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from host +left join cluster on host.cluster_id = cluster.id +left join data_center on host.data_center_id = data_center.id +left join host_pod_ref on host.pod_id = host_pod_ref.id +left join host_details on host.id = host_details.id and host_details.name = "guest.os.category.id" +left join guest_os_category on guest_os_category.id = CONVERT( host_details.value, UNSIGNED ) +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; + +DROP VIEW IF EXISTS `cloud`.`volume_view`; +CREATE VIEW volume_view AS +select +volumes.id, +volumes.uuid, +volumes.name, +volumes.device_id, +volumes.volume_type, +volumes.size, +volumes.created, +volumes.state, +volumes.attached, +volumes.removed, +volumes.pod_id, +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +projects.id project_id, +projects.uuid project_uuid, +projects.name project_name, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +vm_instance.id vm_id, +vm_instance.uuid vm_uuid, +vm_instance.name vm_name, +vm_instance.state vm_state, +vm_instance.vm_type, +user_vm.display_name vm_display_name, +volume_host_ref.size volume_host_size, +volume_host_ref.created volume_host_created, +volume_host_ref.format, +volume_host_ref.download_pct, +volume_host_ref.download_state, +volume_host_ref.error_str, +disk_offering.id disk_offering_id, +disk_offering.uuid disk_offering_uuid, +disk_offering.name disk_offering_name, +disk_offering.display_text disk_offering_display_text, +disk_offering.use_local_storage, +disk_offering.system_use, +storage_pool.id pool_id, +storage_pool.uuid pool_uuid, +storage_pool.name pool_name, +cluster.hypervisor_type, +vm_template.id template_id, +vm_template.uuid template_uuid, +vm_template.extractable, +vm_template.type template_type, +resource_tags.id tag_id, +resource_tags.uuid tag_uuid, +resource_tags.key tag_key, +resource_tags.value tag_value, +resource_tags.domain_id tag_domain_id, +resource_tags.account_id tag_account_id, +resource_tags.resource_id tag_resource_id, +resource_tags.resource_uuid tag_resource_uuid, +resource_tags.resource_type tag_resource_type, +resource_tags.customer tag_customer, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from volumes +inner join account on volumes.account_id=account.id +inner join domain on volumes.domain_id=domain.id +left join projects on projects.project_account_id = account.id +left join data_center on volumes.data_center_id = data_center.id +left join vm_instance on volumes.instance_id = vm_instance.id +left join user_vm on user_vm.id = vm_instance.id +left join volume_host_ref on volumes.id = volume_host_ref.volume_id and volumes.data_center_id = volume_host_ref.zone_id +left join disk_offering on volumes.disk_offering_id = disk_offering.id +left join storage_pool on volumes.pool_id = storage_pool.id +left join cluster on storage_pool.cluster_id = cluster.id +left join vm_template on volumes.template_id = vm_template.id +left join resource_tags on resource_tags.resource_id = volumes.id and resource_tags.resource_type = "Volume" +left join async_job on async_job.instance_id = volumes.id and async_job.instance_type = "Volume" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`account_netstats_view`; +CREATE VIEW account_netstats_view AS +SELECT account_id, +sum(net_bytes_received)+ sum(current_bytes_received) as bytesReceived, +sum(net_bytes_sent)+ sum(current_bytes_sent) as bytesSent +FROM user_statistics +group by account_id; + + +DROP VIEW IF EXISTS `cloud`.`account_vmstats_view`; +CREATE VIEW account_vmstats_view AS +SELECT account_id, state, count(*) as vmcount +from vm_instance +group by account_id, state; + +DROP VIEW IF EXISTS `cloud`.`free_ip_view`; +CREATE VIEW free_ip_view AS +select count(user_ip_address.id) free_ip +from user_ip_address +inner join vlan on vlan.id = user_ip_address.vlan_db_id and vlan.vlan_type = "VirtualNetwork" +where state = "Free" + +DROP VIEW IF EXISTS `cloud`.`account_view`; +CREATE VIEW account_view AS +select +account.id, +account.uuid, +account.account_name, +account.type, +account.state, +account.removed, +account.cleanup_needed, +account.network_domain, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +data_center.id data_center_id, +data_center.uuid data_center_uuid, +data_center.name data_center_name, +account_netstats_view.bytesReceived, +account_netstats_view.bytesSent, +vmlimit.max vmLimit, +vmcount.count vmTotal, +runningvm.vmcount runningVms, +stoppedvm.vmcount stoppedVms, +iplimit.max ipLimit, +ipcount.count ipTotal, +free_ip_view.free_ip ipFree, +volumelimit.max volumeLimit, +volumecount.count volumeTotal, +snapshotlimit.max snapshotLimit, +snapshotcount.count snapshotTotal, +templatelimit.max templateLimit, +templatecount.count templateTotal, +vpclimit.max vpcLimit, +vpccount.count vpcTotal, +projectlimit.max projectLimit, +projectcount.count projectTotal, +networklimit.max networkLimit, +networkcount.count networkTotal, +async_job.id job_id, +async_job.uuid job_uuid, +async_job.job_status job_status, +async_job.account_id job_account_id +from free_ip_view, account +inner join domain on account.domain_id=domain.id +left join data_center on account.default_zone_id = data_center.id +left join account_netstats_view on account.id = account_netstats_view.account_id +left join resource_limit vmlimit on account.id = vmlimit.account_id and vmlimit.type = "user_vm" +left join resource_count vmcount on account.id = vmcount.account_id and vmcount.type = "user_vm" +left join account_vmstats_view runningvm on account.id = runningvm.account_id and runningvm.state = "Running" +left join account_vmstats_view stoppedvm on account.id = stoppedvm.account_id and stoppedvm.state = "Stopped" +left join resource_limit iplimit on account.id = iplimit.account_id and iplimit.type = "public_ip" +left join resource_count ipcount on account.id = ipcount.account_id and ipcount.type = "public_ip" +left join resource_limit volumelimit on account.id = volumelimit.account_id and volumelimit.type = "volume" +left join resource_count volumecount on account.id = volumecount.account_id and volumecount.type = "volume" +left join resource_limit snapshotlimit on account.id = snapshotlimit.account_id and snapshotlimit.type = "snapshot" +left join resource_count snapshotcount on account.id = snapshotcount.account_id and snapshotcount.type = "snapshot" +left join resource_limit templatelimit on account.id = templatelimit.account_id and templatelimit.type = "template" +left join resource_count templatecount on account.id = templatecount.account_id and templatecount.type = "template" +left join resource_limit vpclimit on account.id = vpclimit.account_id and vpclimit.type = "vpc" +left join resource_count vpccount on account.id = vpccount.account_id and vpccount.type = "vpc" +left join resource_limit projectlimit on account.id = projectlimit.account_id and projectlimit.type = "project" +left join resource_count projectcount on account.id = projectcount.account_id and projectcount.type = "project" +left join resource_limit networklimit on account.id = networklimit.account_id and networklimit.type = "network" +left join resource_count networkcount on account.id = networkcount.account_id and networkcount.type = "network" +left join async_job on async_job.instance_id = account.id and async_job.instance_type = "Account" and async_job.job_status = 0; + +DROP VIEW IF EXISTS `cloud`.`async_job_view`; +CREATE VIEW async_job_view AS +select +account.id account_id, +account.uuid account_uuid, +account.account_name account_name, +account.type account_type, +domain.id domain_id, +domain.uuid domain_uuid, +domain.name domain_name, +domain.path domain_path, +user.id user_id, +user.uuid user_uuid, +async_job.id, +async_job.uuid, +async_job.job_cmd, +async_job.job_status, +async_job.job_process_status, +async_job.job_result_code, +async_job.job_result, +async_job.created, +async_job.removed, +async_job.instance_type, +async_job.instance_id, +CASE +WHEN async_job.instance_type = 'Volume' THEN volumes.uuid +WHEN async_job.instance_type = 'Template' or async_job.instance_type = 'Iso' THEN vm_template.uuid +WHEN async_job.instance_type = 'VirtualMachine' or async_job.instance_type = 'ConsoleProxy' or async_job.instance_type = 'SystemVm' or async_job.instance_type = 'DomainRouter' THEN vm_instance.uuid +WHEN async_job.instance_type = 'Snapshot' THEN snapshots.uuid +WHEN async_job.instance_type = 'Host' THEN host.uuid +WHEN async_job.instance_type = 'StoragePool' THEN storage_pool.uuid +WHEN async_job.instance_type = 'IpAddress' THEN user_ip_address.uuid +WHEN async_job.instance_type = 'SecurityGroup' THEN security_group.uuid +WHEN async_job.instance_type = 'PhysicalNetwork' THEN physical_network.uuid +WHEN async_job.instance_type = 'TrafficType' THEN physical_network_traffic_types.uuid +WHEN async_job.instance_type = 'PhysicalNetworkServiceProvider' THEN physical_network_service_providers.uuid +WHEN async_job.instance_type = 'FirewallRule' THEN firewall_rules.uuid +WHEN async_job.instance_type = 'Account' THEN acct.uuid +WHEN async_job.instance_type = 'User' THEN us.uuid +WHEN async_job.instance_type = 'StaticRoute' THEN static_routes.uuid +WHEN async_job.instance_type = 'PrivateGateway' THEN vpc_gateways.uuid +WHEN async_job.instance_type = 'Counter' THEN counter.uuid +WHEN async_job.instance_type = 'Condition' THEN conditions.uuid +WHEN async_job.instance_type = 'AutoScalePolicy' THEN autoscale_policies.uuid +WHEN async_job.instance_type = 'AutoScaleVmProfile' THEN autoscale_vmprofiles.uuid +WHEN async_job.instance_type = 'AutoScaleVmGroup' THEN autoscale_vmgroups.uuid +ELSE null +END instance_uuid +from async_job +left join account on async_job.account_id = account.id +left join domain on domain.id = account.domain_id +left join user on async_job.user_id = user.id +left join volumes on async_job.instance_id = volumes.id +left join vm_template on async_job.instance_id = vm_template.id +left join vm_instance on async_job.instance_id = vm_instance.id +left join snapshots on async_job.instance_id = snapshots.id +left join host on async_job.instance_id = host.id +left join storage_pool on async_job.instance_id = storage_pool.id +left join user_ip_address on async_job.instance_id = user_ip_address.id +left join security_group on async_job.instance_id = security_group.id +left join physical_network on async_job.instance_id = physical_network.id +left join physical_network_traffic_types on async_job.instance_id = physical_network_traffic_types.id +left join physical_network_service_providers on async_job.instance_id = physical_network_service_providers.id +left join firewall_rules on async_job.instance_id = firewall_rules.id +left join account acct on async_job.instance_id = acct.id +left join user us on async_job.instance_id = us.id +left join static_routes on async_job.instance_id = static_routes.id +left join vpc_gateways on async_job.instance_id = vpc_gateways.id +left join counter on async_job.instance_id = counter.id +left join conditions on async_job.instance_id = conditions.id +left join autoscale_policies on async_job.instance_id = autoscale_policies.id +left join autoscale_vmprofiles on async_job.instance_id = autoscale_vmprofiles.id +left join autoscale_vmgroups on async_job.instance_id = autoscale_vmgroups.id; diff --git a/setup/db/deploy-db-dev.sh b/setup/db/deploy-db-dev.sh index 29ec4db6050..a40e278b002 100755 --- a/setup/db/deploy-db-dev.sh +++ b/setup/db/deploy-db-dev.sh @@ -55,6 +55,11 @@ if [ ! -f create-index-fk.sql ]; then exit 6; fi +if [ ! -f create-schema-view.sql ]; then + printf "Error: Unable to find create-schema-view.sql\n" + exit 7 +fi + PATHSEP=':' if [[ $OSTYPE == "cygwin" ]] ; then export CATALINA_HOME=`cygpath -m $CATALINA_HOME` @@ -100,6 +105,12 @@ if [ $? -ne 0 ]; then exit 11 fi +mysql --user=cloud --password=cloud cloud < create-schema-view.sql +if [ $? -ne 0 ]; then + printf "Error: Cannot execute create-schema-view.sql\n" + exit 11 +fi + CP=./ CP=${CP}$PATHSEP$CATALINA_HOME/conf diff --git a/setup/db/deploy-db-simulator.sh b/setup/db/deploy-db-simulator.sh index 4f8c14ebfe5..c918df43009 100644 --- a/setup/db/deploy-db-simulator.sh +++ b/setup/db/deploy-db-simulator.sh @@ -55,6 +55,12 @@ if [ ! -f create-index-fk.sql ]; then exit 6; fi +if [ ! -f create-schema-view.sql ]; then + printf "Error: Unable to find create-schema-view.sql\n" + exit 7 +fi + + PATHSEP=':' if [[ $OSTYPE == "cygwin" ]] ; then export CATALINA_HOME=`cygpath -m $CATALINA_HOME` @@ -103,6 +109,12 @@ if [ $? -ne 0 ]; then exit 11 fi +mysql --user=cloud --password=cloud cloud < create-schema-view.sql +if [ $? -ne 0 ]; then + printf "Error: Cannot execute create-schema-view.sql\n" + exit 11 +fi + mysql --user=cloud --password=cloud cloud < create-schema-simulator.sql if [ $? -ne 0 ]; then printf "Error: Cannot execute create-schema-simulator.sql\n" diff --git a/setup/db/templates.simulator.sql b/setup/db/templates.simulator.sql index 2a140a4b21f..7e712f54177 100755 --- a/setup/db/templates.simulator.sql +++ b/setup/db/templates.simulator.sql @@ -17,439 +17,6 @@ INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (1, 'routing-1', 'SystemVM Template (XenServer)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/routing/debian/latest/systemvm.vhd.bz2', 'c33dfaf0937b35c25ef6a0fdd98f24d3', 0, 'SystemVM Template (XenServer)', 'VHD', 15, 0, 1, 'XenServer'); + VALUES (10, 'simulator-domR', 'SystemVM Template (simulator)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/routing/debian/latest/systemvm.vhd.bz2', '', 0, 'SystemVM Template (simulator)', 'VHD', 15, 0, 1, 'Simulator'); INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (2, 'centos53-x86_64', 'CentOS 5.3(64-bit) no GUI (XenServer)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'CentOS 5.3(64-bit) no GUI (XenServer)', 'VHD', 11, 1, 1, 'XenServer'); - -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (3, 'routing-3', 'SystemVM Template (KVM)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/kvm/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', 'fe80a229e3bf38a702e836236ed07f57', 0, 'SystemVM Template (KVM)', 'QCOW2', 15, 0, 1, 'KVM'); - -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, display_text, enable_password, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (4, 'centos55-x86_64', 'CentOS 5.5(64-bit) no GUI (KVM)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/templates/builtin/eec2209b-9875-3c8d-92be-c001bd8a0faf.qcow2.bz2', '1da20ae69b54f761f3f733dce97adcc0', 'CentOS 5.5(64-bit) no GUI (KVM)', 0, 'QCOW2', 112, 1, 1, 'KVM'); - -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (7, 'centos53-x64', 'CentOS 5.3(64-bit) no GUI (vSphere)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://download.cloud.com/releases/2.2.0/CentOS5.3-x86_64.ova', 'f6f881b7f2292948d8494db837fe0f47', 0, 'CentOS 5.3(64-bit) no GUI (vSphere)', 'OVA', 12, 1, 1, 'VMware'); - -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (8, 'routing-8', 'SystemVM Template (vSphere)', 0, now(), 'SYSTEM', 0, 32, 1, 'http://download.cloud.com/releases/2.2.0/systemvm.ova', 'ee3dc55e94e23a0490310bb78cf8cc76', 0, 'SystemVM Template (vSphere)', 'OVA', 15, 0, 1, 'VMware'); - -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (9, 'simulator-domR', 'SystemVM Template (simulator)', 0, now(), 'SYSTEM', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/routing/debian/latest/systemvm.vhd.bz2', '', 0, 'SystemVM Template (simulator)', 'VHD', 15, 0, 1, 'Simulator'); -INSERT INTO `cloud`.`vm_template` (id, unique_name, name, public, created, type, hvm, bits, account_id, url, checksum, enable_password, display_text, format, guest_os_id, featured, cross_zones, hypervisor_type) - VALUES (10, 'simulator-Centos', 'CentOS 5.3(64-bit) no GUI (Simulator)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', '', 0, 'CentOS 5.3(64-bit) no GUI (Simulator)', 'VHD', 11, 1, 1, 'Simulator'); - -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'CentOS'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Debian'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (3, 'Oracle'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (4, 'RedHat'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'SUSE'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (6, 'Windows'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (7, 'Other'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (8, 'Novel'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (9, 'Unix'); -INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (10, 'Ubuntu'); - - -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (1, 1, 'CentOS 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (2, 1, 'CentOS 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (3, 1, 'CentOS 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (4, 1, 'CentOS 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (5, 1, 'CentOS 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (6, 1, 'CentOS 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (7, 1, 'CentOS 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (8, 1, 'CentOS 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (9, 1, 'CentOS 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (10, 1, 'CentOS 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (11, 1, 'CentOS 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (12, 1, 'CentOS 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (13, 1, 'CentOS 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (14, 1, 'CentOS 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (15, 2, 'Debian GNU/Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (16, 3, 'Oracle Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (17, 3, 'Oracle Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (18, 3, 'Oracle Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (19, 3, 'Oracle Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (20, 3, 'Oracle Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (21, 3, 'Oracle Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (22, 3, 'Oracle Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (23, 3, 'Oracle Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (24, 3, 'Oracle Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (25, 3, 'Oracle Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (26, 4, 'Red Hat Enterprise Linux 4.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (27, 4, 'Red Hat Enterprise Linux 4.6 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (28, 4, 'Red Hat Enterprise Linux 4.7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (29, 4, 'Red Hat Enterprise Linux 4.8 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (30, 4, 'Red Hat Enterprise Linux 5.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (31, 4, 'Red Hat Enterprise Linux 5.0 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (32, 4, 'Red Hat Enterprise Linux 5.1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (33, 4, 'Red Hat Enterprise Linux 5.1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (34, 4, 'Red Hat Enterprise Linux 5.2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (35, 4, 'Red Hat Enterprise Linux 5.2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (36, 4, 'Red Hat Enterprise Linux 5.3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (37, 4, 'Red Hat Enterprise Linux 5.3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (38, 4, 'Red Hat Enterprise Linux 5.4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (39, 4, 'Red Hat Enterprise Linux 5.4 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (40, 5, 'SUSE Linux Enterprise Server 9 SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (41, 5, 'SUSE Linux Enterprise Server 10 SP1 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (42, 5, 'SUSE Linux Enterprise Server 10 SP1 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (43, 5, 'SUSE Linux Enterprise Server 10 SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (44, 5, 'SUSE Linux Enterprise Server 10 SP2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (45, 5, 'SUSE Linux Enterprise Server 10 SP3 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (46, 5, 'SUSE Linux Enterprise Server 11 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (47, 5, 'SUSE Linux Enterprise Server 11 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (48, 6, 'Windows 7 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (49, 6, 'Windows 7 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (50, 6, 'Windows Server 2003 Enterprise Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (51, 6, 'Windows Server 2003 Enterprise Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (52, 6, 'Windows Server 2008 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (53, 6, 'Windows Server 2008 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (54, 6, 'Windows Server 2008 R2 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (55, 6, 'Windows 2000 Server SP4 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (56, 6, 'Windows Vista (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (57, 6, 'Windows XP SP2 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (58, 6, 'Windows XP SP3 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (59, 10, 'Other Ubuntu (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (60, 7, 'Other (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (61, 6, 'Windows 2000 Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (62, 6, 'Windows 98'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (63, 6, 'Windows 95'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (64, 6, 'Windows NT 4'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (65, 6, 'Windows 3.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (66, 4, 'Red Hat Enterprise Linux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (67, 4, 'Red Hat Enterprise Linux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (68, 7, 'Open Enterprise Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (69, 7, 'Asianux 3(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (70, 7, 'Asianux 3(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (72, 2, 'Debian GNU/Linux 5(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (73, 2, 'Debian GNU/Linux 4(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (74, 2, 'Debian GNU/Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (75, 7, 'Other 2.6x Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (76, 7, 'Other 2.6x Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (77, 8, 'Novell Netware 6.x'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (78, 8, 'Novell Netware 5.1'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (79, 9, 'Sun Solaris 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (80, 9, 'Sun Solaris 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (81, 9, 'Sun Solaris 9(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (82, 9, 'Sun Solaris 8(Experimental)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (83, 9, 'FreeBSD (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (84, 9, 'FreeBSD (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (85, 9, 'SCO OpenServer 5'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (86, 9, 'SCO UnixWare 7'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (87, 6, 'Windows Server 2003 DataCenter Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (88, 6, 'Windows Server 2003 DataCenter Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (89, 6, 'Windows Server 2003 Standard Edition(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (90, 6, 'Windows Server 2003 Standard Edition(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (91, 6, 'Windows Server 2003 Web Edition'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (92, 6, 'Microsoft Small Bussiness Server 2003'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (93, 6, 'Windows XP (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (94, 6, 'Windows XP (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (95, 6, 'Windows 2000 Advanced Server'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (96, 5, 'SUSE Linux Enterprise 8(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (97, 5, 'SUSE Linux Enterprise 8(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (98, 7, 'Other Linux (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (99, 7, 'Other Linux (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (100, 10, 'Other Ubuntu (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (101, 6, 'Windows Vista (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (102, 6, 'DOS'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (103, 7, 'Other (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (104, 7, 'OS/2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (105, 6, 'Windows 2000 Professional'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (106, 4, 'Red Hat Enterprise Linux 4(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (107, 5, 'SUSE Linux Enterprise 9(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (108, 5, 'SUSE Linux Enterprise 9(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (109, 5, 'SUSE Linux Enterprise 10(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (110, 5, 'SUSE Linux Enterprise 10(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (111, 1, 'CentOS 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (112, 1, 'CentOS 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (113, 4, 'Red Hat Enterprise Linux 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (114, 4, 'Red Hat Enterprise Linux 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (115, 4, 'Fedora 13'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (116, 4, 'Fedora 12'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (117, 4, 'Fedora 11'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (118, 4, 'Fedora 10'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (119, 4, 'Fedora 9'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (120, 4, 'Fedora 8'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (121, 10, 'Ubuntu 10.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (122, 10, 'Ubuntu 9.10 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (123, 10, 'Ubuntu 9.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (124, 10, 'Ubuntu 8.10 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (125, 10, 'Ubuntu 8.04 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (126, 10, 'Ubuntu 10.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (127, 10, 'Ubuntu 9.10 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (128, 10, 'Ubuntu 9.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (129, 10, 'Ubuntu 8.10 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (130, 10, 'Ubuntu 8.04 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (131, 4, 'Red Hat Enterprise Linux 2'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (132, 2, 'Debian GNU/Linux 6(32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (133, 2, 'Debian GNU/Linux 6(64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (134, 3, 'Oracle Enterprise Linux 5.5 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (135, 3, 'Oracle Enterprise Linux 5.5 (64-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (136, 4, 'Red Hat Enterprise Linux 6.0 (32-bit)'); -INSERT INTO `cloud`.`guest_os` (id, category_id, display_name) VALUES (137, 4, 'Red Hat Enterprise Linux 6.0 (64-bit)'); - - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.5 (32-bit)', 1); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.6 (32-bit)', 2); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.7 (32-bit)', 3); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 4.8 (32-bit)', 4); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.0 (32-bit)', 5); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.0 (64-bit)', 6); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.1 (32-bit)', 7); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.1 (32-bit)', 8); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.2 (32-bit)', 9); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.2 (64-bit)', 10); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.3 (32-bit)', 11); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.3 (64-bit)', 12); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.4 (32-bit)', 13); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'CentOS 5.4 (64-bit)', 14); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Debian Lenny 5.0 (32-bit)', 15); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.0 (32-bit)', 16); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.0 (64-bit)', 17); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.1 (32-bit)', 18); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.1 (64-bit)', 19); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.2 (32-bit)', 20); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.2 (64-bit)', 21); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.3 (32-bit)', 22); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.3 (64-bit)', 23); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.4 (32-bit)', 24); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Oracle Enterprise Linux 5.4 (64-bit)', 25); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 4.5 (32-bit)', 26); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 4.6 (32-bit)', 27); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 4.7 (32-bit)', 28); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 4.8 (32-bit)', 29); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.0 (32-bit)', 30); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.0 (64-bit)', 31); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.1 (32-bit)', 32); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.1 (64-bit)', 33); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.2 (32-bit)', 34); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.2 (64-bit)', 35); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.3 (32-bit)', 36); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.3 (64-bit)', 37); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.4 (32-bit)', 38); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Red Hat Enterprise Linux 5.4 (64-bit)', 39); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 9 SP4 (32-bit)', 40); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 10 SP1 (32-bit)', 41); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 10 SP1 (64-bit)', 42); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 10 SP2 (32-bit)', 43); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 10 SP2 (64-bit)', 44); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 10 SP3 (64-bit)', 45); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 11 (32-bit)', 46); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'SUSE Linux Enterprise Server 11 (64-bit)', 47); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows 7 (32-bit)', 48); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows 7 (64-bit)', 49); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Server 2003 (32-bit)', 50); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Server 2003 (64-bit)', 51); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Server 2008 (32-bit)', 52); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Server 2008 (64-bit)', 53); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Server 2008 R2 (64-bit)', 54); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows 2000 SP4 (32-bit)', 55); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows Vista (32-bit)', 56); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows XP SP2 (32-bit)', 57); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Windows XP SP3 (32-bit)', 58); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Other install media', 59); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Other install media', 100); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Other install media', 60); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("XenServer", 'Other install media', 103); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 121); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 126); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 122); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 127); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 123); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 128); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 124); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 129); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 125); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('XenServer', 'Other install media', 130); - - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 7(32-bit)', 48); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 7(64-bit)', 49); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2008 R2(64-bit)', 54); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2008(32-bit)', 52); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2008(64-bit)', 53); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)', 50); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)', 51); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)', 87); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)', 88); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Standard Edition (32-bit)', 89); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Standard Edition (64-bit)', 90); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Server 2003, Web Edition', 91); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Small Bussiness Server 2003', 92); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Vista (32-bit)', 56); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows Vista (64-bit)', 101); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows XP Professional (32-bit)', 93); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows XP Professional (32-bit)', 57); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows XP Professional (32-bit)', 58); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows XP Professional (64-bit)', 94); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 2000 Advanced Server', 95); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 2000 Server', 61); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 2000 Professional', 105); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 2000 Server', 55); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 98', 62); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 95', 63); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows NT 4', 64); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Microsoft Windows 3.1', 65); - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(32-bit)', 30); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(32-bit)', 32); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(32-bit)', 34); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(32-bit)', 36); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(32-bit)', 38); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(64-bit)', 31); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(64-bit)', 33); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(64-bit)', 35); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(64-bit)', 37); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 5(64-bit)', 39); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 4(32-bit)', 26); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 4(32-bit)', 27); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 4(32-bit)', 28); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 4(32-bit)', 29); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 4(64-bit)', 106); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 3(32-bit)', 66); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 3(64-bit)', 67); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Red Hat Enterprise Linux 2', 131); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 11(32-bit)', 46); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 11(64-bit)', 47); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(32-bit)', 41); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(32-bit)', 43); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(64-bit)', 42); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(64-bit)', 44); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(64-bit)', 45); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(32-bit)', 109); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 10(64-bit)', 110); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 8/9(32-bit)', 40); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 8/9(32-bit)', 96); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 8/9(64-bit)', 97); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 8/9(32-bit)', 107); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Suse Linux Enterprise 8/9(64-bit)', 108); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Open Enterprise Server', 68); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Asianux 3(32-bit)', 69); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Asianux 3(64-bit)', 70); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 5(32-bit)', 15); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 5(64-bit)', 72); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 4(32-bit)', 73); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Debian GNU/Linux 4(64-bit)', 74); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 59); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 121); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 122); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 123); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 124); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (32-bit)', 125); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 100); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 126); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 127); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 128); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 129); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Ubuntu Linux (64-bit)', 130); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other 2.6x Linux (32-bit)', 75); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other 2.6x Linux (64-bit)', 76); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other Linux (32-bit)', 98); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other Linux (64-bit)', 99); - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Novell Netware 6.x', 77); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Novell Netware 5.1', 78); - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Sun Solaris 10(32-bit)', 79); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Sun Solaris 10(64-bit)', 80); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Sun Solaris 9(Experimental)', 81); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Sun Solaris 8(Experimental)', 82); - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'FreeBSD (32-bit)', 83); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'FreeBSD (64-bit)', 84); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'OS/2', 104); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'SCO OpenServer 5', 85); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'SCO UnixWare 7', 86); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'DOS', 102); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other (32-bit)', 60); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ("VmWare", 'Other (64-bit)', 103); - - - -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 4.5', 1); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 4.6', 2); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 4.7', 3); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 4.8', 4); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.0', 5); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.0', 6); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.1', 7); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.1', 8); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.2', 9); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.2', 10); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.3', 11); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.3', 12); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.4', 13); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.4', 14); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.5', 111); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'CentOS 5.5', 112); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 4.5', 26); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 4.6', 27); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 4.7', 28); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 4.8', 29); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.0', 30); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.0', 31); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.1', 32); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.1', 33); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.2', 34); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.2', 35); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.3', 36); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.3', 37); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.4', 38); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.4', 39); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.5', 113); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 5.5', 114); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 4', 106); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 3', 66); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 3', 67); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Red Hat Enterprise Linux 2', 131); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 13', 115); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 12', 116); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 11', 117); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 10', 118); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 9', 119); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Fedora 8', 120); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 121); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 10.04', 126); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.10', 122); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.10', 127); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.04', 123); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 9.04', 128); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 8.10', 124); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 8.10', 129); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 8.04', 125); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Ubuntu 8.04', 130); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Debian GNU/Linux 5', 15); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Debian GNU/Linux 5', 72); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Debian GNU/Linux 4', 73); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Debian GNU/Linux 4', 74); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Linux 2.6x', 75); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Linux 2.6x', 76); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Ubuntu', 59); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Ubuntu', 100); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Linux', 98); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other Linux', 99); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 7', 48); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 7', 49); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 50); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 51); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 87); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 88); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 89); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 90); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 91); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2003', 92); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2008', 52); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Server 2008', 53); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 2000', 55); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 2000', 61); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 2000', 95); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows 98', 62); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Vista', 56); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows Vista', 101); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows XP SP2', 57); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows XP SP3', 58); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows XP ', 93); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Windows XP ', 94); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'DOS', 102); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other', 60); -INSERT INTO `cloud`.`guest_os_hypervisor` (hypervisor_type, guest_os_name, guest_os_id) VALUES ('KVM', 'Other', 103); - + VALUES (11, 'simulator-Centos', 'CentOS 5.3(64-bit) no GUI (Simulator)', 1, now(), 'BUILTIN', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/centos53-x86_64/latest/f59f18fb-ae94-4f97-afd2-f84755767aca.vhd.bz2', '', 0, 'CentOS 5.3(64-bit) no GUI (Simulator)', 'VHD', 11, 1, 1, 'Simulator'); diff --git a/test/conf/README b/test/conf/README deleted file mode 100644 index 6836c0f8b7f..00000000000 --- a/test/conf/README +++ /dev/null @@ -1,8 +0,0 @@ -To run submitCertEC2 and deleteCertEC2 scripts, update parameters in conf/tool.properties file: - -* host - ip address of the host where cloud-bridge software is installed -* port - port cloud-bridge software is listening to -* accesspoint - access point for cloud-bridge REST request -* version - Amazon EC2 api version supported by cloud-bridge -* signaturemethod - HmacSHA1 or HmacSHA256 -* expires - the date when certificate expires \ No newline at end of file diff --git a/test/integration/README b/test/integration/README deleted file mode 100644 index e137a070030..00000000000 --- a/test/integration/README +++ /dev/null @@ -1,8 +0,0 @@ -To run the tests - you should have marvin installed and correctly importable. -The tests are long running and are best monitored by external hudson jobs. - -Also you will have to point marvin to the right configuration file that has -details about your cloudstack deployment. For more help on how to write the -config file and run tests check the tutorial at : - -https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python diff --git a/test/integration/component/README b/test/integration/component/README deleted file mode 100644 index 2fd8d4be795..00000000000 --- a/test/integration/component/README +++ /dev/null @@ -1,41 +0,0 @@ -P1 Cases --------------------------------------- -These test cases are the core functionality tests that ensure the application is stable and can be tested thoroughly. -These P1 cases definitions are located at : https://docs.google.com/a/clogeny.com/spreadsheet/ccc?key=0Aq5M2ldK6eyedDJBa0EzM0RPNmdVNVZOWnFnOVJJcHc&hl=en_US - - -Guidelines ----------- -P1 test cases are being developed using Python's unittests2. Following are certain guidelines being followed - 1. Tests exercised for the same resource should ideally be present under a single suite or file. - - 2. Time-consuming operations that create new cloud resources like server creation, volume creation etc - should not necessarily be exercised per unit test. The resources can be shared by creating them at - the class-level using setUpClass and shared across all instances during a single run. - - 3. Certain tests pertaining to NAT, Firewall and Load Balancing warrant fresh resources per test. Hence a call should be - taken by the stakeholders regarding sharing resources. - - 4. Ensure that the tearDown/tearDownClass functions clean up all the resources created during the test run. - -For more information about unittests: http://docs.python.org/library/unittest.html - - -P1 Tests ----------- -The following files contain these P1 cases: - -1. test_snapshots.py - Snapshots related tests -2. test_routers.py - Router related tests -3. test_usage.py - Usage realted tests -4. test_account.py - Account related tests -5. test_resource_limits.py - Resource limits tests -6. test_security_groups.py - Security groups related tests -7. test_templates.py - templates related tests -8. test_volumes.py - Volumes related tests -9. test_blocker_bugs.py - Blocker bugs tests -10. test_project_configs.py - Project global configuration related tests -11. test_project_limits.py - Project resource limits related tests -12. test_project_resources.py - Project resource creation related tests -13. test_project_usage.py - Project usage related tests -14. test_projects - Projects functionality tests diff --git a/test/integration/component/test_accounts.py b/test/integration/component/test_accounts.py index 641f6fd139c..d0b4434bb4e 100644 --- a/test/integration/component/test_accounts.py +++ b/test/integration/component/test_accounts.py @@ -19,9 +19,9 @@ #Import Local Modules from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin import remoteSSHClient import datetime diff --git a/test/integration/component/test_allocation_states.py b/test/integration/component/test_allocation_states.py index 5d702b9f9c6..006f8795fbf 100644 --- a/test/integration/component/test_allocation_states.py +++ b/test/integration/component/test_allocation_states.py @@ -1,23 +1,27 @@ -# -*- encoding: utf-8 -*- -# Copyright 2012 Citrix Systems, Inc. Licensed under the -# Apache License, Version 2.0 (the "License"); you may not use this -# file except in compliance with the License. Citrix Systems, Inc. -# reserves all rights not expressly granted by 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. -# -# Automatically generated by addcopyright.py at 04/03/2012 +# 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. + import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * import datetime diff --git a/test/integration/component/test_blocker_bugs.py b/test/integration/component/test_blocker_bugs.py index 2285afa8e89..cc5da0ace4a 100644 --- a/test/integration/component/test_blocker_bugs.py +++ b/test/integration/component/test_blocker_bugs.py @@ -18,9 +18,9 @@ """ import marvin from nose.plugins.attrib import attr -from integration.lib.base import * -from integration.lib.utils import * -from integration.lib.common import * +from marvin.integration.lib.base import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.common import * #Import Local Modules from marvin.cloudstackTestCase import * @@ -407,7 +407,6 @@ class TestTemplate(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/component/test_egress_rules.py b/test/integration/component/test_egress_rules.py index 982f036bdf7..73a91f41bfe 100644 --- a/test/integration/component/test_egress_rules.py +++ b/test/integration/component/test_egress_rules.py @@ -23,9 +23,9 @@ from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin.remoteSSHClient import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * #Import System modules import time @@ -138,7 +138,6 @@ class TestDefaultSecurityGroupEgress(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -297,7 +296,6 @@ class TestAuthorizeIngressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -455,7 +453,6 @@ class TestDefaultGroupEgress(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -656,7 +653,6 @@ class TestDefaultGroupEgressAfterDeploy(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -839,7 +835,6 @@ class TestRevokeEgressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1101,7 +1096,6 @@ class TestInvalidAccountAuthroize(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1223,7 +1217,6 @@ class TestMultipleAccountsEgressRuleNeg(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1471,7 +1464,6 @@ class TestMultipleAccountsEgressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1768,7 +1760,6 @@ class TestStartStopVMWithEgressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1980,7 +1971,6 @@ class TestInvalidParametersForEgress(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -2163,7 +2153,6 @@ class TestEgressAfterHostMaintainance(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/component/test_eip_elb.py b/test/integration/component/test_eip_elb.py index 7c28c3d2343..4c8dcbe2c07 100644 --- a/test/integration/component/test_eip_elb.py +++ b/test/integration/component/test_eip_elb.py @@ -22,9 +22,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime @@ -176,7 +176,6 @@ class TestEIP(cloudstackTestCase): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) - self.dbclient.close() except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return @@ -999,7 +998,6 @@ class TestELB(cloudstackTestCase): try: #Clean up, terminate the created network offerings cleanup_resources(self.apiclient, self.cleanup) - self.dbclient.close() except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return diff --git a/test/integration/component/test_network_offering.py b/test/integration/component/test_network_offering.py index 35cc01129ce..c1a518b458a 100644 --- a/test/integration/component/test_network_offering.py +++ b/test/integration/component/test_network_offering.py @@ -22,9 +22,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime diff --git a/test/integration/component/test_project_configs.py b/test/integration/component/test_project_configs.py index c82bf134871..d5ce9d6024d 100644 --- a/test/integration/component/test_project_configs.py +++ b/test/integration/component/test_project_configs.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime diff --git a/test/integration/component/test_project_limits.py b/test/integration/component/test_project_limits.py index c1ef86aade8..8f7c1281b23 100644 --- a/test/integration/component/test_project_limits.py +++ b/test/integration/component/test_project_limits.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * import datetime diff --git a/test/integration/component/test_project_resources.py b/test/integration/component/test_project_resources.py index a32ca74c2e5..27452be811f 100644 --- a/test/integration/component/test_project_resources.py +++ b/test/integration/component/test_project_resources.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime @@ -1172,7 +1172,6 @@ class TestSecurityGroup(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/component/test_project_usage.py b/test/integration/component/test_project_usage.py index c171e3c7f8b..4561576543c 100644 --- a/test/integration/component/test_project_usage.py +++ b/test/integration/component/test_project_usage.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime diff --git a/test/integration/component/test_projects.py b/test/integration/component/test_projects.py index 26d4a6f91c4..811d092d18e 100644 --- a/test/integration/component/test_projects.py +++ b/test/integration/component/test_projects.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime diff --git a/test/integration/component/test_resource_limits.py b/test/integration/component/test_resource_limits.py index f182ed17bd0..cd007f1595e 100644 --- a/test/integration/component/test_resource_limits.py +++ b/test/integration/component/test_resource_limits.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * import datetime diff --git a/test/integration/component/test_routers.py b/test/integration/component/test_routers.py index dde8aa4b8b6..a65c5c34005 100644 --- a/test/integration/component/test_routers.py +++ b/test/integration/component/test_routers.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient #Import System modules diff --git a/test/integration/component/test_security_groups.py b/test/integration/component/test_security_groups.py index 1cad467416a..13a87b67c83 100644 --- a/test/integration/component/test_security_groups.py +++ b/test/integration/component/test_security_groups.py @@ -22,9 +22,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient #Import System modules @@ -110,7 +110,6 @@ class TestDefaultSecurityGroup(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -383,7 +382,6 @@ class TestAuthorizeIngressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -519,7 +517,6 @@ class TestRevokeIngressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -678,7 +675,6 @@ class TestDhcpOnlyRouter(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -815,7 +811,6 @@ class TestdeployVMWithUserData(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1019,7 +1014,6 @@ class TestDeleteSecurityGroup(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -1265,7 +1259,6 @@ class TestIngressRule(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/component/test_snapshots.py b/test/integration/component/test_snapshots.py index b368b853c72..825b8c6877e 100644 --- a/test/integration/component/test_snapshots.py +++ b/test/integration/component/test_snapshots.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient @@ -54,6 +54,30 @@ class Services: "name": "Small Disk", "disksize": 1 }, + "server_with_disk": + { + "displayname": "Test VM -With Disk", + "username": "root", + "password": "password", + "ssh_port": 22, + "hypervisor": 'XenServer', + "privateport": 22, + "publicport": 22, + "protocol": 'TCP', + }, + + "server_without_disk": + { + "displayname": "Test VM-No Disk", + "username": "root", + "password": "password", + "ssh_port": 22, + "hypervisor": 'XenServer', + "privateport": 22, + # For NAT rule creation + "publicport": 22, + "protocol": 'TCP', + }, "server": { "displayname": "TestVM", "username": "root", @@ -81,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", @@ -93,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, @@ -102,6 +125,1062 @@ class Services: } +class TestSnapshotRootDisk(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super(TestSnapshotRootDisk, cls).getClsTestClient().getApiClient() + cls.services = Services().services + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostype"] + ) + cls.services["domainid"] = cls.domain.id + cls.services["server_without_disk"]["zoneid"] = cls.zone.id + cls.services["templates"]["ostypeid"] = template.ostypeid + cls.services["zoneid"] = cls.zone.id + + # Create VMs, NAT Rules etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + + cls.services["account"] = cls.account.account.name + + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.virtual_machine = cls.virtual_machine_with_disk = \ + VirtualMachine.create( + cls.api_client, + cls.services["server_without_disk"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id, + mode=cls.services["mode"] + ) + cls._cleanup = [ + cls.service_offering, + cls.account, + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.api_client, cls._cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def setUp(self): + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + return + + def tearDown(self): + try: + #Clean up, terminate the created instance, volumes and snapshots + cleanup_resources(self.apiclient, self.cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_01_snapshot_root_disk(self): + """Test Snapshot Root Disk + """ + + # Validate the following + # 1. listSnapshots should list the snapshot that was created. + # 2. verify that secondary storage NFS share contains + # the reqd volume under + # /secondary/snapshots//$account_id/$volumeid/$snapshot_uuid + # 3. verify backup_snap_id was non null in the `snapshots` table + + volumes = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine_with_disk.id, + type='ROOT', + listall=True + ) + + snapshot = Snapshot.create( + self.apiclient, + volumes[0].id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + self.debug("Snapshot created: ID - %s" % snapshot.id) + + snapshots = list_snapshots( + self.apiclient, + id=snapshot.id + ) + self.assertEqual( + isinstance(snapshots, list), + True, + "Check list response returns a valid list" + ) + + self.assertNotEqual( + snapshots, + None, + "Check if result exists in list item call" + ) + self.assertEqual( + snapshots[0].id, + snapshot.id, + "Check resource id in list resources call" + ) + self.debug( + "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ + % str(snapshot.id) + ) + qresultset = self.dbclient.execute( + "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ + % str(snapshot.id) + ) + self.assertNotEqual( + len(qresultset), + 0, + "Check DB Query result set" + ) + + qresult = qresultset[0] + + snapshot_uuid = qresult[0] # backup_snap_id = snapshot UUID + account_id = qresult[1] + volume_id = qresult[2] + + self.assertNotEqual( + str(snapshot_uuid), + 'NULL', + "Check if backup_snap_id is not null" + ) + + # Get the Secondary Storage details from list Hosts + hosts = list_hosts( + self.apiclient, + type='SecondaryStorage', + zoneid=self.zone.id + ) + self.assertEqual( + isinstance(hosts, list), + True, + "Check list response returns a valid list" + ) + uuids = [] + for host in hosts: + # hosts[0].name = "nfs://192.168.100.21/export/test" + parse_url = (host.name).split('/') + # parse_url = ['nfs:', '', '192.168.100.21', 'export', 'test'] + + # Split IP address and export path from name + sec_storage_ip = parse_url[2] + # Sec Storage IP: 192.168.100.21 + + export_path = '/'.join(parse_url[3:]) + # Export path: export/test + + try: + # Login to VM to check snapshot present on sec disk + ssh_client = self.virtual_machine_with_disk.get_ssh_client() + + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s/%s %s" % ( + sec_storage_ip, + export_path, + self.services["mount_dir"] + ), + "ls %s/snapshots/%s/%s" % ( + self.services["mount_dir"], + account_id, + volume_id + ), + ] + + for c in cmds: + self.debug(c) + result = ssh_client.execute(c) + self.debug(result) + + except Exception: + self.fail("SSH failed for Virtual machine: %s" % + self.virtual_machine_with_disk.ipaddress) + + uuids.append(result) + # Unmount the Sec Storage + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + try: + for c in cmds: + self.debug(c) + result = ssh_client.execute(c) + self.debug(result) + + except Exception as e: + self.fail("SSH failed for Virtual machine: %s" % + self.virtual_machine_with_disk.ipaddress) + + res = str(uuids) + # Check snapshot UUID in secondary storage and database + self.assertEqual( + res.count(snapshot_uuid), + 1, + "Check snapshot UUID in secondary storage and database" + ) + return + + +class TestSnapshots(cloudstackTestCase): + + @classmethod + def setUpClass(cls): + cls.api_client = super(TestSnapshots, cls).getClsTestClient().getApiClient() + cls.services = Services().services + # Get Zone, Domain and templates + cls.domain = get_domain(cls.api_client, cls.services) + cls.zone = get_zone(cls.api_client, cls.services) + cls.disk_offering = DiskOffering.create( + cls.api_client, + cls.services["disk_offering"] + ) + template = get_template( + cls.api_client, + cls.zone.id, + cls.services["ostype"] + ) + + cls.services["domainid"] = cls.domain.id + cls.services["server_with_disk"]["zoneid"] = cls.zone.id + cls.services["server_with_disk"]["diskoffering"] = cls.disk_offering.id + + cls.services["server_without_disk"]["zoneid"] = cls.zone.id + + cls.services["templates"]["ostypeid"] = template.ostypeid + cls.services["zoneid"] = cls.zone.id + cls.services["diskoffering"] = cls.disk_offering.id + + # Create VMs, NAT Rules etc + cls.account = Account.create( + cls.api_client, + cls.services["account"], + domainid=cls.domain.id + ) + + cls.services["account"] = cls.account.account.name + + cls.service_offering = ServiceOffering.create( + cls.api_client, + cls.services["service_offering"] + ) + cls.virtual_machine = cls.virtual_machine_with_disk = \ + VirtualMachine.create( + cls.api_client, + cls.services["server_with_disk"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id, + mode=cls.services["mode"] + ) + cls.virtual_machine_without_disk = \ + VirtualMachine.create( + cls.api_client, + cls.services["server_without_disk"], + templateid=template.id, + accountid=cls.account.account.name, + domainid=cls.account.account.domainid, + serviceofferingid=cls.service_offering.id, + mode=cls.services["mode"] + ) + cls._cleanup = [ + cls.service_offering, + cls.disk_offering, + cls.account, + ] + return + + @classmethod + def tearDownClass(cls): + try: + #Cleanup resources used + cleanup_resources(cls.api_client, cls._cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + def setUp(self): + self.apiclient = self.testClient.getApiClient() + self.dbclient = self.testClient.getDbConnection() + self.cleanup = [] + return + + def tearDown(self): + try: + #Clean up, terminate the created instance, volumes and snapshots + cleanup_resources(self.apiclient, self.cleanup) + except Exception as e: + raise Exception("Warning: Exception during cleanup : %s" % e) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_02_snapshot_data_disk(self): + """Test Snapshot Data Disk + """ + + volume = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine_with_disk.id, + type='DATADISK', + listall=True + ) + self.assertEqual( + isinstance(volume, list), + True, + "Check list response returns a valid list" + ) + + self.debug("Creating a Snapshot from data volume: %s" % volume[0].id) + snapshot = Snapshot.create( + self.apiclient, + volume[0].id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + snapshots = list_snapshots( + self.apiclient, + id=snapshot.id + ) + self.assertEqual( + isinstance(snapshots, list), + True, + "Check list response returns a valid list" + ) + self.assertNotEqual( + snapshots, + None, + "Check if result exists in list item call" + ) + self.assertEqual( + snapshots[0].id, + snapshot.id, + "Check resource id in list resources call" + ) + self.debug( + "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ + % str(snapshot.id) + ) + qresultset = self.dbclient.execute( + "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ + % str(snapshot.id) + ) + self.assertNotEqual( + len(qresultset), + 0, + "Check DB Query result set" + ) + + qresult = qresultset[0] + snapshot_uuid = qresult[0] # backup_snap_id = snapshot UUID + account_id = qresult[1] + volume_id = qresult[2] + + self.assertNotEqual( + str(snapshot_uuid), + 'NULL', + "Check if backup_snap_id is not null" + ) + + # Get the Secondary Storage details from list Hosts + hosts = list_hosts( + self.apiclient, + type='SecondaryStorage', + zoneid=self.zone.id + ) + self.assertEqual( + isinstance(hosts, list), + True, + "Check list response returns a valid list" + ) + uuids = [] + for host in hosts: + # hosts[0].name = "nfs://192.168.100.21/export" + parse_url = (host.name).split('/') + # parse_url = ['nfs:', '', '192.168.100.21', 'export'] + + # Split IP address and export path from name + sec_storage_ip = parse_url[2] + # Sec Storage IP: 192.168.100.21 + + export_path = '/'.join(parse_url[3:]) + # Export path: export + + try: + # Login to VM to check snapshot present on sec disk + ssh_client = self.virtual_machine_with_disk.get_ssh_client() + + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s/%s %s" % ( + sec_storage_ip, + export_path, + self.services["mount_dir"] + ), + "ls %s/snapshots/%s/%s" % ( + self.services["mount_dir"], + account_id, + volume_id + ), + ] + for c in cmds: + self.debug(c) + result = ssh_client.execute(c) + self.debug(result) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.virtual_machine_with_disk.ipaddress) + + uuids.append(result) + # Unmount the Sec Storage + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + try: + for c in cmds: + self.debug(c) + ssh_client.execute(c) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.virtual_machine_with_disk.ipaddress) + + res = str(uuids) + # Check snapshot UUID in secondary storage and database + self.assertEqual( + res.count(snapshot_uuid), + 1, + "Check snapshot UUID in secondary storage and database" + ) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke", "xen"]) + def test_03_volume_from_snapshot(self): + """Create volumes from snapshots + """ + #1. Login to machine; create temp/test directories on data volume + #2. Snapshot the Volume + #3. Create another Volume from snapshot + #4. Mount/Attach volume to another server + #5. Compare data + random_data_0 = random_gen(100) + random_data_1 = random_gen(100) + + try: + ssh_client = self.virtual_machine.get_ssh_client() + + #Format partition using ext3 + format_volume_to_ext3( + ssh_client, + self.services["diskdevice"] + ) + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s1 %s" % ( + self.services["diskdevice"], + self.services["mount_dir"] + ), + "mkdir -p %s/%s/{%s,%s} " % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["sub_lvl_dir2"] + ), + "echo %s > %s/%s/%s/%s" % ( + random_data_0, + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["random_data"] + ), + "echo %s > %s/%s/%s/%s" % ( + random_data_1, + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir2"], + self.services["random_data"] + ), + ] + for c in cmds: + self.debug(c) + ssh_client.execute(c) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.virtual_machine.ipaddress) + # Unmount the Sec Storage + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + + try: + for c in cmds: + self.debug(c) + ssh_client.execute(c) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.virtual_machine.ipaddress) + + list_volume_response = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine.id, + type='DATADISK', + listall=True + ) + + volume_response = list_volume_response[0] + #Create snapshot from attached volume + snapshot = Snapshot.create( + self.apiclient, + volume_response.id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + self.debug("Created Snapshot from volume: %s" % volume_response.id) + + #Create volume from snapshot + self.debug("Creating volume from snapshot: %s" % snapshot.id) + volume = Volume.create_from_snapshot( + self.apiclient, + snapshot.id, + self.services, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + + volumes = list_volumes( + self.apiclient, + id=volume.id + ) + self.assertEqual( + isinstance(volumes, list), + True, + "Check list response returns a valid list" + ) + self.assertNotEqual( + len(volumes), + None, + "Check Volume list Length" + ) + + self.assertEqual( + volumes[0].id, + volume.id, + "Check Volume in the List Volumes" + ) + #Attaching volume to new VM + new_virtual_machine = self.virtual_machine_without_disk + self.cleanup.append(new_virtual_machine) + + cmd = attachVolume.attachVolumeCmd() + cmd.id = volume.id + cmd.virtualmachineid = new_virtual_machine.id + self.apiclient.attachVolume(cmd) + + try: + #Login to VM to verify test directories and files + ssh = new_virtual_machine.get_ssh_client() + + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s1 %s" % ( + self.services["diskdevice"], + self.services["mount_dir"] + ), + ] + + for c in cmds: + self.debug(c) + result = ssh.execute(c) + self.debug(result) + + returned_data_0 = ssh.execute("cat %s/%s/%s/%s" % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["random_data"] + )) + returned_data_1 = ssh.execute("cat %s/%s/%s/%s" % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir2"], + self.services["random_data"] + )) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.new_virtual_machine.ipaddress) + + #Verify returned data + self.assertEqual( + random_data_0, + returned_data_0[0], + "Verify newly attached volume contents with existing one" + ) + self.assertEqual( + random_data_1, + returned_data_1[0], + "Verify newly attached volume contents with existing one" + ) + # Unmount the Sec Storage + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + try: + for c in cmds: + ssh_client.execute(c) + + except Exception as e: + self.fail("SSH failed for VM with IP: %s" % + self.new_virtual_machine.ipaddress) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_04_delete_snapshot(self): + """Test Delete Snapshot + """ + + #1. Snapshot the Volume + #2. Delete the snapshot + #3. Verify snapshot is removed by calling List Snapshots API + + volumes = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine.id, + type='DATADISK', + listall=True + ) + self.assertEqual( + isinstance(volumes, list), + True, + "Check list response returns a valid list" + ) + snapshot = Snapshot.create( + self.apiclient, + volumes[0].id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + snapshot.delete(self.apiclient) + + snapshots = list_snapshots( + self.apiclient, + id=snapshot.id + ) + + self.assertEqual( + snapshots, + None, + "Check if result exists in list item call" + ) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_05_recurring_snapshot_root_disk(self): + """Test Recurring Snapshot Root Disk + """ + #1. Create snapshot policy for root disk + #2. ListSnapshot policy should return newly created policy + #3. Verify only most recent number (maxsnaps) snapshots retailed + + volume = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine_with_disk.id, + type='ROOT', + listall=True + ) + self.assertEqual( + isinstance(volume, list), + True, + "Check list response returns a valid list" + ) + recurring_snapshot = SnapshotPolicy.create( + self.apiclient, + volume[0].id, + self.services["recurring_snapshot"] + ) + self.cleanup.append(recurring_snapshot) + + #ListSnapshotPolicy should return newly created policy + list_snapshots_policy = list_snapshot_policy( + self.apiclient, + id=recurring_snapshot.id, + volumeid=volume[0].id + ) + self.assertEqual( + isinstance(list_snapshots_policy, list), + True, + "Check list response returns a valid list" + ) + self.assertNotEqual( + list_snapshots_policy, + None, + "Check if result exists in list item call" + ) + snapshots_policy = list_snapshots_policy[0] + self.assertEqual( + snapshots_policy.id, + recurring_snapshot.id, + "Check recurring snapshot id in list resources call" + ) + self.assertEqual( + snapshots_policy.maxsnaps, + self.services["recurring_snapshot"]["maxsnaps"], + "Check interval type in list resources call" + ) + # Sleep for (maxsnaps+1) hours to verify + # only maxsnaps snapshots are retained + time.sleep( + (self.services["recurring_snapshot"]["maxsnaps"]) * 3600 + ) + + timeout = self.services["timeout"] + while True: + snapshots = list_snapshots( + self.apiclient, + volumeid=volume[0].id, + intervaltype=\ + self.services["recurring_snapshot"]["intervaltype"], + snapshottype='RECURRING', + listall=True + ) + + if isinstance(snapshots, list): + break + + elif timeout == 0: + raise Exception("List snapshots API call failed.") + + time.sleep(1) + timeout = timeout - 1 + + self.assertEqual( + isinstance(snapshots, list), + True, + "Check list response returns a valid list" + ) + + self.assertEqual( + len(snapshots), + self.services["recurring_snapshot"]["maxsnaps"], + "Check maximum number of recurring snapshots retained" + ) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke"]) + def test_06_recurring_snapshot_data_disk(self): + """Test Recurring Snapshot data Disk + """ + #1. Create snapshot policy for data disk + #2. ListSnapshot policy should return newly created policy + #3. Verify only most recent number (maxsnaps) snapshots retailed + + volume = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine_with_disk.id, + type='DATADISK', + listall=True + ) + + self.assertEqual( + isinstance(volume, list), + True, + "Check list response returns a valid list" + ) + + recurring_snapshot = SnapshotPolicy.create( + self.apiclient, + volume[0].id, + self.services["recurring_snapshot"] + ) + self.cleanup.append(recurring_snapshot) + #ListSnapshotPolicy should return newly created policy + list_snapshots_policy = list_snapshot_policy( + self.apiclient, + id=recurring_snapshot.id, + volumeid=volume[0].id + ) + + self.assertEqual( + isinstance(list_snapshots_policy, list), + True, + "Check list response returns a valid list" + ) + + self.assertNotEqual( + list_snapshots_policy, + None, + "Check if result exists in list item call" + ) + snapshots_policy = list_snapshots_policy[0] + self.assertEqual( + snapshots_policy.id, + recurring_snapshot.id, + "Check recurring snapshot id in list resources call" + ) + self.assertEqual( + snapshots_policy.maxsnaps, + self.services["recurring_snapshot"]["maxsnaps"], + "Check interval type in list resources call" + ) + + # Sleep for (maxsnaps) hours to verify only maxsnaps snapshots are + # retained + time.sleep( + (self.services["recurring_snapshot"]["maxsnaps"]) * 3600 + ) + + timeout = self.services["timeout"] + while True: + snapshots = list_snapshots( + self.apiclient, + volumeid=volume[0].id, + intervaltype=\ + self.services["recurring_snapshot"]["intervaltype"], + snapshottype='RECURRING', + listall=True + ) + + if isinstance(snapshots, list): + break + + elif timeout == 0: + raise Exception("List snapshots API call failed.") + + time.sleep(1) + timeout = timeout - 1 + + self.assertEqual( + isinstance(snapshots, list), + True, + "Check list response returns a valid list" + ) + self.assertEqual( + len(snapshots), + self.services["recurring_snapshot"]["maxsnaps"], + "Check maximum number of recurring snapshots retained" + ) + return + + @attr(speed = "slow") + @attr(tags = ["advanced", "advancedns", "smoke", "xen"]) + def test_07_template_from_snapshot(self): + """Create Template from snapshot + """ + + #1. Login to machine; create temp/test directories on data volume + #2. Snapshot the Volume + #3. Create Template from snapshot + #4. Deploy Virtual machine using this template + #5. Login to newly created virtual machine + #6. Compare data + + random_data_0 = random_gen(100) + random_data_1 = random_gen(100) + + try: + #Login to virtual machine + ssh_client = self.virtual_machine.get_ssh_client() + + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s1 %s" % ( + self.services["rootdisk"], + self.services["mount_dir"] + ), + "mkdir -p %s/%s/{%s,%s} " % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["sub_lvl_dir2"] + ), + "echo %s > %s/%s/%s/%s" % ( + random_data_0, + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["random_data"] + ), + "echo %s > %s/%s/%s/%s" % ( + random_data_1, + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir2"], + self.services["random_data"] + ), + "sync", + ] + + for c in cmds: + self.debug(c) + result = ssh_client.execute(c) + self.debug(result) + + except Exception as e: + self.fail("SSH failed for VM with IP address: %s" % + self.virtual_machine.ipaddress) + + # Unmount the Volume + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + for c in cmds: + self.debug(c) + ssh_client.execute(c) + + volumes = list_volumes( + self.apiclient, + virtualmachineid=self.virtual_machine.id, + type='ROOT', + listall=True + ) + self.assertEqual( + isinstance(volumes, list), + True, + "Check list response returns a valid list" + ) + + volume = volumes[0] + + #Create a snapshot of volume + snapshot = Snapshot.create( + self.apiclient, + volume.id, + account=self.account.account.name, + domainid=self.account.account.domainid + ) + + self.debug("Snapshot created from volume ID: %s" % volume.id) + # Generate template from the snapshot + template = Template.create_from_snapshot( + self.apiclient, + snapshot, + self.services["templates"] + ) + self.cleanup.append(template) + self.debug("Template created from snapshot ID: %s" % snapshot.id) + + # Verify created template + templates = list_templates( + self.apiclient, + templatefilter=\ + self.services["templates"]["templatefilter"], + id=template.id + ) + self.assertNotEqual( + templates, + None, + "Check if result exists in list item call" + ) + + self.assertEqual( + templates[0].id, + template.id, + "Check new template id in list resources call" + ) + self.debug("Deploying new VM from template: %s" % template.id) + + # Deploy new virtual machine using template + new_virtual_machine = VirtualMachine.create( + self.apiclient, + self.services["server_without_disk"], + templateid=template.id, + accountid=self.account.account.name, + domainid=self.account.account.domainid, + serviceofferingid=self.service_offering.id, + mode=self.services["mode"] + ) + self.cleanup.append(new_virtual_machine) + + try: + #Login to VM & mount directory + ssh = new_virtual_machine.get_ssh_client() + + cmds = [ + "mkdir -p %s" % self.services["mount_dir"], + "mount %s1 %s" % ( + self.services["rootdisk"], + self.services["mount_dir"] + ) + ] + + for c in cmds: + ssh.execute(c) + + returned_data_0 = ssh.execute("cat %s/%s/%s/%s" % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir1"], + self.services["random_data"] + )) + self.debug(returned_data_0) + returned_data_1 = ssh.execute("cat %s/%s/%s/%s" % ( + self.services["mount_dir"], + self.services["sub_dir"], + self.services["sub_lvl_dir2"], + self.services["random_data"] + )) + self.debug(returned_data_1) + except Exception as e: + self.fail("SSH failed for VM with IP address: %s" % + new_virtual_machine.ipaddress) + #Verify returned data + self.assertEqual( + random_data_0, + returned_data_0[0], + "Verify newly attached volume contents with existing one" + ) + self.assertEqual( + random_data_1, + returned_data_1[0], + "Verify newly attached volume contents with existing one" + ) + # Unmount the volume + cmds = [ + "umount %s" % (self.services["mount_dir"]), + ] + try: + for c in cmds: + self.debug(c) + ssh_client.execute(c) + + except Exception as e: + self.fail("SSH failed for VM with IP address: %s" % + new_virtual_machine.ipaddress) + return + class TestCreateVMsnapshotTemplate(cloudstackTestCase): @classmethod @@ -115,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( @@ -411,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 @@ -763,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 @@ -823,7 +1901,7 @@ class TestSnapshotDetachedDisk(cloudstackTestCase): return @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns"]) + @attr(tags = ["advanced", "advancedns", "xen"]) def test_03_snapshot_detachedDisk(self): """Test snapshot from detached disk """ @@ -1046,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 @@ -1304,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 0aa60616fef..e9be63d66b8 100644 --- a/test/integration/component/test_templates.py +++ b/test/integration/component/test_templates.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import urllib from random import random @@ -113,7 +113,6 @@ class TestCreateTemplate(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -284,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, @@ -468,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/component/test_usage.py b/test/integration/component/test_usage.py index e5684f8694b..34dbc3780d0 100644 --- a/test/integration/component/test_usage.py +++ b/test/integration/component/test_usage.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient import datetime diff --git a/test/integration/component/test_volumes.py b/test/integration/component/test_volumes.py index 3bad5f10254..5819001e1b9 100644 --- a/test/integration/component/test_volumes.py +++ b/test/integration/component/test_volumes.py @@ -21,9 +21,9 @@ import marvin from nose.plugins.attrib import attr from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from marvin.remoteSSHClient import remoteSSHClient #Import System modules import os diff --git a/test/integration/smoke/README b/test/integration/smoke/README deleted file mode 100644 index b4c5d82ac19..00000000000 --- a/test/integration/smoke/README +++ /dev/null @@ -1,41 +0,0 @@ -Build Verification Testing (BVT) Cases --------------------------------------- -These test cases are the core functionality tests that ensure the application is stable and can be tested thoroughly. -These BVT cases definitions are located at : https://docs.google.com/a/cloud.com/spreadsheet/ccc?key=0Ak8acbfxQG8ndEppOGZSLV9mUF9idjVkTkZkajhTZkE&invite=CPij0K0L - - -Guidelines ----------- -BVT test cases are being developed using Python's unittests2. Following are certain guidelines being followed - 1. Tests exercised for the same resource should ideally be present under a single suite or file. - - 2. Time-consuming operations that create new cloud resources like server creation, volume creation etc - should not necessarily be exercised per unit test. The resources can be shared by creating them at - the class-level using setUpClass and shared across all instances during a single run. - - 3. Certain tests pertaining to NAT, Firewall and Load Balancing warrant fresh resources per test. Hence a call should be - taken by the stakeholders regarding sharing resources. - - 4. Ensure that the tearDown/tearDownClass functions clean up all the resources created during the test run. - -For more information about unittests: http://docs.python.org/library/unittest.html - - -BVT Tests ----------- -The following files contain these BVT cases: - -1. test_vm_life_cycle.py - VM Life Cycle tests -2. test_volumes.py - Volumes related tests -3. test_snapshots.py - Snapshots related tests -4. test_disk_offerings.py - Disk Offerings related tests -5. test_service_offerings.py - Service Offerings related tests -6. test_hosts.py - Hosts and Clusters related tests -7. test_iso.py - ISO related tests -8. test_network.py - Network related tests -9. test_primary_storage.py - Primary storage related tests -10. test_secondary_storage.py - Secondary storage related tests -11. test_ssvm.py - SSVM & CPVM related tests -12. test_templates.py - Templates related tests -13. test_routers.py - Router related tests - diff --git a/test/integration/smoke/test_disk_offerings.py b/test/integration/smoke/test_disk_offerings.py index eeb514aa378..4588a26c8be 100644 --- a/test/integration/smoke/test_disk_offerings.py +++ b/test/integration/smoke/test_disk_offerings.py @@ -20,11 +20,13 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr +_multiprocess_shared_ = True + class Services: """Test Disk offerings Services """ @@ -49,7 +51,6 @@ class TestCreateDiskOffering(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -112,7 +113,6 @@ class TestDiskOfferings(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/smoke/test_hosts.py b/test/integration/smoke/test_hosts.py index ad443256f3f..6f7d400eda7 100644 --- a/test/integration/smoke/test_hosts.py +++ b/test/integration/smoke/test_hosts.py @@ -20,14 +20,16 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import time +_multiprocess_shared_ = True + class Services: """Test Hosts & Clusters Services """ @@ -109,7 +111,6 @@ class TestHosts(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -226,4 +227,4 @@ class TestHosts(cloudstackTestCase): cluster.hypervisortype, "Check hypervisor type with is " + v["hypervisor"] + " or not" ) - return \ No newline at end of file + return diff --git a/test/integration/smoke/test_iso.py b/test/integration/smoke/test_iso.py index 17da99c0e36..22d424f86cc 100644 --- a/test/integration/smoke/test_iso.py +++ b/test/integration/smoke/test_iso.py @@ -20,15 +20,16 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr import urllib from random import random #Import System modules import time +_multiprocess_shared_ = True class Services: """Test ISO Services @@ -54,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": { @@ -65,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, @@ -78,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 @@ -102,14 +101,23 @@ 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 def tearDown(self): try: - - self.dbclient.close() #Clean up, terminate the created ISOs cleanup_resources(self.apiclient, self.cleanup) @@ -193,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( @@ -201,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"], @@ -247,7 +274,6 @@ class TestISO(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created ISOs, VMs cleanup_resources(self.apiclient, self.cleanup) @@ -503,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 b0a793c5c6d..e78cc43fe33 100644 --- a/test/integration/smoke/test_network.py +++ b/test/integration/smoke/test_network.py @@ -21,13 +21,14 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import time +_multiprocess_shared_ = True class Services: """Test Network Services @@ -35,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 @@ -304,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( @@ -603,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 @@ -1075,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 @@ -1235,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 @@ -1494,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 @@ -1634,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_primary_storage.py b/test/integration/smoke/test_primary_storage.py index 5c804f7ed9c..eb747fa6588 100644 --- a/test/integration/smoke/test_primary_storage.py +++ b/test/integration/smoke/test_primary_storage.py @@ -20,13 +20,14 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr -from integration.lib.common import * #Import System modules import time +_multiprocess_shared_ = True class Services: """Test Primary storage Services @@ -240,4 +241,4 @@ class TestPrimaryStorageServices(cloudstackTestCase): # Call cleanup for reusing primary storage cleanup_resources(self.apiclient, self.cleanup) self.cleanup = [] - return \ No newline at end of file + return diff --git a/test/integration/smoke/test_routers.py b/test/integration/smoke/test_routers.py index e5f4735a846..93dc7606ace 100644 --- a/test/integration/smoke/test_routers.py +++ b/test/integration/smoke/test_routers.py @@ -21,14 +21,15 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import time +_multiprocess_shared_ = True class Services: """Test router Services """ @@ -60,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 @@ -83,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_secondary_storage.py b/test/integration/smoke/test_secondary_storage.py index ef81d041b82..ff9692f9c87 100644 --- a/test/integration/smoke/test_secondary_storage.py +++ b/test/integration/smoke/test_secondary_storage.py @@ -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 @@ -20,43 +20,23 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import time - -class Services: - """Test secondary storage Services - """ - - def __init__(self): - self.services = { - "storage": { - "url": "nfs://192.168.100.131/SecStorage" - # Format: File_System_Type/Location/Path - }, - "hypervisors": { - 0: { - "hypervisor": "XenServer", - "templatefilter": "self", - }, - }, - "sleep": 60, - "timeout": 5, - } +_multiprocess_shared_ = True class TestSecStorageServices(cloudstackTestCase): - + @classmethod def setUpClass(cls): cls.api_client = super(TestSecStorageServices, cls).getClsTestClient().getApiClient() - cls.services = Services().services cls._cleanup = [] return - + @classmethod def tearDownClass(cls): try: @@ -65,16 +45,32 @@ class TestSecStorageServices(cloudstackTestCase): except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return - - def setUp(self): + def setUp(self): self.apiclient = self.testClient.getApiClient() self.cleanup = [] - self.services = Services().services # Get Zone and pod - self.domain = get_domain(self.apiclient, self.services) - self.zone = get_zone(self.apiclient, self.services) - self.pod = get_pod(self.apiclient, self.zone.id) + self.zones = [] + self.pods = [] + for zone in self.config.zones: + cmd = listZones.listZonesCmd() + cmd.name = zone.name + z = self.apiclient.listZones(cmd) + if isinstance(z, list) and len(z) > 0: + self.zones.append(z[0].id) + for pod in zone.pods: + podcmd = listPods.listPodsCmd() + podcmd.zoneid = z[0].id + p = self.apiclient.listPods(podcmd) + if isinstance(p, list) and len(p) >0: + self.pods.append(p[0].id) + + self.domains = [] + dcmd = listDomains.listDomainsCmd() + domains = self.apiclient.listDomains(dcmd) + assert isinstance(domains, list) and len(domains) > 0 + for domain in domains: + self.domains.append(domain.id) return def tearDown(self): @@ -85,62 +81,8 @@ class TestSecStorageServices(cloudstackTestCase): raise Exception("Warning: Exception during cleanup : %s" % e) return - @unittest.skip("skipped - do not add secondary storage") - def test_01_add_sec_storage(self): - """Test secondary storage - """ - - # Validate the following: - # 1. secondary storage should be added to the zone. - # 2. Verify with listHosts and type secondarystorage - - cmd = addSecondaryStorage.addSecondaryStorageCmd() - cmd.zoneid = self.zone.id - cmd.url = self.services["storage"]["url"] - sec_storage = self.apiclient.addSecondaryStorage(cmd) - - self.debug("Added secondary storage to zone: %s" % self.zone.id) - # Cleanup at the end - self._cleanup.append(sec_storage) - - self.assertEqual( - sec_storage.zoneid, - self.zone.id, - "Check zoneid where sec storage is added" - ) - - list_hosts_response = list_hosts( - self.apiclient, - type='SecondaryStorage', - id=sec_storage.id - ) - self.assertEqual( - isinstance(list_hosts_response, list), - True, - "Check list response returns a valid list" - ) - self.assertNotEqual( - len(list_hosts_response), - 0, - "Check list Hosts response" - ) - - host_response = list_hosts_response[0] - #Check if host is Up and running - self.assertEqual( - host_response.id, - sec_storage.id, - "Check ID of secondary storage" - ) - self.assertEqual( - sec_storage.type, - host_response.type, - "Check type of host from list hosts response" - ) - return - @attr(tags = ["advanced", "advancedns", "smoke", "basic", "eip", "sg"]) - def test_02_sys_vm_start(self): + def test_01_sys_vm_start(self): """Test system VM start """ @@ -152,8 +94,6 @@ class TestSecStorageServices(cloudstackTestCase): list_hosts_response = list_hosts( self.apiclient, type='Routing', - zoneid=self.zone.id, - podid=self.pod.id ) self.assertEqual( isinstance(list_hosts_response, list), @@ -176,8 +116,6 @@ class TestSecStorageServices(cloudstackTestCase): # ListStoragePools shows all primary storage pools in UP state list_storage_response = list_storage_pools( self.apiclient, - zoneid=self.zone.id, - podid=self.pod.id ) self.assertEqual( isinstance(list_storage_response, list), @@ -197,59 +135,11 @@ class TestSecStorageServices(cloudstackTestCase): "Check state of primary storage pools is Up or not" ) - # Secondary storage is added successfully - timeout = self.services["timeout"] - while True: - list_hosts_response = list_hosts( - self.apiclient, - type='SecondaryStorageVM', - zoneid=self.zone.id, - ) + list_ssvm_response = list_ssvms( + self.apiclient, + systemvmtype='secondarystoragevm', + ) - if not isinstance(list_hosts_response, list): - # Sleep to ensure Secondary storage is Up - time.sleep(int(self.services["sleep"])) - timeout = timeout - 1 - elif timeout == 0 or isinstance(list_hosts_response, list): - break - - self.assertEqual( - isinstance(list_hosts_response, list), - True, - "Check list response returns a valid list" - ) - - self.assertNotEqual( - len(list_hosts_response), - 0, - "Check list Hosts response" - ) - - host_response = list_hosts_response[0] - #Check if host is Up and running - self.assertEqual( - host_response.state, - 'Up', - "Check state of secondary storage" - ) - self.debug("Checking SSVM status in zone: %s" % self.zone.id) - - timeout = self.services["timeout"] - - while True: - list_ssvm_response = list_ssvms( - self.apiclient, - systemvmtype='secondarystoragevm', - zoneid=self.zone.id, - podid=self.pod.id - ) - if not isinstance(list_ssvm_response, list): - # Sleep to ensure SSVMs are Up and Running - time.sleep(int(self.services["sleep"])) - timeout = timeout - 1 - elif timeout == 0 or isinstance(list_ssvm_response, list): - break - self.assertEqual( isinstance(list_ssvm_response, list), True, @@ -271,109 +161,59 @@ class TestSecStorageServices(cloudstackTestCase): return @attr(tags = ["advanced", "advancedns", "smoke", "basic", "eip", "sg"]) - def test_03_sys_template_ready(self): + def test_02_sys_template_ready(self): """Test system templates are ready """ # Validate the following # If SSVM is in UP state and running - # 1. wait for listTemplates to show all builtin templates - # downloaded for all added hypervisors and in “Ready†state" + # 1. wait for listTemplates to show all builtin templates downloaded and + # in Ready state - for k, v in self.services["hypervisors"].items(): + hypervisors = {} + for zone in self.config.zones: + for pod in zone.pods: + for cluster in pod.clusters: + hypervisors[cluster.hypervisor] = "self" - self.debug("Downloading BUILTIN templates in zone: %s" % - self.zone.id) - - list_template_response = list_templates( - self.apiclient, - hypervisor=v["hypervisor"], - zoneid=self.zone.id, - templatefilter=v["templatefilter"], - listall=True, - account='system', - domainid=self.domain.id - ) + for zid in self.zones: + for k, v in hypervisors.items(): + self.debug("Checking BUILTIN templates in zone: %s" %zid) + list_template_response = list_templates( + self.apiclient, + hypervisor=k, + zoneid=zid, + templatefilter=v, + listall=True, + account='system' + ) - # Ensure all BUILTIN templates are downloaded - templateid = None - for template in list_template_response: - if template.templatetype == "BUILTIN": - templateid = template.id + # Ensure all BUILTIN templates are downloaded + templateid = None + for template in list_template_response: + if template.templatetype == "BUILTIN": + templateid = template.id - # Wait to start a downloading of template - time.sleep(self.services["sleep"]) - - while True and (templateid != None): - - timeout = self.services["timeout"] - while True: template_response = list_templates( self.apiclient, id=templateid, - zoneid=self.zone.id, - templatefilter=v["templatefilter"], + zoneid=zid, + templatefilter=v, listall=True, - account='system', - domainid=self.domain.id + account='system' ) - if isinstance(template_response, list): template = template_response[0] - break - - elif timeout == 0: - raise Exception("List template API call failed.") - - time.sleep(1) - timeout = timeout - 1 - - # If template is ready, - # template.status = Download Complete - # Downloading - x% Downloaded - # Error - Any other string - if template.status == 'Download Complete' : - break - elif 'Downloaded' not in template.status.split(): - raise Exception - elif 'Downloaded' in template.status.split(): - time.sleep(self.services["sleep"]) + else: + raise Exception("ListTemplate API returned invalid list") - #Ensuring the template is in ready state - time.sleep(self.services["sleep"]) - - timeout = self.services["timeout"] - while True: - template_response = list_templates( - self.apiclient, - id=templateid, - zoneid=self.zone.id, - templatefilter=v["templatefilter"], - listall=True, - account='system', - domainid=self.domain.id - ) - - if isinstance(template_response, list): - template = template_response[0] - break - - elif timeout == 0: - raise Exception("List template API call failed.") - - time.sleep(1) - timeout = timeout - 1 - - self.assertEqual( - isinstance(template_response, list), - True, - "Check list response returns a valid list" - ) - template = template_response[0] + if template.status == 'Download Complete': + self.debug("Template %s is ready in zone %s"%(template.templatetype, zid)) + elif 'Downloaded' not in template.status.split(): + self.debug("templates status is %s"%template.status) - self.assertEqual( - template.isready, - True, - "Check whether state of template is ready or not" - ) - return + self.assertEqual( + template.isready, + True, + "Builtin template is not ready %s in zone %s"%(template.status, zid) + ) diff --git a/test/integration/smoke/test_service_offerings.py b/test/integration/smoke/test_service_offerings.py index 5913338a207..3a8a9e156b9 100644 --- a/test/integration/smoke/test_service_offerings.py +++ b/test/integration/smoke/test_service_offerings.py @@ -20,12 +20,13 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr +_multiprocess_shared_ = True class Services: """Test Service offerings Services """ @@ -52,7 +53,6 @@ class TestCreateServiceOffering(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -132,7 +132,6 @@ class TestServiceOfferings(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) diff --git a/test/integration/smoke/test_snapshots.py b/test/integration/smoke/test_snapshots.py deleted file mode 100644 index 79a2c0a2852..00000000000 --- a/test/integration/smoke/test_snapshots.py +++ /dev/null @@ -1,1177 +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. -""" BVT tests for Snapshots -""" -#Import Local Modules -import marvin -from marvin.cloudstackTestCase import * -from marvin.cloudstackAPI import * -from marvin.remoteSSHClient import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * -from nose.plugins.attrib import attr - - -class Services: - """Test Snapshots Services - """ - - def __init__(self): - self.services = { - "account": { - "email": "test@test.com", - "firstname": "Test", - "lastname": "User", - "username": "test", - # Random characters are appended for unique - # username - "password": "password", - }, - "service_offering": { - "name": "Tiny Instance", - "displaytext": "Tiny Instance", - "cpunumber": 1, - "cpuspeed": 100, # in MHz - "memory": 64, # In MBs - }, - "disk_offering": { - "displaytext": "Small", - "name": "Small", - "disksize": 1 - }, - "server_with_disk": - { - "displayname": "Test VM -With Disk", - "username": "root", - "password": "password", - "ssh_port": 22, - "hypervisor": 'XenServer', - "privateport": 22, - "publicport": 22, - "protocol": 'TCP', - }, - - "server_without_disk": - { - "displayname": "Test VM-No Disk", - "username": "root", - "password": "password", - "ssh_port": 22, - "hypervisor": 'XenServer', - "privateport": 22, - # For NAT rule creation - "publicport": 22, - "protocol": 'TCP', - }, - - "recurring_snapshot": - { - "intervaltype": 'HOURLY', - # Frequency of snapshots - "maxsnaps": 1, # Should be min 2 - "schedule": 1, - "timezone": 'US/Arizona', - # Timezone Formats - http://cloud.mindtouch.us/CloudStack_Documentation/Developer's_Guide%3A_CloudStack - }, - - "templates": - { - "displaytext": 'Template from snapshot', - "name": 'Template from snapshot', - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', - "templatefilter": 'self', - }, - "ostypeid": '01853327-513e-4508-9628-f1f55db1946f', - # Cent OS 5.3 (64 bit) - "diskdevice": "/dev/xvdb", # Data Disk - "rootdisk": "/dev/xvda", # Root Disk - - "diskname": "Test Disk", - "size": 1, # GBs - - "mount_dir": "/mnt/tmp", - "sub_dir": "test", - "sub_lvl_dir1": "test1", - "sub_lvl_dir2": "test2", - "random_data": "random.data", - - "username": "root", - "password": "password", - "ssh_port": 22, - "sleep": 60, - "timeout": 10, - "mode": 'advanced', - # Networking mode, Advanced, Basic - } - - -class TestSnapshotRootDisk(cloudstackTestCase): - - @classmethod - def setUpClass(cls): - cls.api_client = super(TestSnapshotRootDisk, cls).getClsTestClient().getApiClient() - cls.services = Services().services - # Get Zone, Domain and templates - cls.domain = get_domain(cls.api_client, cls.services) - cls.zone = get_zone(cls.api_client, cls.services) - - template = get_template( - cls.api_client, - cls.zone.id, - cls.services["ostypeid"] - ) - cls.services["domainid"] = cls.domain.id - cls.services["server_without_disk"]["zoneid"] = cls.zone.id - cls.services["template"] = template.id - cls.services["zoneid"] = cls.zone.id - - # Create VMs, NAT Rules etc - cls.account = Account.create( - cls.api_client, - cls.services["account"], - domainid=cls.domain.id - ) - - cls.services["account"] = cls.account.account.name - - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.services["service_offering"] - ) - cls.virtual_machine = cls.virtual_machine_with_disk = \ - VirtualMachine.create( - cls.api_client, - cls.services["server_without_disk"], - templateid=template.id, - accountid=cls.account.account.name, - domainid=cls.account.account.domainid, - serviceofferingid=cls.service_offering.id, - mode=cls.services["mode"] - ) - cls._cleanup = [ - cls.service_offering, - cls.account, - ] - return - - @classmethod - def tearDownClass(cls): - try: - #Cleanup resources used - cleanup_resources(cls.api_client, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.cleanup = [] - return - - def tearDown(self): - try: - #Clean up, terminate the created instance, volumes and snapshots - cleanup_resources(self.apiclient, self.cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_01_snapshot_root_disk(self): - """Test Snapshot Root Disk - """ - - # Validate the following - # 1. listSnapshots should list the snapshot that was created. - # 2. verify that secondary storage NFS share contains - # the reqd volume under - # /secondary/snapshots//$account_id/$volumeid/$snapshot_uuid - # 3. verify backup_snap_id was non null in the `snapshots` table - - volumes = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine_with_disk.id, - type='ROOT', - listall=True - ) - - snapshot = Snapshot.create( - self.apiclient, - volumes[0].id, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - self.debug("Snapshot created: ID - %s" % snapshot.id) - - snapshots = list_snapshots( - self.apiclient, - id=snapshot.id - ) - self.assertEqual( - isinstance(snapshots, list), - True, - "Check list response returns a valid list" - ) - - self.assertNotEqual( - snapshots, - None, - "Check if result exists in list item call" - ) - self.assertEqual( - snapshots[0].id, - snapshot.id, - "Check resource id in list resources call" - ) - self.debug( - "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ - % str(snapshot.id) - ) - qresultset = self.dbclient.execute( - "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ - % str(snapshot.id) - ) - self.assertNotEqual( - len(qresultset), - 0, - "Check DB Query result set" - ) - - qresult = qresultset[0] - - snapshot_uuid = qresult[0] # backup_snap_id = snapshot UUID - account_id = qresult[1] - volume_id = qresult[2] - - self.assertNotEqual( - str(snapshot_uuid), - 'NULL', - "Check if backup_snap_id is not null" - ) - - # Get the Secondary Storage details from list Hosts - hosts = list_hosts( - self.apiclient, - type='SecondaryStorage', - zoneid=self.zone.id - ) - self.assertEqual( - isinstance(hosts, list), - True, - "Check list response returns a valid list" - ) - uuids = [] - for host in hosts: - # hosts[0].name = "nfs://192.168.100.21/export/test" - parse_url = (host.name).split('/') - # parse_url = ['nfs:', '', '192.168.100.21', 'export', 'test'] - - # Split IP address and export path from name - sec_storage_ip = parse_url[2] - # Sec Storage IP: 192.168.100.21 - - export_path = '/'.join(parse_url[3:]) - # Export path: export/test - - try: - # Login to VM to check snapshot present on sec disk - ssh_client = self.virtual_machine_with_disk.get_ssh_client() - - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s/%s %s" % ( - sec_storage_ip, - export_path, - self.services["mount_dir"] - ), - "ls %s/snapshots/%s/%s" % ( - self.services["mount_dir"], - account_id, - volume_id - ), - ] - - for c in cmds: - self.debug(c) - result = ssh_client.execute(c) - self.debug(result) - - except Exception: - self.fail("SSH failed for Virtual machine: %s" % - self.virtual_machine_with_disk.ipaddress) - - uuids.append(result) - # Unmount the Sec Storage - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - try: - for c in cmds: - self.debug(c) - result = ssh_client.execute(c) - self.debug(result) - - except Exception as e: - self.fail("SSH failed for Virtual machine: %s" % - self.virtual_machine_with_disk.ipaddress) - - res = str(uuids) - # Check snapshot UUID in secondary storage and database - self.assertEqual( - res.count(snapshot_uuid), - 1, - "Check snapshot UUID in secondary storage and database" - ) - return - - -class TestSnapshots(cloudstackTestCase): - - @classmethod - def setUpClass(cls): - cls.api_client = super(TestSnapshots, cls).getClsTestClient().getApiClient() - cls.services = Services().services - # Get Zone, Domain and templates - cls.domain = get_domain(cls.api_client, cls.services) - cls.zone = get_zone(cls.api_client, cls.services) - cls.disk_offering = DiskOffering.create( - cls.api_client, - cls.services["disk_offering"] - ) - template = get_template( - cls.api_client, - cls.zone.id, - cls.services["ostypeid"] - ) - - cls.services["domainid"] = cls.domain.id - cls.services["server_with_disk"]["zoneid"] = cls.zone.id - cls.services["server_with_disk"]["diskoffering"] = cls.disk_offering.id - - cls.services["server_without_disk"]["zoneid"] = cls.zone.id - - cls.services["template"] = template.id - cls.services["zoneid"] = cls.zone.id - cls.services["diskoffering"] = cls.disk_offering.id - - # Create VMs, NAT Rules etc - cls.account = Account.create( - cls.api_client, - cls.services["account"], - domainid=cls.domain.id - ) - - cls.services["account"] = cls.account.account.name - - cls.service_offering = ServiceOffering.create( - cls.api_client, - cls.services["service_offering"] - ) - cls.virtual_machine = cls.virtual_machine_with_disk = \ - VirtualMachine.create( - cls.api_client, - cls.services["server_with_disk"], - templateid=template.id, - accountid=cls.account.account.name, - domainid=cls.account.account.domainid, - serviceofferingid=cls.service_offering.id, - mode=cls.services["mode"] - ) - cls.virtual_machine_without_disk = \ - VirtualMachine.create( - cls.api_client, - cls.services["server_without_disk"], - templateid=template.id, - accountid=cls.account.account.name, - domainid=cls.account.account.domainid, - serviceofferingid=cls.service_offering.id, - mode=cls.services["mode"] - ) - cls._cleanup = [ - cls.service_offering, - cls.disk_offering, - cls.account, - ] - return - - @classmethod - def tearDownClass(cls): - try: - #Cleanup resources used - cleanup_resources(cls.api_client, cls._cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - def setUp(self): - self.apiclient = self.testClient.getApiClient() - self.dbclient = self.testClient.getDbConnection() - self.cleanup = [] - return - - def tearDown(self): - try: - #Clean up, terminate the created instance, volumes and snapshots - cleanup_resources(self.apiclient, self.cleanup) - except Exception as e: - raise Exception("Warning: Exception during cleanup : %s" % e) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_02_snapshot_data_disk(self): - """Test Snapshot Data Disk - """ - - volume = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine_with_disk.id, - type='DATADISK', - listall=True - ) - self.assertEqual( - isinstance(volume, list), - True, - "Check list response returns a valid list" - ) - - self.debug("Creating a Snapshot from data volume: %s" % volume[0].id) - snapshot = Snapshot.create( - self.apiclient, - volume[0].id, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - snapshots = list_snapshots( - self.apiclient, - id=snapshot.id - ) - self.assertEqual( - isinstance(snapshots, list), - True, - "Check list response returns a valid list" - ) - self.assertNotEqual( - snapshots, - None, - "Check if result exists in list item call" - ) - self.assertEqual( - snapshots[0].id, - snapshot.id, - "Check resource id in list resources call" - ) - self.debug( - "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ - % str(snapshot.id) - ) - qresultset = self.dbclient.execute( - "select backup_snap_id, account_id, volume_id from snapshots where uuid = '%s';" \ - % str(snapshot.id) - ) - self.assertNotEqual( - len(qresultset), - 0, - "Check DB Query result set" - ) - - qresult = qresultset[0] - snapshot_uuid = qresult[0] # backup_snap_id = snapshot UUID - account_id = qresult[1] - volume_id = qresult[2] - - self.assertNotEqual( - str(snapshot_uuid), - 'NULL', - "Check if backup_snap_id is not null" - ) - - # Get the Secondary Storage details from list Hosts - hosts = list_hosts( - self.apiclient, - type='SecondaryStorage', - zoneid=self.zone.id - ) - self.assertEqual( - isinstance(hosts, list), - True, - "Check list response returns a valid list" - ) - uuids = [] - for host in hosts: - # hosts[0].name = "nfs://192.168.100.21/export" - parse_url = (host.name).split('/') - # parse_url = ['nfs:', '', '192.168.100.21', 'export'] - - # Split IP address and export path from name - sec_storage_ip = parse_url[2] - # Sec Storage IP: 192.168.100.21 - - export_path = '/'.join(parse_url[3:]) - # Export path: export - - try: - # Login to VM to check snapshot present on sec disk - ssh_client = self.virtual_machine_with_disk.get_ssh_client() - - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s/%s %s" % ( - sec_storage_ip, - export_path, - self.services["mount_dir"] - ), - "ls %s/snapshots/%s/%s" % ( - self.services["mount_dir"], - account_id, - volume_id - ), - ] - for c in cmds: - self.debug(c) - result = ssh_client.execute(c) - self.debug(result) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.virtual_machine_with_disk.ipaddress) - - uuids.append(result) - # Unmount the Sec Storage - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - try: - for c in cmds: - self.debug(c) - ssh_client.execute(c) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.virtual_machine_with_disk.ipaddress) - - res = str(uuids) - # Check snapshot UUID in secondary storage and database - self.assertEqual( - res.count(snapshot_uuid), - 1, - "Check snapshot UUID in secondary storage and database" - ) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_03_volume_from_snapshot(self): - """Create volumes from snapshots - """ - #1. Login to machine; create temp/test directories on data volume - #2. Snapshot the Volume - #3. Create another Volume from snapshot - #4. Mount/Attach volume to another server - #5. Compare data - random_data_0 = random_gen(100) - random_data_1 = random_gen(100) - - try: - ssh_client = self.virtual_machine.get_ssh_client() - - #Format partition using ext3 - format_volume_to_ext3( - ssh_client, - self.services["diskdevice"] - ) - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s1 %s" % ( - self.services["diskdevice"], - self.services["mount_dir"] - ), - "mkdir -p %s/%s/{%s,%s} " % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["sub_lvl_dir2"] - ), - "echo %s > %s/%s/%s/%s" % ( - random_data_0, - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["random_data"] - ), - "echo %s > %s/%s/%s/%s" % ( - random_data_1, - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir2"], - self.services["random_data"] - ), - ] - for c in cmds: - self.debug(c) - ssh_client.execute(c) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.virtual_machine.ipaddress) - # Unmount the Sec Storage - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - - try: - for c in cmds: - self.debug(c) - ssh_client.execute(c) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.virtual_machine.ipaddress) - - list_volume_response = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine.id, - type='DATADISK', - listall=True - ) - - volume_response = list_volume_response[0] - #Create snapshot from attached volume - snapshot = Snapshot.create( - self.apiclient, - volume_response.id, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - self.debug("Created Snapshot from volume: %s" % volume_response.id) - - #Create volume from snapshot - self.debug("Creating volume from snapshot: %s" % snapshot.id) - volume = Volume.create_from_snapshot( - self.apiclient, - snapshot.id, - self.services, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - - volumes = list_volumes( - self.apiclient, - id=volume.id - ) - self.assertEqual( - isinstance(volumes, list), - True, - "Check list response returns a valid list" - ) - self.assertNotEqual( - len(volumes), - None, - "Check Volume list Length" - ) - - self.assertEqual( - volumes[0].id, - volume.id, - "Check Volume in the List Volumes" - ) - #Attaching volume to new VM - new_virtual_machine = self.virtual_machine_without_disk - self.cleanup.append(new_virtual_machine) - - cmd = attachVolume.attachVolumeCmd() - cmd.id = volume.id - cmd.virtualmachineid = new_virtual_machine.id - self.apiclient.attachVolume(cmd) - - try: - #Login to VM to verify test directories and files - ssh = new_virtual_machine.get_ssh_client() - - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s1 %s" % ( - self.services["diskdevice"], - self.services["mount_dir"] - ), - ] - - for c in cmds: - self.debug(c) - result = ssh.execute(c) - self.debug(result) - - returned_data_0 = ssh.execute("cat %s/%s/%s/%s" % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["random_data"] - )) - returned_data_1 = ssh.execute("cat %s/%s/%s/%s" % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir2"], - self.services["random_data"] - )) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.new_virtual_machine.ipaddress) - - #Verify returned data - self.assertEqual( - random_data_0, - returned_data_0[0], - "Verify newly attached volume contents with existing one" - ) - self.assertEqual( - random_data_1, - returned_data_1[0], - "Verify newly attached volume contents with existing one" - ) - # Unmount the Sec Storage - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - try: - for c in cmds: - ssh_client.execute(c) - - except Exception as e: - self.fail("SSH failed for VM with IP: %s" % - self.new_virtual_machine.ipaddress) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_04_delete_snapshot(self): - """Test Delete Snapshot - """ - - #1. Snapshot the Volume - #2. Delete the snapshot - #3. Verify snapshot is removed by calling List Snapshots API - - volumes = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine.id, - type='DATADISK', - listall=True - ) - self.assertEqual( - isinstance(volumes, list), - True, - "Check list response returns a valid list" - ) - snapshot = Snapshot.create( - self.apiclient, - volumes[0].id, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - snapshot.delete(self.apiclient) - - snapshots = list_snapshots( - self.apiclient, - id=snapshot.id - ) - - self.assertEqual( - snapshots, - None, - "Check if result exists in list item call" - ) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_05_recurring_snapshot_root_disk(self): - """Test Recurring Snapshot Root Disk - """ - #1. Create snapshot policy for root disk - #2. ListSnapshot policy should return newly created policy - #3. Verify only most recent number (maxsnaps) snapshots retailed - - volume = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine_with_disk.id, - type='ROOT', - listall=True - ) - self.assertEqual( - isinstance(volume, list), - True, - "Check list response returns a valid list" - ) - recurring_snapshot = SnapshotPolicy.create( - self.apiclient, - volume[0].id, - self.services["recurring_snapshot"] - ) - self.cleanup.append(recurring_snapshot) - - #ListSnapshotPolicy should return newly created policy - list_snapshots_policy = list_snapshot_policy( - self.apiclient, - id=recurring_snapshot.id, - volumeid=volume[0].id - ) - self.assertEqual( - isinstance(list_snapshots_policy, list), - True, - "Check list response returns a valid list" - ) - self.assertNotEqual( - list_snapshots_policy, - None, - "Check if result exists in list item call" - ) - snapshots_policy = list_snapshots_policy[0] - self.assertEqual( - snapshots_policy.id, - recurring_snapshot.id, - "Check recurring snapshot id in list resources call" - ) - self.assertEqual( - snapshots_policy.maxsnaps, - self.services["recurring_snapshot"]["maxsnaps"], - "Check interval type in list resources call" - ) - # Sleep for (maxsnaps+1) hours to verify - # only maxsnaps snapshots are retained - time.sleep( - (self.services["recurring_snapshot"]["maxsnaps"]) * 3600 - ) - - timeout = self.services["timeout"] - while True: - snapshots = list_snapshots( - self.apiclient, - volumeid=volume[0].id, - intervaltype=\ - self.services["recurring_snapshot"]["intervaltype"], - snapshottype='RECURRING', - listall=True - ) - - if isinstance(snapshots, list): - break - - elif timeout == 0: - raise Exception("List snapshots API call failed.") - - time.sleep(1) - timeout = timeout - 1 - - self.assertEqual( - isinstance(snapshots, list), - True, - "Check list response returns a valid list" - ) - - self.assertEqual( - len(snapshots), - self.services["recurring_snapshot"]["maxsnaps"], - "Check maximum number of recurring snapshots retained" - ) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_06_recurring_snapshot_data_disk(self): - """Test Recurring Snapshot data Disk - """ - #1. Create snapshot policy for data disk - #2. ListSnapshot policy should return newly created policy - #3. Verify only most recent number (maxsnaps) snapshots retailed - - volume = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine_with_disk.id, - type='DATADISK', - listall=True - ) - - self.assertEqual( - isinstance(volume, list), - True, - "Check list response returns a valid list" - ) - - recurring_snapshot = SnapshotPolicy.create( - self.apiclient, - volume[0].id, - self.services["recurring_snapshot"] - ) - self.cleanup.append(recurring_snapshot) - #ListSnapshotPolicy should return newly created policy - list_snapshots_policy = list_snapshot_policy( - self.apiclient, - id=recurring_snapshot.id, - volumeid=volume[0].id - ) - - self.assertEqual( - isinstance(list_snapshots_policy, list), - True, - "Check list response returns a valid list" - ) - - self.assertNotEqual( - list_snapshots_policy, - None, - "Check if result exists in list item call" - ) - snapshots_policy = list_snapshots_policy[0] - self.assertEqual( - snapshots_policy.id, - recurring_snapshot.id, - "Check recurring snapshot id in list resources call" - ) - self.assertEqual( - snapshots_policy.maxsnaps, - self.services["recurring_snapshot"]["maxsnaps"], - "Check interval type in list resources call" - ) - - # Sleep for (maxsnaps) hours to verify only maxsnaps snapshots are - # retained - time.sleep( - (self.services["recurring_snapshot"]["maxsnaps"]) * 3600 - ) - - timeout = self.services["timeout"] - while True: - snapshots = list_snapshots( - self.apiclient, - volumeid=volume[0].id, - intervaltype=\ - self.services["recurring_snapshot"]["intervaltype"], - snapshottype='RECURRING', - listall=True - ) - - if isinstance(snapshots, list): - break - - elif timeout == 0: - raise Exception("List snapshots API call failed.") - - time.sleep(1) - timeout = timeout - 1 - - self.assertEqual( - isinstance(snapshots, list), - True, - "Check list response returns a valid list" - ) - self.assertEqual( - len(snapshots), - self.services["recurring_snapshot"]["maxsnaps"], - "Check maximum number of recurring snapshots retained" - ) - return - - @attr(speed = "slow") - @attr(tags = ["advanced", "advancedns", "smoke"]) - def test_07_template_from_snapshot(self): - """Create Template from snapshot - """ - - #1. Login to machine; create temp/test directories on data volume - #2. Snapshot the Volume - #3. Create Template from snapshot - #4. Deploy Virtual machine using this template - #5. Login to newly created virtual machine - #6. Compare data - - random_data_0 = random_gen(100) - random_data_1 = random_gen(100) - - try: - #Login to virtual machine - ssh_client = self.virtual_machine.get_ssh_client() - - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s1 %s" % ( - self.services["rootdisk"], - self.services["mount_dir"] - ), - "mkdir -p %s/%s/{%s,%s} " % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["sub_lvl_dir2"] - ), - "echo %s > %s/%s/%s/%s" % ( - random_data_0, - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["random_data"] - ), - "echo %s > %s/%s/%s/%s" % ( - random_data_1, - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir2"], - self.services["random_data"] - ), - "sync", - ] - - for c in cmds: - self.debug(c) - result = ssh_client.execute(c) - self.debug(result) - - except Exception as e: - self.fail("SSH failed for VM with IP address: %s" % - self.virtual_machine.ipaddress) - - # Unmount the Volume - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - for c in cmds: - self.debug(c) - ssh_client.execute(c) - - volumes = list_volumes( - self.apiclient, - virtualmachineid=self.virtual_machine.id, - type='ROOT', - listall=True - ) - self.assertEqual( - isinstance(volumes, list), - True, - "Check list response returns a valid list" - ) - - volume = volumes[0] - - #Create a snapshot of volume - snapshot = Snapshot.create( - self.apiclient, - volume.id, - account=self.account.account.name, - domainid=self.account.account.domainid - ) - - self.debug("Snapshot created from volume ID: %s" % volume.id) - # Generate template from the snapshot - template = Template.create_from_snapshot( - self.apiclient, - snapshot, - self.services["templates"] - ) - self.cleanup.append(template) - self.debug("Template created from snapshot ID: %s" % snapshot.id) - - # Verify created template - templates = list_templates( - self.apiclient, - templatefilter=\ - self.services["templates"]["templatefilter"], - id=template.id - ) - self.assertNotEqual( - templates, - None, - "Check if result exists in list item call" - ) - - self.assertEqual( - templates[0].id, - template.id, - "Check new template id in list resources call" - ) - self.debug("Deploying new VM from template: %s" % template.id) - - # Deploy new virtual machine using template - new_virtual_machine = VirtualMachine.create( - self.apiclient, - self.services["server_without_disk"], - templateid=template.id, - accountid=self.account.account.name, - domainid=self.account.account.domainid, - serviceofferingid=self.service_offering.id, - mode=self.services["mode"] - ) - self.cleanup.append(new_virtual_machine) - - try: - #Login to VM & mount directory - ssh = new_virtual_machine.get_ssh_client() - - cmds = [ - "mkdir -p %s" % self.services["mount_dir"], - "mount %s1 %s" % ( - self.services["rootdisk"], - self.services["mount_dir"] - ) - ] - - for c in cmds: - ssh.execute(c) - - returned_data_0 = ssh.execute("cat %s/%s/%s/%s" % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir1"], - self.services["random_data"] - )) - self.debug(returned_data_0) - returned_data_1 = ssh.execute("cat %s/%s/%s/%s" % ( - self.services["mount_dir"], - self.services["sub_dir"], - self.services["sub_lvl_dir2"], - self.services["random_data"] - )) - self.debug(returned_data_1) - except Exception as e: - self.fail("SSH failed for VM with IP address: %s" % - new_virtual_machine.ipaddress) - #Verify returned data - self.assertEqual( - random_data_0, - returned_data_0[0], - "Verify newly attached volume contents with existing one" - ) - self.assertEqual( - random_data_1, - returned_data_1[0], - "Verify newly attached volume contents with existing one" - ) - # Unmount the volume - cmds = [ - "umount %s" % (self.services["mount_dir"]), - ] - try: - for c in cmds: - self.debug(c) - ssh_client.execute(c) - - except Exception as e: - self.fail("SSH failed for VM with IP address: %s" % - new_virtual_machine.ipaddress) - return diff --git a/test/integration/smoke/test_ssvm.py b/test/integration/smoke/test_ssvm.py index 5c9d030380d..d637f966a0b 100644 --- a/test/integration/smoke/test_ssvm.py +++ b/test/integration/smoke/test_ssvm.py @@ -21,14 +21,15 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr import telnetlib #Import System modules import time +_multiprocess_shared_ = True class Services: """Test SSVM Services diff --git a/test/integration/smoke/test_templates.py b/test/integration/smoke/test_templates.py index d68371667b5..d450a5d8122 100644 --- a/test/integration/smoke/test_templates.py +++ b/test/integration/smoke/test_templates.py @@ -21,15 +21,16 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin.remoteSSHClient import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr import urllib from random import random #Import System modules import datetime +_multiprocess_shared_ = True class Services: """Test Templates Services @@ -74,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, @@ -112,7 +111,6 @@ class TestCreateTemplate(cloudstackTestCase): def tearDown(self): try: - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -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"], @@ -418,8 +432,6 @@ class TestTemplates(cloudstackTestCase): def tearDown(self): try: - - self.dbclient.close() #Clean up, terminate the created templates cleanup_resources(self.apiclient, self.cleanup) @@ -694,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 b47c1642925..f6fe4e002a1 100644 --- a/test/integration/smoke/test_vm_life_cycle.py +++ b/test/integration/smoke/test_vm_life_cycle.py @@ -21,13 +21,14 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin.remoteSSHClient import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import time +_multiprocess_shared_ = True class Services: """Test VM Life Cycle Services """ @@ -89,7 +90,7 @@ class Services: "displaytext": "Small Instance", "cpunumber": 1, "cpuspeed": 100, - "memory": 256 + "memory": 256, }, "medium": { @@ -99,7 +100,7 @@ class Services: "displaytext": "Medium Instance", "cpunumber": 1, "cpuspeed": 100, - "memory": 256 + "memory": 256, } }, "iso": # ISO settings for Attach/Detach ISO tests @@ -108,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": { @@ -122,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', } @@ -138,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 @@ -169,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 """ @@ -184,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( @@ -218,9 +227,9 @@ class TestDeployVM(cloudstackTestCase): ) self.assertEqual( - vm_response.displayname, - self.virtual_machine.displayname, - "Check virtual machine displayname in listVirtualMachines" + vm_response.name, + self.virtual_machine.name, + "Check virtual machine name in listVirtualMachines" ) return @@ -241,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 @@ -318,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 """ @@ -354,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 """ @@ -392,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 """ @@ -668,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 """ @@ -704,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 """ @@ -817,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 """ @@ -998,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 @@ -1064,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 ed5cbafe28d..2d0cd491672 100644 --- a/test/integration/smoke/test_volumes.py +++ b/test/integration/smoke/test_volumes.py @@ -21,9 +21,9 @@ import marvin from marvin.cloudstackTestCase import * from marvin.cloudstackAPI import * from marvin.remoteSSHClient import remoteSSHClient -from integration.lib.utils import * -from integration.lib.base import * -from integration.lib.common import * +from marvin.integration.lib.utils import * +from marvin.integration.lib.base import * +from marvin.integration.lib.common import * from nose.plugins.attrib import attr #Import System modules import os @@ -31,6 +31,7 @@ import urllib import time import tempfile +_multiprocess_shared_ = True class Services: """Test Volume Services @@ -74,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, } @@ -103,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 @@ -285,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/test/setup-test-data.sh b/test/setup-test-data.sh index a0e78de339f..844c275da7c 100755 --- a/test/setup-test-data.sh +++ b/test/setup-test-data.sh @@ -20,6 +20,7 @@ usage() { printf "Usage: %s:\n [-t path to tests ] \n [-m mgmt-server ] \n + [-h hypervisor (xen|kvm) ] \n [-p hypervisor root password ] \n [-d db node url ]\n" $(basename $0) >&2 } @@ -34,7 +35,7 @@ MGMT_SVR="localhost" DB_SVR="localhost" HV_PASSWD="password" -while getopts 't:d:m:p:' OPTION +while getopts 't:d:m:p:h:' OPTION do case $OPTION in d) dflag=1 @@ -46,6 +47,9 @@ do m) mflag=1 MGMT_SVR="$OPTARG" ;; + h) hflag=1 + HV="$OPTARG" + ;; p) pflag=1 HV_PASSWD="$OPTARG" ;; @@ -56,7 +60,11 @@ do done #Damn Small Linux ISO type -ostypeid=$(mysql -uroot -Dcloud -h$DB_SVR -s -N -r -e"select uuid from guest_os where display_name='CentOS 5.3 (64-bit)'") +if [[ $HV == "kvm" ]]; then + ostypeid=$(mysql -ucloud -Dcloud -pcloud -h$DB_SVR -s -N -r -e"select uuid from guest_os where display_name='CentOS 5.5 (64-bit)'") +else + ostypeid=$(mysql -ucloud -Dcloud -pcloud -h$DB_SVR -s -N -r -e"select uuid from guest_os where display_name='CentOS 5.3 (64-bit)'") +fi if [[ $ostypeid == "" ]]; then echo "Unable to contact DB server @ $DB_SVR" exit 2 diff --git a/setup/apidoc/XmlToHtmlConverter.java b/tools/apidoc/XmlToHtmlConverter.java similarity index 100% rename from setup/apidoc/XmlToHtmlConverter.java rename to tools/apidoc/XmlToHtmlConverter.java diff --git a/setup/apidoc/build-apidoc.sh b/tools/apidoc/build-apidoc.sh old mode 100644 new mode 100755 similarity index 100% rename from setup/apidoc/build-apidoc.sh rename to tools/apidoc/build-apidoc.sh diff --git a/setup/apidoc/gen_toc.py b/tools/apidoc/gen_toc.py similarity index 98% rename from setup/apidoc/gen_toc.py rename to tools/apidoc/gen_toc.py index 1f7fe36d556..abff8d15980 100644 --- a/setup/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', @@ -124,6 +125,10 @@ known_categories = { 'PrivateGateway': 'VPC', 'StaticRoute': 'VPC', 'Tags': 'Resource tags', + 'NiciraNvpDevice': 'Nicira NVP', + 'AutoScale': 'AutoScale', + 'Counter': 'AutoScale', + 'Condition': 'AutoScale' } diff --git a/setup/apidoc/generateadmincommands.xsl b/tools/apidoc/generateadmincommands.xsl similarity index 88% rename from setup/apidoc/generateadmincommands.xsl rename to tools/apidoc/generateadmincommands.xsl index 5f576c0f887..bb5dc51774d 100644 --- a/setup/apidoc/generateadmincommands.xsl +++ b/tools/apidoc/generateadmincommands.xsl @@ -1,4 +1,22 @@ + diff --git a/setup/apidoc/generatecommand.xsl b/tools/apidoc/generatecommand.xsl similarity index 90% rename from setup/apidoc/generatecommand.xsl rename to tools/apidoc/generatecommand.xsl index 0d2e8622711..b665cf36f7d 100644 --- a/setup/apidoc/generatecommand.xsl +++ b/tools/apidoc/generatecommand.xsl @@ -1,4 +1,22 @@ + diff --git a/setup/apidoc/generatecustomcommand.xsl b/tools/apidoc/generatecustomcommand.xsl similarity index 100% rename from setup/apidoc/generatecustomcommand.xsl rename to tools/apidoc/generatecustomcommand.xsl diff --git a/setup/apidoc/generatedomainadmincommands.xsl b/tools/apidoc/generatedomainadmincommands.xsl similarity index 88% rename from setup/apidoc/generatedomainadmincommands.xsl rename to tools/apidoc/generatedomainadmincommands.xsl index 7d60ef2b91f..de67a056f86 100644 --- a/setup/apidoc/generatedomainadmincommands.xsl +++ b/tools/apidoc/generatedomainadmincommands.xsl @@ -1,4 +1,22 @@ + diff --git a/setup/apidoc/generategenericcommand.xsl b/tools/apidoc/generategenericcommand.xsl similarity index 100% rename from setup/apidoc/generategenericcommand.xsl rename to tools/apidoc/generategenericcommand.xsl diff --git a/setup/apidoc/generatetoc.xsl b/tools/apidoc/generatetoc.xsl similarity index 100% rename from setup/apidoc/generatetoc.xsl rename to tools/apidoc/generatetoc.xsl diff --git a/tools/apidoc/generatetoc_footer.xsl b/tools/apidoc/generatetoc_footer.xsl new file mode 100644 index 00000000000..cf6dbc4c7b3 --- /dev/null +++ b/tools/apidoc/generatetoc_footer.xsl @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + diff --git a/setup/apidoc/generatetoc_header.xsl b/tools/apidoc/generatetoc_header.xsl similarity index 100% rename from setup/apidoc/generatetoc_header.xsl rename to tools/apidoc/generatetoc_header.xsl diff --git a/setup/apidoc/generateusercommands.xsl b/tools/apidoc/generateusercommands.xsl similarity index 88% rename from setup/apidoc/generateusercommands.xsl rename to tools/apidoc/generateusercommands.xsl index ca0eb1f6eaf..fe8ac91d890 100644 --- a/setup/apidoc/generateusercommands.xsl +++ b/tools/apidoc/generateusercommands.xsl @@ -1,4 +1,22 @@ + diff --git a/setup/apidoc/images/api_bullets.gif b/tools/apidoc/images/api_bullets.gif similarity index 100% rename from setup/apidoc/images/api_bullets.gif rename to tools/apidoc/images/api_bullets.gif diff --git a/setup/apidoc/images/back_button.gif b/tools/apidoc/images/back_button.gif similarity index 100% rename from setup/apidoc/images/back_button.gif rename to tools/apidoc/images/back_button.gif diff --git a/setup/apidoc/images/back_button_hover.gif b/tools/apidoc/images/back_button_hover.gif similarity index 100% rename from setup/apidoc/images/back_button_hover.gif rename to tools/apidoc/images/back_button_hover.gif diff --git a/setup/apidoc/images/cloudstack.png b/tools/apidoc/images/cloudstack.png similarity index 100% rename from setup/apidoc/images/cloudstack.png rename to tools/apidoc/images/cloudstack.png diff --git a/setup/apidoc/images/ins_buttonshadow.gif b/tools/apidoc/images/ins_buttonshadow.gif similarity index 100% rename from setup/apidoc/images/ins_buttonshadow.gif rename to tools/apidoc/images/ins_buttonshadow.gif diff --git a/setup/apidoc/images/insdownload_button.gif b/tools/apidoc/images/insdownload_button.gif similarity index 100% rename from setup/apidoc/images/insdownload_button.gif rename to tools/apidoc/images/insdownload_button.gif diff --git a/setup/apidoc/images/insdownload_button_hover.gif b/tools/apidoc/images/insdownload_button_hover.gif similarity index 100% rename from setup/apidoc/images/insdownload_button_hover.gif rename to tools/apidoc/images/insdownload_button_hover.gif diff --git a/setup/apidoc/images/insjoincomm_button.gif b/tools/apidoc/images/insjoincomm_button.gif similarity index 100% rename from setup/apidoc/images/insjoincomm_button.gif rename to tools/apidoc/images/insjoincomm_button.gif diff --git a/setup/apidoc/images/insjoincomm_button_hover.gif b/tools/apidoc/images/insjoincomm_button_hover.gif similarity index 100% rename from setup/apidoc/images/insjoincomm_button_hover.gif rename to tools/apidoc/images/insjoincomm_button_hover.gif diff --git a/setup/apidoc/includes/main.css b/tools/apidoc/includes/main.css similarity index 100% rename from setup/apidoc/includes/main.css rename to tools/apidoc/includes/main.css diff --git a/tools/apidoc/pom.xml b/tools/apidoc/pom.xml new file mode 100644 index 00000000000..b75ee826372 --- /dev/null +++ b/tools/apidoc/pom.xml @@ -0,0 +1,84 @@ + + + 4.0.0 + cloud-apidoc + Apache CloudStack apidoc Tools + pom + + org.apache.cloudstack + cloudstack + 4.1.0-SNAPSHOT + ../../pom.xml + + + + org.apache.cloudstack + cloud-client-ui + ${project.version} + war + + + + ../../client/target/cloud-client-ui-4.1.0-SNAPSHOT/WEB-INF/ + ${client.config.base}/lib + ${client.config.base}/classes + + + + install + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + compile + compile + + exec + + + bash + + -x + ./build-apidoc.sh + ${client.config.jars} + ${client.config.jars} + ./target + -f + ${client.config.conf}/commands.properties,${client.config.conf}/commands-ext.properties,${client.config.conf}/virtualrouter_commands.properties,${client.config.conf}/nicira-nvp_commands.properties + + + + + package + package + + exec + + + target + tar + + -cvjf + apidoc.tar.bz2 + xmldoc + + + + + + + + diff --git a/tools/build/build_asf.sh b/tools/build/build_asf.sh index 52f82a6c710..c652a20bf42 100755 --- a/tools/build/build_asf.sh +++ b/tools/build/build_asf.sh @@ -78,29 +78,24 @@ if [ -d "$outputdir" ]; then else mkdir $outputdir fi -cp $sourcedir/KEYS $outputdir/KEYS cd $sourcedir echo 'archiving' -git archive --format=tar.gz --prefix=apache-cloudstack-$version-incubating-src/ $branch > $outputdir/apache-cloudstack-$version-incubating-src.tar.gz -git archive --format=zip --prefix=apache-cloudstack-$version-incubating-src/ $branch > $outputdir/apache-cloudstack-$version-incubating-src.zip +git archive --format=tar --prefix=apache-cloudstack-$version-incubating-src/ $branch > $outputdir/apache-cloudstack-$version-incubating-src.tar +bzip2 $outputdir/apache-cloudstack-$version-incubating-src.tar cd $outputdir echo 'armor' -gpg -v $keyid --armor --output apache-cloudstack-$version-incubating-src.tar.gz.asc --detach-sig apache-cloudstack-$version-incubating-src.tar.gz -gpg -v $keyid --armor --output apache-cloudstack-$version-incubating-src.zip.asc --detach-sig apache-cloudstack-$version-incubating-src.zip +gpg -v $keyid --armor --output apache-cloudstack-$version-incubating-src.tar.bz2.asc --detach-sig apache-cloudstack-$version-incubating-src.tar.bz2 echo 'md5' -gpg -v --print-md MD5 apache-cloudstack-$version-incubating-src.tar.gz > apache-cloudstack-$version-incubating-src.tar.gz.md5 -gpg -v --print-md MD5 apache-cloudstack-$version-incubating-src.zip > apache-cloudstack-$version-incubating-src.zip.md5 +gpg -v --print-md MD5 apache-cloudstack-$version-incubating-src.tar.bz2 > apache-cloudstack-$version-incubating-src.tar.bz2.md5 echo 'sha' -gpg -v --print-md SHA512 apache-cloudstack-$version-incubating-src.tar.gz > apache-cloudstack-$version-incubating-src.tar.gz.sha -gpg -v --print-md SHA512 apache-cloudstack-$version-incubating-src.zip > apache-cloudstack-$version-incubating-src.zip.sha +gpg -v --print-md SHA512 apache-cloudstack-$version-incubating-src.tar.bz2 > apache-cloudstack-$version-incubating-src.tar.bz2.sha echo 'verify' -gpg -v --verify apache-cloudstack-$version-incubating-src.tar.gz.asc apache-cloudstack-$version-incubating-src.tar.gz -gpg -v --verify apache-cloudstack-$version-incubating-src.zip.asc apache-cloudstack-$version-incubating-src.zip +gpg -v --verify apache-cloudstack-$version-incubating-src.tar.bz2.asc apache-cloudstack-$version-incubating-src.tar.bz2 if [ $tag == 'yes' ]; then echo 'tag' diff --git a/tools/build/build_docs.sh b/tools/build/build_docs.sh index 34e459f7b94..8bb63e30e87 100755 --- a/tools/build/build_docs.sh +++ b/tools/build/build_docs.sh @@ -51,5 +51,5 @@ fi cd $sourcedir/docs cp -R /usr/share/publican/Common_Content . ln -s $sourcedir/docs/publican-cloudstack Common_Content/cloudstack -publican build --config=publican-all.cfg --formats html,pdf --langs en-US --common_content=$sourcedir/docs/Common_Content +publican build --config=publican-installation.cfg --formats html,pdf --langs en-US --common_content=$sourcedir/docs/Common_Content rm -r Common_Content \ No newline at end of file diff --git a/tools/cli/cloudmonkey/__init__.py b/tools/cli/cloudmonkey/__init__.py new file mode 100644 index 00000000000..967477794bf --- /dev/null +++ b/tools/cli/cloudmonkey/__init__.py @@ -0,0 +1,21 @@ +# 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. + +try: + from common import __version__ +except ImportError, e: + print e diff --git a/tools/cli/cloudmonkey/cachegen.py b/tools/cli/cloudmonkey/cachegen.py new file mode 100644 index 00000000000..e03b6fddf89 --- /dev/null +++ b/tools/cli/cloudmonkey/cachegen.py @@ -0,0 +1,92 @@ +# 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. + +try: + from common import grammar + from marvin.cloudstackAPI import * + from marvin import cloudstackAPI +except ImportError, e: + pass + +completions = cloudstackAPI.__all__ + + +def get_api_module(api_name, api_class_strs=[]): + try: + api_mod = __import__("marvin.cloudstackAPI.%s" % api_name, + globals(), locals(), api_class_strs, -1) + except ImportError, e: + print "Error: API not found", e + return None + return api_mod + + +def main(): + """ + cachegen.py creates a precached dictionary for all the available verbs in + the predefined grammar of cloudmonkey, it dumps the dictionary in an + importable python module. This way we cheat on the runtime overhead of + completing commands and help docs. This reduces the overall search and + cache_miss (computation) complexity from O(n) to O(1) for any valid cmd. + """ + # datastructure {'verb': {cmd': ['api', [params], doc, required=[]]}} + cache_verbs = {} + for verb in grammar: + completions_found = filter(lambda x: x.startswith(verb), completions) + cache_verbs[verb] = {} + for api_name in completions_found: + api_cmd_str = "%sCmd" % api_name + api_mod = get_api_module(api_name, [api_cmd_str]) + if api_mod is None: + continue + try: + api_cmd = getattr(api_mod, api_cmd_str)() + required = api_cmd.required + doc = api_mod.__doc__ + except AttributeError, e: + print "Error: API attribute %s not found!" % e + params = filter(lambda x: '__' not in x and 'required' not in x, + dir(api_cmd)) + if len(required) > 0: + doc += "\nRequired args: %s" % " ".join(required) + doc += "\nArgs: %s" % " ".join(params) + api_name_lower = api_name.replace(verb, '').lower() + cache_verbs[verb][api_name_lower] = [api_name, params, doc, + required] + f = open("precache.py", "w") + f.write("""# Auto-generated code by cachegen.py +# 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.""") + f.write("\nprecached_verbs = %s" % cache_verbs) + f.close() + +if __name__ == "__main__": + main() diff --git a/tools/cli/cloudmonkey/cloudmonkey.py b/tools/cli/cloudmonkey/cloudmonkey.py new file mode 100644 index 00000000000..339a2014522 --- /dev/null +++ b/tools/cli/cloudmonkey/cloudmonkey.py @@ -0,0 +1,537 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# 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. + +try: + import atexit + import cmd + import clint + import codecs + import json + import logging + import os + import pdb + import shlex + import sys + import time + import types + + from clint.textui import colored + from ConfigParser import ConfigParser, SafeConfigParser + 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 + from marvin.cloudstackException import cloudstackAPIException + from marvin.cloudstackAPI import * + from marvin import cloudstackAPI +except ImportError, e: + print "Import error in %s : %s" % (__name__, e) + import sys + sys.exit() + +# Fix autocompletion issue, can be put in .pythonstartup +try: + import readline +except ImportError, e: + print "Module readline not found, autocompletions will fail", e +else: + import rlcompleter + if 'libedit' in readline.__doc__: + readline.parse_and_bind("bind ^I rl_complete") + else: + readline.parse_and_bind("tab: complete") + +log_fmt = '%(asctime)s - %(filename)s:%(lineno)s - [%(levelname)s] %(message)s' +logger = logging.getLogger(__name__) +completions = cloudstackAPI.__all__ + + +class CloudMonkeyShell(cmd.Cmd, object): + intro = ("☠Apache CloudStack 🵠cloudmonkey " + __version__ + + ". Type help or ? to list commands.\n") + ruler = "=" + config_file = config_file + config_fields = config_fields + grammar = grammar + # datastructure {'verb': {cmd': ['api', [params], doc, required=[]]}} + cache_verbs = precached_verbs + + def __init__(self): + if os.path.exists(self.config_file): + config = self.read_config() + else: + for key in self.config_fields.keys(): + setattr(self, key, self.config_fields[key]) + config = self.write_config() + print "Welcome! Using `set` configure the necessary settings:" + print " ".join(sorted(self.config_fields.keys())) + print "Config file:", self.config_file + print "For debugging, tail -f", self.log_file, "\n" + + for key in self.config_fields.keys(): + try: + setattr(self, key, config.get('CLI', key)) + self.config_fields[key] = config.get('CLI', key) + except Exception: + print "Please fix `%s` config in %s" % (key, self.config_file) + sys.exit() + + self.prompt = self.prompt.strip() + " " # Cosmetic fix for prompt + logging.basicConfig(filename=self.log_file, + level=logging.DEBUG, format=log_fmt) + logger.debug("Loaded config fields:\n%s" % self.config_fields) + + cmd.Cmd.__init__(self) + # Update config if config_file does not exist + if not os.path.exists(self.config_file): + config = self.write_config() + + # Enable history support + try: + if os.path.exists(self.history_file): + readline.read_history_file(self.history_file) + atexit.register(readline.write_history_file, self.history_file) + except IOError: + print("Error: history support") + + def read_config(self): + config = ConfigParser() + try: + with open(self.config_file, 'r') as cfg: + config.readfp(cfg) + except IOError, e: + self.print_shell("Error: config_file not found", e) + return config + + def write_config(self): + config = ConfigParser() + config.add_section('CLI') + for key in self.config_fields.keys(): + config.set('CLI', key, getattr(self, key)) + with open(self.config_file, 'w') as cfg: + config.write(cfg) + return config + + 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: + arg = str(arg) + if isinstance(type(args), types.NoneType): + continue + if self.color == 'true': + if str(arg).count(self.ruler) == len(str(arg)): + print colored.green(arg), + elif 'Error' in arg: + print colored.red(arg), + elif ":\n=" in arg: + print colored.red(arg), + elif ':' in arg: + print colored.blue(arg), + elif 'type' in arg: + print colored.green(arg), + elif 'state' in arg or 'count' in arg: + print colored.magenta(arg), + elif 'id =' in arg: + print colored.yellow(arg), + elif 'name =' in arg: + print colored.cyan(arg), + else: + print arg, + else: + print arg, + print + except Exception, e: + print colored.red("Error: "), e + + def print_result(self, result, result_filter=None): + if result is None or len(result) == 0: + return + + 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 sorted(result.keys(), + key=lambda x: x != 'id' and x != 'count' and x): + 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.ruler) + self.print_result(result[key], result_filter) + + 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, result_filter) + elif isinstance(result, list): + print_result_as_list(result, result_filter) + elif isinstance(result, str): + print result + elif not (str(result) is None): + self.print_shell(result) + + def make_request(self, command, requests={}, isAsync=False): + conn = cloudConnection(self.host, port=int(self.port), + apiKey=self.apikey, securityKey=self.secretkey, + asyncTimeout=self.timeout, logging=logger, + protocol=self.protocol, path=self.path) + response = None + logger.debug("====START Request====") + logger.debug("Requesting command=%s, args=%s" % (command, requests)) + try: + response = conn.make_request_with_auth(command, requests) + except cloudstackAPIException, e: + self.print_shell("API Error:", e) + except HTTPError, e: + self.print_shell(e) + except (URLError, BadStatusLine), e: + self.print_shell("Connection Error:", e) + logger.debug("====END Request====\n") + + def process_json(response): + try: + response = json.loads(str(response)) + except ValueError, e: + pass + return response + + response = process_json(response) + if response is None: + return + + isAsync = isAsync and (self.asyncblock == "true") + if isAsync and 'jobid' in response[response.keys()[0]]: + jobId = response[response.keys()[0]]['jobid'] + command = "queryAsyncJobResult" + requests = {'jobid': jobId} + timeout = int(self.timeout) + pollperiod = 3 + progress = 1 + while timeout > 0: + print '\r' + '.' * progress, + sys.stdout.flush() + response = process_json(conn.make_request_with_auth(command, + requests)) + responsekeys = filter(lambda x: 'response' in x, + response.keys()) + if len(responsekeys) < 1: + continue + result = response[responsekeys[0]] + jobstatus = result['jobstatus'] + if jobstatus == 2: + jobresult = result["jobresult"] + self.print_shell("Async query failed for jobid=", + jobId, "\nError", jobresult["errorcode"], + jobresult["errortext"]) + return + elif jobstatus == 1: + print '\r', + return response + time.sleep(pollperiod) + timeout = timeout - pollperiod + progress += 1 + logger.debug("job: %s to timeout in %ds" % (jobId, timeout)) + self.print_shell("Error:", "Async query timeout for jobid=", jobId) + + return response + + def get_api_module(self, api_name, api_class_strs=[]): + try: + api_mod = __import__("marvin.cloudstackAPI.%s" % api_name, + globals(), locals(), api_class_strs, -1) + except ImportError, e: + self.print_shell("Error: API not found", e) + return None + return api_mod + + def default(self, args): + lexp = shlex.shlex(args.strip()) + lexp.whitespace = " " + lexp.whitespace_split = True + lexp.posix = True + args = [] + while True: + next_val = lexp.next() + if next_val is None: + break + args.append(next_val) + api_name = args[0] + + 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(','))) + + api_cmd_str = "%sCmd" % api_name + api_mod = self.get_api_module(api_name, [api_cmd_str]) + if api_mod is None: + return + + try: + api_cmd = getattr(api_mod, api_cmd_str) + except AttributeError, e: + self.print_shell("Error: API attribute %s not found!" % e) + return + + for attribute in args_dict.keys(): + setattr(api_cmd, attribute, args_dict[attribute]) + + command = api_cmd() + 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)) + return + + isAsync = False + if "isAsync" in dir(command): + isAsync = (command.isAsync == "true") + + result = self.make_request(api_name, args_dict, isAsync) + if result is None: + return + try: + responsekeys = filter(lambda x: 'response' in x, result.keys()) + for responsekey in responsekeys: + self.print_result(result[responsekey], field_filter) + print + except Exception as e: + self.print_shell("🙈 Error on parsing and printing", e) + + def completedefault(self, text, line, begidx, endidx): + partitions = line.partition(" ") + verb = partitions[0] + rline = partitions[2].partition(" ") + subject = rline[0] + separator = rline[1] + params = rline[2] + + if verb not in self.grammar: + return [] + + autocompletions = [] + search_string = "" + + if separator != " ": # Complete verb subjects + autocompletions = self.cache_verbs[verb].keys() + search_string = subject + else: # Complete subject params + autocompletions = map(lambda x: x + "=", + 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): + """ + Make raw api calls. Syntax: api =. + + Example: + api listAccount listall=true + """ + if len(args) > 0: + return self.default(args) + else: + self.print_shell("Please use a valid syntax") + + def complete_api(self, text, line, begidx, endidx): + mline = line.partition(" ")[2] + offs = len(mline) - len(text) + return [s[offs:] for s in completions if s.startswith(mline)] + + def do_set(self, args): + """ + 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. + + Example: + set host 192.168.56.2 + set prompt 🵠cloudmonkey> + set log_file /var/log/cloudmonkey.log + """ + args = args.strip().partition(" ") + key, value = (args[0], args[2]) + setattr(self, key, value) # keys and attributes should have same names + self.prompt = self.prompt.strip() + " " # prompt fix + self.write_config() + + def complete_set(self, text, line, begidx, endidx): + mline = line.partition(" ")[2] + offs = len(mline) - len(text) + return [s[offs:] for s in self.config_fields.keys() + if s.startswith(mline)] + + def do_shell(self, args): + """ + Execute shell commands using shell or ! + + Example: + !ls + shell ls + !for((i=0; i<10; i++)); do cloudmonkey create user account=admin \ + email=test@test.tt firstname=user$i lastname=user$i \ + password=password username=user$i; done + """ + os.system(args) + + def do_help(self, args): + """ + Show help docs for various topics + + Example: + help list + help list users + ?list + ?list users + """ + fields = args.partition(" ") + if fields[2] == "": + cmd.Cmd.do_help(self, args) + else: + verb = fields[0] + subject = fields[2].partition(" ")[0] + + if subject in self.cache_verbs[verb]: + self.print_shell(self.cache_verbs[verb][subject][2]) + else: + self.print_shell("Error: no such api (%s) on %s" % + (subject, verb)) + + def complete_help(self, text, line, begidx, endidx): + fields = line.partition(" ") + subfields = fields[2].partition(" ") + + if subfields[1] != " ": + return cmd.Cmd.complete_help(self, text, line, begidx, endidx) + else: + line = fields[2] + text = subfields[2] + return self.completedefault(text, line, begidx, endidx) + + def do_exit(self, args): + """ + Quit CloudMonkey CLI + """ + return self.do_quit(args) + + def do_quit(self, args): + """ + Quit CloudMonkey CLI + """ + self.print_shell("Bye!") + return self.do_EOF(args) + + def do_EOF(self, args): + """ + Quit on Ctrl+d or EOF + """ + sys.exit() + + +def main(): + # Create handlers on the fly using closures + self = CloudMonkeyShell + global grammar + for rule in grammar: + def add_grammar(rule): + def grammar_closure(self, args): + if '|' in args: # FIXME: Consider parsing issues + prog_name = sys.argv[0] + if '.py' in prog_name: + prog_name = "python " + prog_name + self.do_shell("%s %s %s" % (prog_name, rule, args)) + return + 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 + if ' --help' in args or ' -h' in args: + self.print_shell(res[2]) + return + self.default(res[0] + " " + args_partition[2]) + return grammar_closure + + grammar_handler = add_grammar(rule) + grammar_handler.__doc__ = "%ss resources" % rule.capitalize() + grammar_handler.__name__ = 'do_' + rule + setattr(self, grammar_handler.__name__, grammar_handler) + + shell = CloudMonkeyShell() + if len(sys.argv) > 1: + shell.onecmd(' '.join(sys.argv[1:])) + else: + shell.cmdloop() + +if __name__ == "__main__": + main() diff --git a/tools/cli/cloudmonkey/common.py b/tools/cli/cloudmonkey/common.py new file mode 100644 index 00000000000..3199af26c85 --- /dev/null +++ b/tools/cli/cloudmonkey/common.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# 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. + +# Use following rules for versioning: +# .. +__version__ = "4.0.0" + +try: + import os + from precache import precached_verbs +except ImportError, e: + precached_verbs = {} + +# Add config key:value +config_file = os.path.expanduser('~/.cloudmonkey_config') +config_fields = {'host': 'localhost', 'port': '8080', + 'protocol': 'http', 'path': '/client/api', + 'apikey': '', 'secretkey': '', + 'timeout': '3600', 'asyncblock': 'true', + 'prompt': '🵠cloudmonkey>', 'color': 'true', + 'tabularize': 'false', + 'log_file': + os.path.expanduser('~/.cloudmonkey_log'), + 'history_file': + os.path.expanduser('~/.cloudmonkey_history')} + +# Add verbs in grammar +grammar = ['create', 'list', 'delete', 'update', + 'enable', 'activate', 'disable', 'add', 'remove', + 'attach', 'detach', 'associate', 'generate', 'ldap', + 'assign', 'authorize', 'change', 'register', 'configure', + 'start', 'restart', 'reboot', 'stop', 'reconnect', + 'cancel', 'destroy', 'revoke', 'mark', 'reset', + 'copy', 'extract', 'migrate', 'restore', 'suspend', + 'get', 'query', 'prepare', 'deploy', 'upload'] diff --git a/tools/cli/pom.xml b/tools/cli/pom.xml new file mode 100644 index 00000000000..aba5ec3c2a5 --- /dev/null +++ b/tools/cli/pom.xml @@ -0,0 +1,107 @@ + + + 4.0.0 + cloud-cli + Apache CloudStack Developer Tools: cloudmonkey cli + pom + + org.apache.cloudstack + cloudstack + 4.1.0-SNAPSHOT + ../../pom.xml + + + + install + + + maven-antrun-plugin + 1.7 + + + generate-resource + generate-resources + + run + + + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + compile + compile + + exec + + + ${basedir} + cp + + -rv + ${basedir}/../marvin/marvin + ${basedir}/cloudmonkey + + + + + cachegen + compile + + exec + + + ${basedir}/cloudmonkey + python + + cachegen.py + + + + + package + compile + + exec + + + ${basedir} + python + + setup.py + sdist + + + + + + + + diff --git a/tools/cli/setup.py b/tools/cli/setup.py new file mode 100644 index 00000000000..739c044f7dd --- /dev/null +++ b/tools/cli/setup.py @@ -0,0 +1,70 @@ +# 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. + +try: + from setuptools import setup, find_packages +except ImportError: + from distribute_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + +from cloudmonkey import __version__ + +name = 'cloudmonkey' +version = __version__ +requires = ['clint>=0.3.0', + 'prettytable>=0.6', + ] + +try: + import readline +except ImportError: + requires.append('readline') + +setup( + name = name, + version = version, + author = "The Apache CloudStack Team", + author_email = "cloudstack-dev@incubator.apache.org", + maintainer = "Rohit Yadav", + maintainer_email = "bhaisaab@apache.org", + url = "http://incubator.apache.org/cloudstack", + description = "Command Line Interface for Apache CloudStack", + long_description = "cloudmonkey is a command line interface for Apache " + "CloudStack powered by CloudStack Marvin", + platforms = ("Any",), + license = 'ASL 2.0', + packages = find_packages(), + install_requires = requires, + include_package_data = True, + zip_safe = False, + classifiers = [ + "Development Status :: 4 - Beta", + "Environment :: Console", + "Intended Audience :: Developers", + "Intended Audience :: End Users/Desktop", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Topic :: Software Development :: Testing", + "Topic :: Software Development :: Interpreters", + "Topic :: Utilities", + ], + entry_points=""" + [console_scripts] + cloudmonkey = cloudmonkey.cloudmonkey:main + """, +) diff --git a/tools/devcloud/README b/tools/devcloud/README deleted file mode 100644 index b0161543284..00000000000 --- a/tools/devcloud/README +++ /dev/null @@ -1,56 +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. - -=========================================================== - -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. - -=========================================================== -Contents: - -This folder contains various scripts used to build the devcloud image. -devcloudsetup.sh - the origional devcloud build script (assumes an Ubuntu 12.04 VM image) - -build_vagrant_basebox.sh - a script that uses VirtualBox, VeeWee, Vagrant (patched) and puppet to create a devcloud basebox -veewee - configuration files used to build a basic Ubuntu 12.04 vagrant box via VeeWee -basebuild - The Vagrantfile and puppet module that gets applied to the basic Ubuntu 12.04 box -devcloudbox - The Vagrantfile and puppet module that is used with the [hopefully] distributed devcloud base box - -=========================================================== -Instructions: - -To build a "devcloud base box", run you need a system with VirtualBox and rvm -installed (use ruby 1.9.2). Run build_vagrant_basebox.sh to build the base box. - -To use the "devcloud base box" that is created in the previous step, you -need to have installed a forked version of Vagrant (until we make the changes -plugins instead of direct source patches) that can be found here: - - -Once installed per the Vagrant installation process, run: - -vagrant box add devcloud [path to devcloud.box] - -Then, either go into the devcloudbox folder of your checked out -version of the CloudStack code (incubator-cloudstack/tools/devcloud/devcloudbox), -or copy the contents of that folder to another location. - -Assuming the patched Vagrant installation is working, you then -simply run "vagrant up" from within that directory. - 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 10fca376442..8d296eb7b98 100644 --- a/tools/devcloud/devcloud.cfg +++ b/tools/devcloud/devcloud.cfg @@ -33,15 +33,15 @@ "networktype": "Basic", "pods": [ { - "endip": "10.0.2.220", + "endip": "192.168.56.220", "name": "test00", - "startip": "10.0.2.200", + "startip": "192.168.56.200", "guestIpRanges": [ { - "startip": "10.0.2.100", - "endip": "10.0.2.199", + "startip": "192.168.56.100", + "endip": "192.168.56.199", "netmask": "255.255.255.0", - "gateway": "10.0.2.2" + "gateway": "192.168.56.1" } ], "netmask": "255.255.255.0", @@ -52,21 +52,20 @@ "hosts": [ { "username": "root", - "url": "http://10.0.2.15/", + "url": "http://192.168.56.10/", "password": "password" } ], "clustertype": "CloudManaged" } ], - "gateway": "10.0.2.2" + "gateway": "192.168.56.1" } ], - "internaldns1": "10.0.2.3", - "internaldns2": "10.0.2.3", + "internaldns1": "192.168.56.1", "secondaryStorages": [ { - "url": "nfs://10.0.2.15:/opt/storage/secondary" + "url": "nfs://192.168.56.10:/opt/storage/secondary" } ] } @@ -81,36 +80,18 @@ "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" - } - ], "mgtSvr": [ { "mgtSvrIp": "127.0.0.1", "port": 8096 } - ] + ], + "dbSvr": + { + "dbSvr": "127.0.0.1", + "port": 3306, + "user": "cloud", + "passwd": "cloud", + "db": "cloud" + } } diff --git a/tools/devcloud/devcloud.sql b/tools/devcloud/devcloud.sql new file mode 100644 index 00000000000..cebf5a3702e --- /dev/null +++ b/tools/devcloud/devcloud.sql @@ -0,0 +1,40 @@ +-- 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. + + +INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, use_local_storage, type, disk_size) VALUES (17, 'tinyOffering', UUID(), 'tinyOffering', NOW(), 1, 'Service', 0); +INSERT INTO `cloud`.`service_offering` (id, cpu, speed, ram_size) VALUES (17, 1, 100, 100); +INSERT INTO `cloud`.`disk_offering` (id, name, uuid, display_text, created, type, disk_size) VALUES (18, 'tinyDiskOffering', UUID(), 'tinyDiskOffering', NOW(), 'Disk', 1073741824); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.ram.size', '100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','router.cpu.mhz','100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.ram.size','100'); +INSERT INTO `cloud`.`configuration` (instance, name,value) VALUE('DEFAULT','console.cpu.mhz', '100'); +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'; +UPDATE `cloud`.`vm_template` SET unique_name="tiny Linux",name="tiny Linux",url="https://github.com/downloads/bhaisaab/incubator-cloudstack/ttylinux_pv.vhd",checksum="046e134e642e6d344b34648223ba4bc1",display_text="tiny Linux" where id=5; 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/pom.xml b/tools/devcloud/pom.xml index 5f37d65389b..c40a4f0fd4e 100644 --- a/tools/devcloud/pom.xml +++ b/tools/devcloud/pom.xml @@ -20,51 +20,116 @@ 4.1.0-SNAPSHOT ../../pom.xml + + + mysql + mysql-connector-java + 5.1.21 + runtime + + + install - clean + deploydb - clean + deploydb - - - org.apache.maven.plugins - maven-antrun-plugin + org.codehaus.mojo + properties-maven-plugin + 1.0-alpha-2 - integration-test + initialize - run + read-project-properties - - - + + ${project.parent.basedir}/utils/conf/db.properties + ${project.parent.basedir}/utils/conf/db.properties.override + + true + + + org.codehaus.mojo + sql-maven-plugin + 1.5 + - ant - ant-jsch - 1.6.5 - - - jsch - jsch - 0.1.29 + mysql + mysql-connector-java + ${cs.mysql.version} + + org.gjt.mm.mysql.Driver + jdbc:mysql://${db.cloud.host}:${db.cloud.port}/cloud + ${db.cloud.username} + ${db.cloud.password} + + ${maven.test.skip} + true + + + + create-schema + process-test-resources + + execute + + + + ${basedir}/devcloud.sql + + + + + + + + + + deploysvr + + + deploysvr + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + package + + exec + + + + + python + + ../marvin/marvin/deployDataCenter.py + -i + devcloud.cfg + + 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/src/Gemfile b/tools/devcloud/src/Gemfile new file mode 100644 index 00000000000..2790c4a52a0 --- /dev/null +++ b/tools/devcloud/src/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/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/src/deps/boxes/basebox-build/Vagrantfile b/tools/devcloud/src/deps/boxes/basebox-build/Vagrantfile new file mode 100644 index 00000000000..245692337bc --- /dev/null +++ b/tools/devcloud/src/deps/boxes/basebox-build/Vagrantfile @@ -0,0 +1,17 @@ +# 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/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/src/puppet/manifests/vagrant-devcloud.pp b/tools/devcloud/src/puppet/manifests/vagrant-devcloud.pp new file mode 100644 index 00000000000..47b07dc6dd1 --- /dev/null +++ b/tools/devcloud/src/puppet/manifests/vagrant-devcloud.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 permissions and limitations +# under the License. + +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/devcloud/veewee/README b/tools/devcloud/veewee/README deleted file mode 100644 index c9299e504b4..00000000000 --- a/tools/devcloud/veewee/README +++ /dev/null @@ -1,5 +0,0 @@ -Install DevCloud Base system: -1. get code from https://github.com/jedi4ever/veewee, and install -2. veewee vbox define devcloud ubuntu-12.04-server-i386 -3. put these two files(definition.rb and preseed.cfg) under ./definition/devcloud/ -3. veewee vbox build devcloud diff --git a/tools/git/prepare-commit-msg b/tools/git/prepare-commit-msg new file mode 100755 index 00000000000..af8964b4b28 --- /dev/null +++ b/tools/git/prepare-commit-msg @@ -0,0 +1,105 @@ +#!/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. + +# An example hook script to prepare the commit log message. +# Called by "git commit" with the name of the file that has the +# commit message, followed by the description of the commit +# message's source. The hook's purpose is to edit the commit +# message file. If the hook fails with a non-zero status, +# the commit is aborted. +# +# To enable this hook, rename this file to "prepare-commit-msg". + +# This hook includes three examples. The first comments out the +# "Conflicts:" part of a merge commit. +# +# The second includes the output of "git diff --name-status -r" +# into the message, just before the "git status" output. It is +# commented because it doesn't cope with --amend or with squashed +# commits. +# +# The third example adds a Signed-off-by line to the message, that can +# still be edited. This is rarely a good idea. + +#case "$2,$3" in +# merge,) +# /usr/bin/perl -i.bak -ne 's/^/# /, s/^# #/#/ if /^Conflicts/ .. /#/; print' "$1" ;; + +# ,|template,) +# /usr/bin/perl -i.bak -pe ' +# print "\n" . `git diff --cached --name-status -r` +# if /^#/ && $first++ == 0' "$1" ;; + +# *) ;; +#esac + +# SOB=$(git var GIT_AUTHOR_IDENT | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') +# grep -qs "^$SOB" "$1" || echo "$SOB" >> "$1" + +run_generic_commit () { +local file=$1 +cat < $file +################################# 80 chars ##################################### +# The following is an example of how to fill out the above form. Please limit +# your formatting to 80 cols. +# +# Summary: One line description of commit, followed by blank line +# +# Detail: Multi-line description, followed by blank line +# +# BUG-ID: CLOUDSTACK-9999 +# Bugfix-for: 4.0 (a branch that this should be considered for in a bugfix release) +# Reviewed-by: Bar Barlington , Foo McFooson +# Reported-by: Baz Bazelli +# Signed-off-by: You +# +$ORIGINAL +EOF + +SOB=$(git var GIT_AUTHOR_IDENT) + +sed -i "1s/^/################################# 80 chars #####################################\n\ +Summary: \n\n\ +Detail: \n\n\ +BUG-ID: \n\ +Bugfix-for: \n\ +Reviewed-by: \n\ +Reported-by: \n\ +Signed-off-by: ${SOB}\n\n/" $file + +} + +case "$2,$3" in + merge,*) + ;; + + template,*) + ;; + + message,*) + ;; + + squash,*) + ;; + + *) + run_generic_commit $1 + ;; +esac + diff --git a/tools/guest_password/cloud-set-guest-password b/tools/guest_password/cloud-set-guest-password deleted file mode 100644 index 3da0ff36191..00000000000 --- a/tools/guest_password/cloud-set-guest-password +++ /dev/null @@ -1,116 +0,0 @@ -#!/bin/bash -# -# Init file for Password Download Client -# -# chkconfig: 345 98 02 -# description: Password Download Client - -# 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. - - -# Modify this line to specify the user (default is root) -user=root - -# Add your DHCP lease folders here -DHCP_FOLDERS="/var/lib/dhclient/* /var/lib/dhcp3/* /var/lib/dhcp/*" -password_received=0 -file_count=0 -error_count=0 - -for DHCP_FILE in $DHCP_FOLDERS -do - if [ -f $DHCP_FILE ] - then - file_count=$((file_count+1)) - PASSWORD_SERVER_IP=$(grep dhcp-server-identifier $DHCP_FILE | tail -1 | awk '{print $NF}' | tr -d '\;') - - if [ -n $PASSWORD_SERVER_IP ] - then - logger -t "cloud" "Found password server IP $PASSWORD_SERVER_IP in $DHCP_FILE" - logger -t "cloud" "Sending request to password server at $PASSWORD_SERVER_IP" - password=$(wget -q -t 3 -T 20 -O - --header "DomU_Request: send_my_password" $PASSWORD_SERVER_IP:8080) - password=$(echo $password | tr -d '\r') - - if [ $? -eq 0 ] - then - logger -t "cloud" "Got response from server at $PASSWORD_SERVER_IP" - - case $password in - - "") logger -t "cloud" "Password server at $PASSWORD_SERVER_IP did not have any password for the VM" - continue - ;; - - "bad_request") logger -t "cloud" "VM sent an invalid request to password server at $PASSWORD_SERVER_IP" - error_count=$((error_count+1)) - continue - ;; - - "saved_password") logger -t "cloud" "VM has already saved a password from the password server at $PASSWORD_SERVER_IP" - continue - ;; - - *) logger -t "cloud" "VM got a valid password from server at $PASSWORD_SERVER_IP" - password_received=1 - break - ;; - - esac - else - logger -t "cloud" "Failed to send request to password server at $PASSWORD_SERVER_IP" - error_count=$((error_count+1)) - fi - else - logger -t "cloud" "Could not find password server IP in $DHCP_FILE" - error_count=$((error_count+1)) - fi - fi -done - -if [ "$password_received" == "0" ] -then - if [ "$error_count" == "$file_count" ] - then - logger -t "cloud" "Failed to get password from any server" - exit 1 - else - logger -t "cloud" "Did not need to change password." - exit 0 - fi -fi - -logger -t "cloud" "Changing password ..." -echo $user:$password | chpasswd - -if [ $? -gt 0 ] -then - usermod -p `mkpasswd -m SHA-512 $password` $user - - if [ $? -gt 0 ] - then - logger -t "cloud" "Failed to change password for user $user" - exit 1 - else - logger -t "cloud" "Successfully changed password for user $user" - fi -fi - -logger -t "cloud" "Sending acknowledgment to password server at $PASSWORD_SERVER_IP" -wget -t 3 -T 20 -O - --header "DomU_Request: saved_password" $PASSWORD_SERVER_IP:8080 -exit 0 - diff --git a/tools/marvin/DISCLAIMER.txt b/tools/marvin/DISCLAIMER.txt new file mode 100644 index 00000000000..fa1e9261a36 --- /dev/null +++ b/tools/marvin/DISCLAIMER.txt @@ -0,0 +1,7 @@ +Apache CloudStack is an effort undergoing incubation at The Apache Software Foundation (ASF), +sponsored by the Apache Incubator. Incubation is required of all newly accepted +projects until a further review indicates that the infrastructure, communications, and +decision making process have stabilized in a manner consistent with other successful ASF +projects. While incubation status is not necessarily a reflection of the completeness or +stability of the code, it does indicate that the project has yet to be fully endorsed by +the ASF. diff --git a/tools/marvin/LICENSE.txt b/tools/marvin/LICENSE.txt index 00ae6c00d2e..d9a10c0d8e8 100644 --- a/tools/marvin/LICENSE.txt +++ b/tools/marvin/LICENSE.txt @@ -1,17 +1,176 @@ -# 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. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) 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. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/tools/marvin/README b/tools/marvin/README deleted file mode 100644 index 785f078804b..00000000000 --- a/tools/marvin/README +++ /dev/null @@ -1,18 +0,0 @@ -Marvin is the testing framework for CloudStack written in python. Writing of -unittests and functional tests with Marvin makes testing with cloudstack easier - -1. INSTALL - untar Marvin-0.1.0.tar.gz - cd Marvin-0.1.0 - python setup.py install - -2. Facility it provides: - 1. very handy cloudstack API python wrapper - 2. support async job executing in parallel - 3. remote ssh login/execute command - 4. mysql query - -3. sample code is under sandbox - -4. WIKI page - https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python diff --git a/tools/marvin/marvin/TestCaseExecuteEngine.py b/tools/marvin/marvin/TestCaseExecuteEngine.py index 44a44aa141c..3c34c7efdfc 100644 --- a/tools/marvin/marvin/TestCaseExecuteEngine.py +++ b/tools/marvin/marvin/TestCaseExecuteEngine.py @@ -27,13 +27,14 @@ def testCaseLogger(message, logger=None): logger.debug(message) class TestCaseExecuteEngine(object): - def __init__(self, testclient, testcaseLogFile=None, testResultLogFile=None, format="text", xmlDir="xml-reports"): + def __init__(self, testclient, config, testcaseLogFile=None, testResultLogFile=None, format="text", xmlDir="xml-reports"): """ Initialize the testcase execution engine, just the basics here @var testcaseLogFile: client log file @var testResultLogFile: summary report file """ self.testclient = testclient + self.config = config self.logformat = logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s") self.loader = unittest.loader.TestLoader() self.suite = None @@ -83,14 +84,15 @@ class TestCaseExecuteEngine(object): #inject testclient and logger into each unittest setattr(test, "testClient", self.testclient) + 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: if self.format == "text": unittest.TextTestRunner(stream=self.testResultLogFile, verbosity=2).run(self.suite) elif self.format == "xml": - xmlrunner.XMLTestRunner(output=self.xmlDir, verbose=True).run(self.suite) + xmlrunner.XMLTestRunner(output=self.xmlDir).run(self.suite) diff --git a/tools/marvin/marvin/cloudstackConnection.py b/tools/marvin/marvin/cloudstackConnection.py index d70c192406e..e8b861eedb2 100644 --- a/tools/marvin/marvin/cloudstackConnection.py +++ b/tools/marvin/marvin/cloudstackConnection.py @@ -31,17 +31,21 @@ from cloudstackAPI import * import jsonHelper class cloudConnection(object): - def __init__(self, mgtSvr, port=8096, apiKey = None, securityKey = None, asyncTimeout=3600, logging=None): + def __init__(self, mgtSvr, port=8096, apiKey = None, securityKey = None, asyncTimeout=3600, logging=None, protocol='http', path='/client/api'): self.apiKey = apiKey self.securityKey = securityKey self.mgtSvr = mgtSvr self.port = port self.logging = logging - if port == 8096: + if protocol != 'http' and protocol != 'https': + raise ValueError("Protocol must be 'http' or 'https'.") + else: + self.protocol=protocol + self.path = path + if port == 8096 or (self.apiKey == None and self.securityKey == None): self.auth = False else: self.auth = True - self.retries = 5 self.asyncTimeout = asyncTimeout @@ -52,7 +56,7 @@ class cloudConnection(object): pass def __copy__(self): - return cloudConnection(self.mgtSvr, self.port, self.apiKey, self.securityKey, self.asyncTimeout, self.logging) + return cloudConnection(self.mgtSvr, self.port, self.apiKey, self.securityKey, self.asyncTimeout, self.logging, self.protocol, self.path) def make_request_with_auth(self, command, requests={}): requests["command"] = command @@ -68,17 +72,23 @@ class cloudConnection(object): requestUrl += "&signature=%s"%sig try: - self.connection = urllib2.urlopen("http://%s:%d/client/api?%s"%(self.mgtSvr, self.port, requestUrl)) - self.logging.debug("sending GET request: %s"%requestUrl) + self.connection = urllib2.urlopen("%s://%s:%d%s?%s"%(self.protocol, self.mgtSvr, self.port, self.path, requestUrl)) + if self.logging is not None: + self.logging.debug("sending GET request: %s"%requestUrl) response = self.connection.read() - self.logging.info("got response: %s"%response) + if self.logging is not None: + self.logging.info("got response: %s"%response) except IOError, e: if hasattr(e, 'reason'): - self.logging.critical("failed to reach %s because of %s"%(self.mgtSvr, e.reason)) + if self.logging is not None: + self.logging.critical("failed to reach %s because of %s"%(self.mgtSvr, e.reason)) elif hasattr(e, 'code'): - self.logging.critical("server returned %d error code"%e.code) + if self.logging is not None: + self.logging.critical("server returned %d error code"%e.code) + raise e except httplib.HTTPException, h: - self.logging.debug("encountered http Exception %s"%h.args) + if self.logging is not None: + self.logging.debug("encountered http Exception %s"%h.args) if self.retries > 0: self.retries = self.retries - 1 self.make_request_with_auth(command, requests) @@ -94,10 +104,12 @@ class cloudConnection(object): requests = zip(requests.keys(), requests.values()) requestUrl = "&".join(["=".join([request[0], urllib.quote_plus(str(request[1]))]) for request in requests]) - self.connection = urllib2.urlopen("http://%s:%d/client/api?%s"%(self.mgtSvr, self.port, requestUrl)) - self.logging.debug("sending GET request without auth: %s"%requestUrl) + self.connection = urllib2.urlopen("%s://%s:%d%s?%s"%(self.protocol, self.mgtSvr, self.port, self.path, requestUrl)) + if self.logging is not None: + self.logging.debug("sending GET request without auth: %s"%requestUrl) response = self.connection.read() - self.logging.info("got response: %s"%response) + if self.logging is not None: + self.logging.info("got response: %s"%response) return response def pollAsyncJob(self, jobId, response): @@ -114,7 +126,8 @@ class cloudConnection(object): return asyncResonse time.sleep(5) - self.logging.debug("job: %s still processing, will timeout in %ds"%(jobId, timeout)) + if self.logging is not None: + self.logging.debug("job: %s still processing, will timeout in %ds"%(jobId, timeout)) timeout = timeout - 5 raise cloudstackException.cloudstackAPIException("asyncquery", "Async job timeout %s"%jobId) 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/configGenerator.py b/tools/marvin/marvin/configGenerator.py index 11fbce997dd..d494beb6444 100644 --- a/tools/marvin/marvin/configGenerator.py +++ b/tools/marvin/marvin/configGenerator.py @@ -180,6 +180,17 @@ class secondaryStorage(): def __init__(self): self.url = None +class s3(): + def __init__(self): + self.accesskey = None + self.secretkey = None + self.bucket = None + self.endpoint = None + self.sockettimeout = None + self.connectiontimeout = None + self.maxerrorrety = None + self.usehttps = None + class netscaler(): def __init__(self, hostname=None, username='nsroot', password='nsroot'): self.hostname = hostname diff --git a/tools/marvin/marvin/dbConnection.py b/tools/marvin/marvin/dbConnection.py index 1992f801428..8fa86438ab0 100644 --- a/tools/marvin/marvin/dbConnection.py +++ b/tools/marvin/marvin/dbConnection.py @@ -15,59 +15,39 @@ # specific language governing permissions and limitations # under the License. -import pymysql +import mysql +import contextlib +from mysql import connector +from mysql.connector import errors +from contextlib import closing import cloudstackException import sys import os -import traceback + class dbConnection(object): def __init__(self, host="localhost", port=3306, user='cloud', passwd='cloud', db='cloud'): self.host = host self.port = port - self.user = user + self.user = str(user) #Workaround: http://bugs.mysql.com/?id=67306 self.passwd = passwd self.database = db - try: - self.db = pymysql.Connect(host=host, port=port, user=user, passwd=passwd, db=db) - except: - traceback.print_exc() - raise cloudstackException.InvalidParameterException(sys.exc_info()) - - def __copy__(self): - return dbConnection(self.host, self.port, self.user, self.passwd, self.database) - - def close(self): - try: - self.db.close() - except: - pass - - def execute(self, sql=None): + def execute(self, sql=None, params=None): if sql is None: return None - + resultRow = [] - cursor = None - try: - # commit to restart the transaction, else we don't get fresh data - self.db.commit() - cursor = self.db.cursor() - cursor.execute(sql) - - result = cursor.fetchall() - if result is not None: - for r in result: - resultRow.append(r) - return resultRow - except pymysql.MySQLError, e: - raise cloudstackException.dbException("db Exception:%s"%e) - except: - raise cloudstackException.internalError(sys.exc_info()) - finally: - if cursor is not None: - cursor.close() - + with contextlib.closing(mysql.connector.connect(host=self.host, port=self.port, user=self.user, password=self.passwd, db=self.database)) as conn: + conn.autocommit = True + with contextlib.closing(conn.cursor(buffered=True)) as cursor: + cursor.execute(sql, params) + try: + resultRow = cursor.fetchall() + except errors.InterfaceError: + #Raised on empty result - DML + resultRow = [] + return resultRow + def executeSqlFromFile(self, fileName=None): if fileName is None: raise cloudstackException.InvalidParameterException("file can't not none") diff --git a/tools/marvin/marvin/deployAndRun.py b/tools/marvin/marvin/deployAndRun.py index 1c82d9fcc2e..e7b005caf68 100644 --- a/tools/marvin/marvin/deployAndRun.py +++ b/tools/marvin/marvin/deployAndRun.py @@ -46,21 +46,30 @@ if __name__ == "__main__": else: deploy.deploy() - format = "text" + fmt = "text" xmlDir = None if options.xmlrunner is not None: xmlDir = options.xmlrunner - format = "xml" + fmt = "xml" if options.testCaseFolder is None: if options.module is None: parser.print_usage() exit(1) else: - engine = TestCaseExecuteEngine.TestCaseExecuteEngine(deploy.testClient, testCaseLogFile, testResultLogFile, format, xmlDir) + engine = \ + TestCaseExecuteEngine.TestCaseExecuteEngine(deploy.testClient, + deploy.getCfg(), + testCaseLogFile, + testResultLogFile, fmt, + xmlDir) engine.loadTestsFromFile(options.module) engine.run() else: - engine = TestCaseExecuteEngine.TestCaseExecuteEngine(deploy.testClient, testCaseLogFile, testResultLogFile, format, xmlDir) + engine = TestCaseExecuteEngine.TestCaseExecuteEngine(deploy.testClient, + deploy.getCfg(), + testCaseLogFile, + testResultLogFile, + fmt, xmlDir) engine.loadTestsFromDir(options.testCaseFolder) engine.run() diff --git a/tools/marvin/marvin/deployDataCenter.py b/tools/marvin/marvin/deployDataCenter.py index 571d5a4ff72..0d5f3bdc659 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) @@ -349,6 +349,11 @@ class deployDataCenters(): self.config.mgtSvr[0].securityKey = securityKey return apiKey, securityKey + def getCfg(self): + if self.config is not None: + return self.config + return None + def loadCfg(self): try: self.config = configGenerator.get_setup_config(self.configFile) @@ -395,8 +400,10 @@ class deployDataCenters(): """config database""" dbSvr = self.config.dbSvr - self.testClient.dbConfigure(dbSvr.dbSvr, dbSvr.port, dbSvr.user, \ - dbSvr.passwd, dbSvr.db) + if dbSvr is not None: + self.testClient.dbConfigure(dbSvr.dbSvr, dbSvr.port, dbSvr.user, \ + dbSvr.passwd, dbSvr.db) + self.apiClient = self.testClient.getApiClient() def updateConfiguration(self, globalCfg): @@ -409,11 +416,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/devcloud/devcloudbox/puppet-devcloud/init.pp b/tools/marvin/marvin/integration/__init__.py similarity index 97% rename from tools/devcloud/devcloudbox/puppet-devcloud/init.pp rename to tools/marvin/marvin/integration/__init__.py index 2574392251a..57823fcc162 100644 --- a/tools/devcloud/devcloudbox/puppet-devcloud/init.pp +++ b/tools/marvin/marvin/integration/__init__.py @@ -15,4 +15,4 @@ # specific language governing permissions and limitations # under the License. -include puppet-devcloud + diff --git a/test/integration/lib/__init__.py b/tools/marvin/marvin/integration/lib/__init__.py similarity index 100% rename from test/integration/lib/__init__.py rename to tools/marvin/marvin/integration/lib/__init__.py diff --git a/test/integration/lib/base.py b/tools/marvin/marvin/integration/lib/base.py similarity index 88% rename from test/integration/lib/base.py rename to tools/marvin/marvin/integration/lib/base.py index 5001dafb5ec..0daea5dd579 100644 --- a/test/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/test/integration/lib/common.py b/tools/marvin/marvin/integration/lib/common.py similarity index 88% rename from test/integration/lib/common.py rename to tools/marvin/marvin/integration/lib/common.py index b1c87bcf91d..69aa733420e 100644 --- a/test/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/test/integration/lib/utils.py b/tools/marvin/marvin/integration/lib/utils.py similarity index 96% rename from test/integration/lib/utils.py rename to tools/marvin/marvin/integration/lib/utils.py index 05aed798a24..cff24a1b2d5 100644 --- a/test/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/jsonHelper.py b/tools/marvin/marvin/jsonHelper.py index b2e7d2ff7dc..652cce0bf9e 100644 --- a/tools/marvin/marvin/jsonHelper.py +++ b/tools/marvin/marvin/jsonHelper.py @@ -121,7 +121,7 @@ def getResultObj(returnObj, responsecls=None): if len(returnObj) == 0: return None - responseName = returnObj.keys()[0] + responseName = filter(lambda a: a!=u'cloudstack-version', returnObj.keys())[0] response = returnObj[responseName] if len(response) == 0: diff --git a/tools/marvin/marvin/marvinPlugin.py b/tools/marvin/marvin/marvinPlugin.py index 0251e96a2bb..c52596e6d43 100644 --- a/tools/marvin/marvin/marvinPlugin.py +++ b/tools/marvin/marvin/marvinPlugin.py @@ -58,6 +58,7 @@ class MarvinPlugin(Plugin): deploy = deployDataCenter.deployDataCenters(options.config) deploy.loadCfg() if options.load else deploy.deploy() self.setClient(deploy.testClient) + self.setConfig(deploy.getCfg()) cfg = nose.config.Config() cfg.logStream = self.result_stream @@ -101,9 +102,13 @@ class MarvinPlugin(Plugin): self._injectClients(cls) def setClient(self, client): - if client: + if client is not None: self.testclient = client + def setConfig(self, config): + if config is not None: + self.config = config + def _injectClients(self, test): testcaselogger = logging.getLogger("testclient.testcase.%s" % test.__name__) self.debug_stream.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(name)s - %(message)s")) @@ -111,8 +116,9 @@ class MarvinPlugin(Plugin): testcaselogger.setLevel(logging.DEBUG) setattr(test, "testClient", self.testclient) + 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 60df2a744d7..95a9adab53f 100644 --- a/tools/marvin/marvin/remoteSSHClient.py +++ b/tools/marvin/marvin/remoteSSHClient.py @@ -18,6 +18,9 @@ import paramiko import time import cloudstackException +import contextlib +import logging +from contextlib import closing class remoteSSHClient(object): def __init__(self, host, port, user, passwd, retries = 10): @@ -27,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)) @@ -44,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 = [] @@ -55,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): @@ -67,8 +76,11 @@ class remoteSSHClient(object): except IOError, e: raise e + def close(self): + self.ssh.close() + if __name__ == "__main__": - ssh = remoteSSHClient("192.168.137.2", 22, "root", "password") - print ssh.execute("ls -l") - print ssh.execute("rm x") + with contextlib.closing(remoteSSHClient("10.223.75.10", 22, "root", + "password")) as ssh: + print ssh.execute("ls -l") diff --git a/tools/marvin/marvin/sandbox/README.txt b/tools/marvin/marvin/sandbox/README.txt deleted file mode 100644 index bb4d35e10e3..00000000000 --- a/tools/marvin/marvin/sandbox/README.txt +++ /dev/null @@ -1,30 +0,0 @@ -Welcome to the marvin sandbox ----------------------------------- - -In here you should find a few common deployment models of CloudStack that you -can configure with properties files to suit your own deployment. One deployment -model for each of - advanced zone, basic zone and a simulator demo are given. - -$ ls - -basic/ -advanced/ -simulator/ - -Each property file is divided into logical sections and should be familiar to -those who have deployed CloudStack before. Once you have your properties file -you will have to create a JSON configuration of your deployment using the -python script provided in the respective folder. - -The demo files are from the tutorial for testing with python that can be found at - https://cwiki.apache.org/confluence/display/CLOUDSTACK/Testing+with+Python - -A common deployment model of a simulator.cfg that can be used for debugging is -included. This will configure an advanced zone with simulators that can be used -for debugging purposes when you do not have hardware to debug with. - -To do this: -$ cd cloudstack-oss/ -$ ant run-simulator #This will start up the mgmt server with the simulator seeded - -## In another shell -$ ant run-simulator diff --git a/tools/marvin/marvin/sandbox/advanced/advanced_env.py b/tools/marvin/marvin/sandbox/advanced/advanced_env.py index 136629fe944..1873f31d50f 100644 --- a/tools/marvin/marvin/sandbox/advanced/advanced_env.py +++ b/tools/marvin/marvin/sandbox/advanced/advanced_env.py @@ -101,6 +101,8 @@ def describeResources(config): '''Add mgt server''' mgt = managementServer() mgt.mgtSvrIp = config.get('environment', 'mshost') + mgt.user = config.get('environment', 'mshost.user') + mgt.passwd = config.get('environment', 'mshost.passwd') zs.mgtSvr.append(mgt) '''Add a database''' diff --git a/tools/marvin/marvin/sandbox/advanced/setup.properties b/tools/marvin/marvin/sandbox/advanced/setup.properties index 966d1f9a52c..ba44d5146b6 100644 --- a/tools/marvin/marvin/sandbox/advanced/setup.properties +++ b/tools/marvin/marvin/sandbox/advanced/setup.properties @@ -36,6 +36,8 @@ secstorage.allowed.internal.sites=10.147.28.0/24 [environment] dns=10.147.28.6 mshost=10.147.29.111 +mshost.user=root +mshost.passwd=password mysql.host=10.147.29.111 mysql.cloud.user=cloud mysql.cloud.passwd=cloud diff --git a/tools/marvin/marvin/sandbox/basic/basic_env.py b/tools/marvin/marvin/sandbox/basic/basic_env.py index 7c2a0b1d957..e588fdcc882 100644 --- a/tools/marvin/marvin/sandbox/basic/basic_env.py +++ b/tools/marvin/marvin/sandbox/basic/basic_env.py @@ -102,6 +102,8 @@ def describeResources(config): '''Add mgt server''' mgt = managementServer() mgt.mgtSvrIp = config.get('environment', 'mshost') + mgt.user = config.get('environment', 'mshost.user') + mgt.passwd = config.get('environment', 'mshost.passwd') zs.mgtSvr.append(mgt) '''Add a database''' diff --git a/tools/marvin/marvin/sandbox/basic/setup.properties b/tools/marvin/marvin/sandbox/basic/setup.properties index e9c0f4d70e3..8833b507252 100644 --- a/tools/marvin/marvin/sandbox/basic/setup.properties +++ b/tools/marvin/marvin/sandbox/basic/setup.properties @@ -36,6 +36,8 @@ secstorage.allowed.internal.sites=10.147.28.0/24 [environment] dns=10.147.28.6 mshost=10.147.39.69 +mshost.user=root +mshost.passwd=password mysql.host=10.147.39.69 mysql.cloud.user=cloud mysql.cloud.passwd=cloud diff --git a/tools/marvin/marvin/sandbox/demo/live/README b/tools/marvin/marvin/sandbox/demo/live/README deleted file mode 100644 index 8ca0f4cf763..00000000000 --- a/tools/marvin/marvin/sandbox/demo/live/README +++ /dev/null @@ -1,8 +0,0 @@ - -Download Marvin source from hudson - -Install Marvin: -pip install Marvin-0.1.0.tar.gz - -To Run the test: -python -m marvin.deployAndRun -c demo.cfg -t /tmp/t.log -r /tmp/r.log -f testSshDeployVM.py -l diff --git a/tools/marvin/marvin/sandbox/demo/simulator/README b/tools/marvin/marvin/sandbox/demo/simulator/README deleted file mode 100644 index d34ca9f80ec..00000000000 --- a/tools/marvin/marvin/sandbox/demo/simulator/README +++ /dev/null @@ -1,12 +0,0 @@ -To generate the config -Alter the .properties file to point to your simulator installed environment - -python simulator_setup.py -i simulatordemo.properties -o simulatordemo.cfg - - -To deploy the environment and run the tests - -python -m marvin.deployAndRun -c simulatordemo.cfg -t /tmp/t.log -r /tmp/r.log -d testcase - - - diff --git a/tools/marvin/marvin/sandbox/demo/simulator/simulator.cfg b/tools/marvin/marvin/sandbox/demo/simulator/simulator.cfg index 7d250c84ec0..7c733ade256 100644 --- a/tools/marvin/marvin/sandbox/demo/simulator/simulator.cfg +++ b/tools/marvin/marvin/sandbox/demo/simulator/simulator.cfg @@ -16,7 +16,6 @@ # under the License. - { "zones": [ { @@ -149,10 +148,6 @@ "name": "workers", "value": "10" }, - { - "name": "use.user.concentrated.pod.allocation", - "value": "false" - }, { "name": "account.cleanup.interval", "value": "600" @@ -193,6 +188,8 @@ "mgtSvr": [ { "mgtSvrIp": "localhost", + "passwd": "password", + "user": "root", "port": 8096 } ] diff --git a/tools/marvin/marvin/sandbox/demo/simulator/simulator_setup.py b/tools/marvin/marvin/sandbox/demo/simulator/simulator_setup.py index 2bd52f14345..0d341408aea 100644 --- a/tools/marvin/marvin/sandbox/demo/simulator/simulator_setup.py +++ b/tools/marvin/marvin/sandbox/demo/simulator/simulator_setup.py @@ -103,6 +103,8 @@ def describeResources(config): '''Add mgt server''' mgt = managementServer() mgt.mgtSvrIp = config.get('environment', 'mshost') + mgt.user = config.get('environment', 'mshost.user') + mgt.passwd = config.get('environment', 'mshost.passwd') zs.mgtSvr.append(mgt) '''Add a database''' diff --git a/tools/marvin/marvin/sandbox/demo/simulator/simulatordemo.properties b/tools/marvin/marvin/sandbox/demo/simulator/simulatordemo.properties index aa3deb0afa1..9d9f14b70a4 100644 --- a/tools/marvin/marvin/sandbox/demo/simulator/simulatordemo.properties +++ b/tools/marvin/marvin/sandbox/demo/simulator/simulatordemo.properties @@ -37,6 +37,8 @@ secstorage.allowed.internal.sites=10.147.28.0/24 [environment] dns=10.147.28.6 mshost=localhost +mshost.user=root +mshost.passwd=password mysql.host=localhost mysql.cloud.user=cloud mysql.cloud.passwd=cloud diff --git a/tools/marvin/marvin/settings.py b/tools/marvin/marvin/settings.py new file mode 100644 index 00000000000..30b78ac1522 --- /dev/null +++ b/tools/marvin/marvin/settings.py @@ -0,0 +1,28 @@ +# 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. + +# Settings for the XML test runner + +# Use this setting to choose between a verbose and a non-verbose output. +TEST_OUTPUT_VERBOSE = 2. + +# If your test methods contains docstrings, you can display such docstrings +# instead of display the test name (ex: module.TestCase.test_method). In order to +# use this feature, you have to enable verbose output by setting +# TEST_OUTPUT_VERBOSE = 2. + +TEST_OUTPUT_DESCRIPTIONS=True 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/pom.xml b/tools/marvin/pom.xml new file mode 100644 index 00000000000..51c70cd92b8 --- /dev/null +++ b/tools/marvin/pom.xml @@ -0,0 +1,100 @@ + + + 4.0.0 + cloud-marvin + Apache CloudStack Developer Tools: marvin + pom + + org.apache.cloudstack + cloudstack + 4.1.0-SNAPSHOT + ../../pom.xml + + + + install + + + maven-antrun-plugin + 1.7 + + + generate-resource + generate-resources + + run + + + + + + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + compile + compile + + exec + + + marvin + python + + codegenerator.py + -s + ${basedir}/../apidoc/target/commands.xml + + + + + package + package + + exec + + + ${exec.workingdir} + python + + setup.py + sdist + + + + + deploy + deploy + + exec + + + dist + pip + + install + Marvin-0.1.0.tar.gz + + + + + + + + diff --git a/tools/marvin/setup.py b/tools/marvin/setup.py index c9841f31f3b..fea53d07f8a 100644 --- a/tools/marvin/setup.py +++ b/tools/marvin/setup.py @@ -16,14 +16,10 @@ # specific language governing permissions and limitations # under the License. -from distutils.core import setup +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", @@ -34,12 +30,14 @@ setup(name="Marvin", long_description="Marvin is the cloudstack testclient written around the python unittest framework", platforms=("Any",), url="http://jenkins.cloudstack.org:8080/job/marvin", - packages=["marvin", "marvin.cloudstackAPI", "marvin.sandbox", "marvin.sandbox.advanced", "marvin.sandbox.basic"], + packages=["marvin", "marvin.cloudstackAPI", "marvin.integration", + "marvin.integration.lib", "marvin.sandbox", + "marvin.sandbox.advanced", "marvin.sandbox.basic"], license="LICENSE.txt", install_requires=[ - "pymysql", + "mysql-connector-python", "paramiko", "nose", - "unittest-xml-reporting" + "unittest-xml-reporting>1.2" ], ) diff --git a/tools/whisker/descriptor.xml b/tools/whisker/descriptor.xml index 007535def5c..a94d60b612e 100644 --- a/tools/whisker/descriptor.xml +++ b/tools/whisker/descriptor.xml @@ -2250,7 +2250,17 @@ The Apache Software Foundation (http://www.apache.org/). Please read the different LICENSE files present in the lib directory of this distribution. - + + +Apache WebServices - WSS4J +Copyright 2004-2011 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). + +This product includes software Copyright University of Southampton IT +Innovation Centre, 2006 (http://www.it-innovation.soton.ac.uk). + + + +Copyright (c) 2006 Google Inc. + + + + + Copyright (c) 2011, John Resig @@ -2616,6 +2634,29 @@ Copyright (c) 2004 Clinton Begin + + + +Copyright (c) 2010-2011 OpenStack, LLC. + + + + + + + + + +Copyright (c) 2010-2011 OpenStack, LLC. + + + + + + + + + @@ -2771,26 +2812,6 @@ All rights reserved. - - - -Copyright (c) 2010-2011 OpenStack, LLC. - - - - - - - - - -Copyright (c) 2010-2011 OpenStack, LLC. - - - - - - @@ -2824,6 +2845,7 @@ Copyright (c) 2004-2012 The Apache Software Foundation + @@ -2848,6 +2870,7 @@ Copyright (c) 2004-2012 The Apache Software Foundation + diff --git a/ui/css/cloudstack3-ie7.css b/ui/css/cloudstack3-ie7.css index 90b823a4c0a..114e9c01edc 100644 --- a/ui/css/cloudstack3-ie7.css +++ b/ui/css/cloudstack3-ie7.css @@ -32,12 +32,13 @@ div.toolbar div.text-search div.search-bar input { float: left; border: none; margin-top: -1px; - margin-right:0px; - margin-bottom:0px; - margin-left:-12px; + margin-right: 0px; + margin-bottom: 0px; + margin-left: -12px; width: 97%; height: 67%; } + div.panel div.list-view div.fixed-header { top: expression(this.offsetParent.scrollTop + 30); } @@ -162,3 +163,47 @@ table th { top: 5px; } +.quick-view-tooltip div.title > span.title { +} + +.quick-view-tooltip div.title .icon { + top: -15px; +} + +.quick-view-tooltip table { +} + +.quick-view-tooltip .main-groups { + float: left; + left: 0px; + margin-top: 7px; +} + +.quick-view-tooltip .actions { + width: 426px !important; + float: left; +} + +.quick-view-tooltip .action { + float: left !important; + width: 54px !important; + margin-left: 7px !important; +} + +.quick-view-tooltip .action .label { + float: left; + max-width: 20px; +} + +.quick-view-tooltip .action .icon { + float: left; + height: 7px; + left: 0px; +} + +.list-view td.quick-view { +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text { + filter:alpha(opacity=100); +} diff --git a/ui/css/cloudstack3.css b/ui/css/cloudstack3.css index 19b0aee4794..e1c9c86a04f 100644 --- a/ui/css/cloudstack3.css +++ b/ui/css/cloudstack3.css @@ -1,3 +1,4 @@ +/*[fmt]1C20-1C0D-E*/ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -16,7 +17,6 @@ * specific language governing permissions and limitations * under the License. */ -/*[fmt]1C20-1C0D-E*/ /*+clearfix {*/ div.toolbar:after, .multi-wizard .progress ul li:after, @@ -62,9 +62,8 @@ body.install-wizard { #container { width: 1024px; - height: 768px; + height: 783px; margin: auto; - overflow: hidden; border: 1px solid #E2E2E2; border-top: none; position: relative; @@ -74,6 +73,7 @@ body.install-wizard { display: none; } +/*Table*/ table { width: 740px; max-width: 777px; @@ -140,10 +140,11 @@ table tbody td.loading { border-top: 1px solid #FBFBFB; } +/** Actions table cell*/ table tbody td.actions { - width: 155px; - max-width: 155px !important; - min-width: 155px !important; + width: 130px; + max-width: 130px !important; + min-width: 130px !important; vertical-align: middle; } @@ -155,6 +156,44 @@ table tbody td.actions input { margin: 11px 0 0px; } +/** Quick view table cell*/ +table tbody td.quick-view, +table thead th.quick-view { + min-width: 58px; + max-width: 58px !important; + width: 58px !important; + height: 14px !important; + text-indent: 7px; +} + +table tbody td.quick-view { + cursor: pointer; +} + +table tbody td.quick-view .icon { + margin-left: 22px; + margin-top: 3px; + padding: 0px 0px 6px 12px; + background: url(../images/sprites.png) no-repeat -44px -62px; +} + +table tbody td.quick-view:hover .icon { + background-position: -44px -644px; +} + +table tbody tr.loading td.quick-view .icon { + display: none; +} + +table tbody tr.loading td.quick-view { + cursor: default; +} + +table tbody tr.loading td.quick-view .loading { + background-position: center center; +} + +/** Row styling*/ table tbody tr { border-left: 1px solid #C4C5C5; border-right: 1px solid #C4C5C5; @@ -220,6 +259,7 @@ table th div.ui-resizable-handle { float: right; } +/** Header, misc*/ #header, #navigation { /*+text-shadow:0px -1px 1px #000000;*/ @@ -401,13 +441,20 @@ body.login { div.list-view table tbody td span { display: block; float: left; - max-width: 210px; + max-width: 160px; word-wrap: break-word; text-indent: 0; margin-left: 12px; line-height: 15px; - overflow: auto; + overflow: hidden; overflow-x: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +div.list-view table tbody td span:hover { + overflow: auto; + margin-top: 4px; } div.list-view div.toolbar div.section-switcher div.section-select label { @@ -616,44 +663,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; @@ -1153,7 +1168,7 @@ div.notification.corner-alert:hover div.message span { div.panel div.list-view { overflow: auto; overflow-x: hidden; - height: 652px; + height: 668px; margin-top: 30px; border-bottom: 1px solid #E7E7E7; } @@ -1229,7 +1244,9 @@ div.panel div.list-view div.fixed-header table { } div.list-view td.state { - width: 129px; + width: 120px; + min-width: 120px; + max-width: 120px; } div.list-view td.first { @@ -1241,7 +1258,7 @@ div.list-view td.first:hover { } div.list-view td.state span { - padding: 0 0 0 26px; + padding: 1px 0 0 18px; text-align: center; width: 80px; /*+text-shadow:0px 1px 1px #FFFFFF;*/ @@ -1266,6 +1283,242 @@ div.list-view td.state.off span { background-position: 1px -496px; } +/** Quick view tooltip*/ +.quick-view-tooltip { + width: 400px; + display: inline-block; + margin-left: -359px; + padding-top: 50px; +} + +.quick-view-tooltip > div.title { + width: 376px; + position: absolute; + top: 71px; + left: 10px; + color: #5A6977; + /*+text-shadow:0px 1px #EAEAEA;*/ + -moz-text-shadow: 0px 1px #EAEAEA; + -webkit-text-shadow: 0px 1px #EAEAEA; + -o-text-shadow: 0px 1px #EAEAEA; + text-shadow: 0px 1px #EAEAEA; +} + +.quick-view-tooltip > div.title .icon { + position: relative; + top: -3px; + background: url(../images/sprites.png) no-repeat -42px -67px; + float: right; + padding: 5px 21px 0 1px; +} + +.quick-view-tooltip .loading-overlay { + top: 94px; + height: 57px; + left: 1px; + /*+opacity:35%;*/ + filter: alpha(opacity=35); + -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=35); + -moz-opacity: 0.35; + opacity: 0.35; +} + +.quick-view-tooltip > div.title span.title { +} + +.quick-view-tooltip .container { + border: 1px solid #9EA2A5; + background: #CCCFD6; + width: 400px; + min-height: 100px; + height: auto; + overflow: hidden; + display: inline-block; + /*+box-shadow:0px 7px 9px #676F76;*/ + -moz-box-shadow: 0px 7px 9px #676F76; + -webkit-box-shadow: 0px 7px 9px #676F76; + -o-box-shadow: 0px 7px 9px #676F76; + box-shadow: 0px 7px 9px #676F76; +} + +/*** Quick view detail view*/ +.quick-view-tooltip .detail-view { +} + +.quick-view-tooltip .detail-view .main-groups { + width: 394px; + height: 132px; + position: absolute; + top: 55px; + padding-top: 7px; + border: 1px solid #808080; + border-left: none; + border-right: none; + overflow: hidden; + /*+box-shadow:0px 1px #E6E6E6;*/ + -moz-box-shadow: 0px 1px #E6E6E6; + -webkit-box-shadow: 0px 1px #E6E6E6; + -o-box-shadow: 0px 1px #E6E6E6; + box-shadow: 0px 1px #E6E6E6; +} + +.quick-view-tooltip .detail-view .actions { +} + +.quick-view-tooltip .detail-view .tagger { + display: none; +} + +.quick-view-tooltip .detail-view ul { + display: none !important; +} + +.quick-view-tooltip .detail-view .ui-tabs-panel { + display: inline-block; + width: 100% !important; + float: left; + height: auto; + overflow: hidden; +} + +.quick-view-tooltip .detail-view .details { + display: inline-block; + height: auto; + padding-bottom: 209px; +} + +.quick-view-tooltip .detail-view .detail-group { + width: 365px; + margin: 0; + padding: 0; + left: -9px; + background: none; + border: none; +} + +.quick-view-tooltip .detail-view .detail-group table { + margin: 0; + border: none; + background: none; +} + +.quick-view-tooltip .detail-view .detail-group table tr { + background: none; +} + +.quick-view-tooltip .detail-view .detail-group table td.name { + color: #3E5F7F !important; + padding: 0px 29px 0px 5px !important; + font-size: 13px; + /*+text-shadow:0px 1px #DBDBDB;*/ + -moz-text-shadow: 0px 1px #DBDBDB; + -webkit-text-shadow: 0px 1px #DBDBDB; + -o-text-shadow: 0px 1px #DBDBDB; + text-shadow: 0px 1px #DBDBDB; +} + +.quick-view-tooltip .detail-view .detail-group table td.value { + font-size: 12px; + /*+text-shadow:0px 1px #EAEAEA;*/ + -moz-text-shadow: 0px 1px #EAEAEA; + -webkit-text-shadow: 0px 1px #EAEAEA; + -o-text-shadow: 0px 1px #EAEAEA; + text-shadow: 0px 1px #EAEAEA; + overflow: hidden; +} + +.quick-view-tooltip .detail-view .detail-group table td.value input[type=text] { + width: 258px; + height: 10px; + margin-left: 0px; +} + +.quick-view-tooltip .detail-view .detail-group .main-groups table td.value span { + height: 25px; + top: 0px; +} + +.quick-view-tooltip .detail-view .detail-group.actions { + position: relative; + top: 202px; + float: left; + width: 100%; + height: auto; +} + +.quick-view-tooltip .detail-view .detail-group.actions .button { + top: 160px; +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text { + width: 112px; + height: 41px; + background: none; + border: none; + float: left; + margin-left: 5px; + display: inline-block; +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text:hover { + /*+box-shadow:none;*/ + -moz-box-shadow: none; + -webkit-box-shadow: none; + -o-box-shadow: none; + box-shadow: none; +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text .icon { + display: block; + float: left; + width: 4px; +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text .label { + width: 81px; + display: block; + float: right; + font-size: 11px; + color: #454C53; + /*+text-shadow:0px 1px #FFFFFF;*/ + -moz-text-shadow: 0px 1px #FFFFFF; + -webkit-text-shadow: 0px 1px #FFFFFF; + -o-text-shadow: 0px 1px #FFFFFF; + text-shadow: 0px 1px #FFFFFF; + text-indent: 0px; +} + +.quick-view-tooltip .detail-view .detail-group.actions .action.text:hover .label { + color: #000000; +} + +.quick-view-tooltip .detail-view .detail-group.actions .detail-actions { + width: 400px; + height: auto; + background: none; + vertical-align: top; + float: left; +} + +.quick-view-tooltip .detail-view .detail-group.actions td.view-all { + position: relative; + left: 0px; + float: left; + width: 394px; + height: 22px; + border-top: 1px solid #808080; + /*+box-shadow:inset 0px 1px #FFFFFF;*/ + -moz-box-shadow: inset 0px 1px #FFFFFF; + -webkit-box-shadow: inset 0px 1px #FFFFFF; + -o-box-shadow: inset 0px 1px #FFFFFF; + box-shadow: inset 0px 1px #FFFFFF; +} + +.quick-view-tooltip .detail-view .detail-actions a { + background: none; + width: 30px; +} + /*Details page*/ .detail-view { padding: 0 0 0 14px; @@ -1794,15 +2047,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; @@ -1818,7 +2062,6 @@ div.detail-group.actions td { float: right; margin-top: 8px; display: inline-block; - background: url(../images/citrix-logo-darkbg.png) no-repeat 97% 8px; padding: 0 96px 0 0; } @@ -2168,6 +2411,13 @@ div.detail-group.actions td { overflow: hidden; } +#browser.panel-highlight { + overflow: visible; +} + +#browser.panel-highlight .panel { +} + #browser div.panel { height: 698px; background: #F7F7F7; @@ -2175,6 +2425,35 @@ div.detail-group.actions td { overflow: visible; } +#browser div.panel.panel-highlight-wrapper { + display: inline-block; + background: none; + /*+border-radius:9px;*/ + -moz-border-radius: 9px; + -webkit-border-radius: 9px; + -khtml-border-radius: 9px; + border-radius: 9px; + margin-top: 7px; + /*+box-shadow:0px 0px 12px #000000;*/ + -moz-box-shadow: 0px 0px 12px #000000; + -webkit-box-shadow: 0px 0px 12px #000000; + -o-box-shadow: 0px 0px 12px #000000; + box-shadow: 0px 0px 12px #000000; + border: 3px solid #FFFFFF; + height: 542px; + overflow: hidden; + position: absolute; + z-index: 10000; + padding: 78px 0px 67px 51px; +} + +#browser div.panel.panel-highlight-wrapper .panel { + left: 20px !important; + height: 631px; + overflow: hidden; + top: 3px; +} + .project-view #browser div.panel { background: #6D747D; } @@ -2197,6 +2476,38 @@ div.detail-group.actions td { background: url(../images/bg-panel-shadow.png) repeat-y 0px 0px; } +#browser.panel-highlight { + overflow: visible; +} + +#browser.panel-highlight .panel.highlighted { + /*+box-shadow:0px 10px 11px #5C5C5C;*/ + -moz-box-shadow: 0px 10px 11px #5C5C5C; + -webkit-box-shadow: 0px 10px 11px #5C5C5C; + -o-box-shadow: 0px 10px 11px #5C5C5C; + box-shadow: 0px 10px 11px #5C5C5C; + border: 5px solid #FFFFFF; + /*+border-radius:6px;*/ + -moz-border-radius: 6px; + -webkit-border-radius: 6px; + -khtml-border-radius: 6px; + border-radius: 6px; + margin-top: 21px; +} + +#browser.panel-highlight .panel > .shadow { + display: none; +} + +#browser .highlight-arrow { + width: 24px; + height: 19px; + background: url(../images/sprites.png) -590px -1295px; + position: absolute; + top: -22px; + left: 80px; +} + /*Toolbar*/ /*[clearfix]*/div.toolbar { width: 793px; @@ -2266,6 +2577,7 @@ div.toolbar div.filters select { div.toolbar div.text-search { float: right; + position: relative; } div.toolbar div.text-search div.search-bar { @@ -2400,6 +2712,137 @@ div.toolbar div.button.add span { border-right: 1px solid #43586B; } +/*** Advanced search*/ +#advanced_search { + width: 15px; + position: absolute; + left: 139px; + top: 4px; + z-index: 4; + background: none; +} + +#advanced_search .icon { + /*+opacity:56%;*/ + filter: alpha(opacity=56); + -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=56); + -moz-opacity: 0.56; + opacity: 0.56; + background: url(../images/sprites.png) no-repeat -62px -162px; + padding: 10px; + position: absolute; + top: 1px; + left: -1px; + z-index: 10; +} + +#advanced_search:hover .icon { + /*+opacity:100%;*/ + filter: alpha(opacity=100); + -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); + -moz-opacity: 1; + opacity: 1; +} + +#advanced_search .form-container { + /*+opacity:91%;*/ + filter: alpha(opacity=91); + -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=91); + -moz-opacity: 0.91; + opacity: 0.91; + /*+box-shadow:0px 5px 9px #B6B0B0;*/ + -moz-box-shadow: 0px 5px 9px #B6B0B0; + -webkit-box-shadow: 0px 5px 9px #B6B0B0; + -o-box-shadow: 0px 5px 9px #B6B0B0; + box-shadow: 0px 5px 9px #B6B0B0; + border: 1px solid #808080; + /*+border-radius:0 0 4px 4px;*/ + -moz-border-radius: 0 0 4px 4px; + -webkit-border-radius: 0 0 4px 4px; + -khtml-border-radius: 0 0 4px 4px; + border-radius: 0 0 4px 4px; + left: -290px; + top: 2px; + position: absolute; + display: inline-block; + background: #FFFFFF; + padding: 18px; + cursor: default; +} + +#advanced_search .form-container .name { + width: 66px; + float: left; +} + +#advanced_search .form-container .value { + width: 186px; + float: left; +} + +#advanced_search .form-container .form-item { + width: 268px; + height: 40px; + margin-bottom: 15px; +} + +#advanced_search .form-container .form-item input, +#advanced_search .form-container .form-item select { + width: 97%; + padding: 3px; +} + +#advanced_search input[type=submit] { + float: right; + background: url(../images/bg-gradients.png) 0px -220px; + /*+box-shadow:0px 2px 5px #858585;*/ + -moz-box-shadow: 0px 2px 5px #858585; + -webkit-box-shadow: 0px 2px 5px #858585; + -o-box-shadow: 0px 2px 5px #858585; + box-shadow: 0px 2px 5px #858585; + border: 1px solid #606060; + border-top: none; + color: #FFFFFF; + font-size: 12px; + font-weight: bold; + /*+text-shadow:0px 1px 1px #000000;*/ + -moz-text-shadow: 0px 1px 1px #000000; + -webkit-text-shadow: 0px 1px 1px #000000; + -o-text-shadow: 0px 1px 1px #000000; + text-shadow: 0px 1px 1px #000000; + /*+border-radius:4px;*/ + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -khtml-border-radius: 4px; + border-radius: 4px; + cursor: pointer; + padding: 8px 20px; +} + +#advanced_search input[type=submit]:hover { + /*+box-shadow:inset 0px 2px 3px #000000;*/ + -moz-box-shadow: inset 0px 2px 3px #000000; + -webkit-box-shadow: inset 0px 2px 3px #000000; + -o-box-shadow: inset 0px 2px 3px #000000; + box-shadow: inset 0px 2px 3px #000000; +} + +#advanced_search .button.cancel { + background: url(noen); + color: #9A9A9A; + font-size: 12px; + float: right; + /*+placement:shift -32px 13px;*/ + position: relative; + left: -32px; + top: 13px; + font-weight: bold; +} + +#advanced_search .button.cancel:hover { + color: #494949; +} + /*** Panel controls*/ #browser div.panel div.toolbar div.panel-controls { float: right; @@ -2444,7 +2887,7 @@ div.toolbar div.button.add span { } /*** Section switcher*/ -div.list-view div.toolbar div.section-switcher { +div.panel div.toolbar div.section-switcher { margin-top: 6px; margin-left: 10px; float: left; @@ -2454,12 +2897,12 @@ div.list-view div.toolbar div.section-switcher { display: none; } -div.list-view div.toolbar div.section-switcher div.section-select { +div.toolbar div.section-switcher div.section-select { float: right; background: #A8AFB6; } -div.list-view div.toolbar div.section-switcher div.section { +div.toolbar div.section-switcher div.section { float: left; font-size: 11px; font-weight: bold; @@ -2476,7 +2919,7 @@ div.list-view div.toolbar div.section-switcher div.section { text-shadow: 0px 1px 1px #EDEDED; } -div.list-view div.toolbar div.section-switcher div.section a { +div.toolbar div.section-switcher div.section a { background: url(../images/bg-section-switcher.png) repeat-x 0px -22px; text-decoration: none; display: block; @@ -2485,7 +2928,7 @@ div.list-view div.toolbar div.section-switcher div.section a { border: 1px solid #979FA4; } -div.list-view div.toolbar div.section-switcher div.section a.active { +div.toolbar div.section-switcher div.section a.active { background: url(../images/bg-section-switcher.png) repeat-x 0px -21px; background-position: 0px 0px; border: none; @@ -2499,7 +2942,7 @@ div.list-view div.toolbar div.section-switcher div.section a.active { box-shadow: inset 0px 1px 5px #546874; } -div.list-view div.toolbar div.section-switcher div.section.first a { +div.toolbar div.section-switcher div.section.first a { /*+border-radius:4px 0 0 5px;*/ -moz-border-radius: 4px 0 0 5px; -webkit-border-radius: 4px 0 0 5px; @@ -2507,7 +2950,7 @@ div.list-view div.toolbar div.section-switcher div.section.first a { border-radius: 4px 0 0 5px; } -div.list-view div.toolbar div.section-switcher div.section.last a { +div.toolbar div.section-switcher div.section.last a { /*+border-radius:0 4px 4px 0px;*/ -moz-border-radius: 0 4px 4px 0px; -webkit-border-radius: 0 4px 4px 0px; @@ -2515,7 +2958,7 @@ div.list-view div.toolbar div.section-switcher div.section.last a { border-radius: 0 4px 4px 0px; } -div.list-view div.toolbar div.section-switcher div.section.first.last a { +div.toolbar div.section-switcher div.section.first.last a { /*+border-radius:5px;*/ -moz-border-radius: 5px; -webkit-border-radius: 5px; @@ -2524,17 +2967,17 @@ div.list-view div.toolbar div.section-switcher div.section.first.last a { border-radius: 5px 5px 5px 5px; } -div.list-view div.toolbar div.section-switcher div.section-select { +div.toolbar div.section-switcher div.section-select { float: left; background: #A8AFB6; height: 26px; } -.project-view div.list-view div.toolbar div.section-switcher div.section-select { +.project-view div.toolbar div.section-switcher div.section-select { background: transparent; } -div.list-view div.toolbar div.section-switcher div.section-select select { +div.toolbar div.section-switcher div.section-select select { width: 142px; height: 21px; margin-right: 13px; @@ -2548,7 +2991,7 @@ div.list-view div.toolbar div.section-switcher div.section-select select { border-radius: 4px 4px 4px 4px; } -div.list-view div.toolbar div.section-switcher div.section-select label { +div.toolbar div.section-switcher div.section-select label { margin: 0 9px 0 0; } @@ -2844,7 +3287,7 @@ table td.actions span { table td.actions .action span.icon { background-image: url(../images/sprites.png); cursor: pointer; - width: 28px; + width: 23px; height: 21px; float: left; } @@ -2986,7 +3429,6 @@ Dialogs*/ display: inline; padding: 0; float: right; - text-decoration: underline; color: #516374; /*+text-shadow:0px -1px 1px #FFFFFF;*/ -moz-text-shadow: 0px -1px 1px #FFFFFF; @@ -3083,6 +3525,11 @@ Dialogs*/ -webkit-text-shadow: 0px -1px 1px #495968; -o-text-shadow: 0px -1px 1px #495968; text-shadow: 0px -1px 1px #495968; + background: url(../images/icons.png) no-repeat 0px -255px; +} + +.notice .ui-dialog-title { + background-position: 0px -288px; } .ui-dialog.confirm .ui-dialog-title { @@ -5828,23 +6275,53 @@ label.error { .multi-wizard.zone-wizard .select-network-model .select-area { height: 181px; width: 586px; + position: relative; +} + +.multi-wizard.zone-wizard .select-network-model .select-area.basic-zone { + height: 105px; +} + +.multi-wizard.zone-wizard .select-network-model .select-area.advanced-zone { + height: 233px; } .multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode { - height: 169px; + height: 98px; overflow: hidden; float: left; margin: 5px 0 0; -/*Hide isolation mode (always defaults to VLAN)*/ - display: none; + position: absolute; + top: 114px; + left: 9px; +} + +.multi-wizard.zone-wizard .select-network-model .select-area.disabled .isolation-mode { + /*+opacity:50%;*/ + filter: alpha(opacity=50); + -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); + -moz-opacity: 0.5; + opacity: 0.5; +} + +.multi-wizard.zone-wizard .select-network-model .select-area.disabled .isolation-mode input { +} + +.multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .title { + font-size: 15px; + color: #5D7387; + /*+placement:shift 36px 2px;*/ + position: relative; + left: 36px; + top: 2px; } .multi-wizard.zone-wizard .select-network-model .select-area .desc { width: 373px; - height: 120px; + height: 62px; color: #727272; background: #EFEFEF; - padding: 18px; + padding: 12px 18px 25px; /*+placement:shift -27px 12px;*/ position: relative; left: -27px; @@ -5858,6 +6335,10 @@ label.error { line-height: 19px; } +.multi-wizard.zone-wizard .select-network-model .select-area.basic-zone .desc { + padding-bottom: 4px; +} + .multi-wizard.zone-wizard .select-network-model .select-area .desc em { font-weight: bold; text-decoration: underline; @@ -5865,31 +6346,39 @@ label.error { .multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .select-area { width: 586px; - height: 41px; + height: 31px; overflow: hidden; margin: 0; padding: 0px 0 9px; + background: none; } .multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .select-area label { font-size: 11px; - margin: 18px 0 0 11px; + margin: 24px 0 0 2px; } .multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .select-area input { - margin: 17px 0 0 39px; + margin: 26px 0 11px; +} + +.multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .select-area input { + margin: 24px 8px 0 36px !important; + padding: 0 !important; } .multi-wizard.zone-wizard .select-network-model .select-area .isolation-mode .select-area .desc { - padding: 7px; + padding: 6px 7px 11px; width: 388px; + height: 9px; font-size: 11px; - background: #E6E6E6; + margin-right: 9px; + background: #EFEFEF; float: right; - /*+placement:shift -27px 11px;*/ + /*+placement:shift -27px 12px;*/ position: relative; left: -27px; - top: 11px; + top: 12px; } .multi-wizard.zone-wizard .content.input-area { @@ -5978,7 +6467,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;*/ @@ -6018,10 +6507,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*/ @@ -6249,20 +6738,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 { @@ -6275,10 +6764,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 { @@ -6299,6 +6788,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; @@ -6339,6 +6858,12 @@ label.error { width: 98%; } +.multi-wizard.zone-wizard .multi-edit table th, +.multi-wizard.zone-wizard .multi-edit table td { + min-width: 97px; + max-width: 97px; +} + .multi-wizard.zone-wizard .multi-edit .data { width: 102%; float: left; @@ -6692,6 +7217,25 @@ div.panel.ui-dialog div.list-view div.fixed-header { } /*Multi-edit*/ +div.container div.panel div#details-tab-addloadBalancer.detail-group div.loadBalancer div.multi-edit form table.multi-edit thead tr th, +div.container div.panel div#details-tab-addloadBalancer.detail-group div.loadBalancer div.multi-edit form table.multi-edit tbody tr td { + min-width: 100px; +} + +div.ui-dialog div.multi-edit-add-list div.view div.data-table table.body tbody tr.even td { + border-right: 1px solid #BFBFBF; + clear: none; + color: #495A76; + font-size: 10px; + margin-right: 25px; + min-width: -moz-available; + max-width: 90px; + overflow: hidden; + padding: 9px 5px 8px 0; + position: relative; + vertical-align: middle; +} + .multi-edit { } @@ -6704,6 +7248,10 @@ div.panel.ui-dialog div.list-view div.fixed-header { border-top: none; } +.multi-edit table th { + min-width: 88px; +} + .detail-group .multi-edit table td { border-left: 1px solid #CDCCCC; } @@ -6712,6 +7260,11 @@ div.panel.ui-dialog div.list-view div.fixed-header { width: 70%; } +.detail-view .multi-edit select { + width: 93%; + font-size: 10px; +} + .multi-edit input { width: 85%; } @@ -6725,9 +7278,10 @@ div.panel.ui-dialog div.list-view div.fixed-header { } .multi-edit .range input { - width: 70px; + width: 41px; margin-left: 13px; position: relative; + float: left; } .multi-edit .range label { @@ -6789,8 +7343,9 @@ div.panel.ui-dialog div.list-view div.fixed-header { border-radius: 5px; border-radius: 5px 5px 5px 5px; width: 74px; + text-indent: 0px; text-align: center; - padding: 6px 9px 4px 0px; + padding: 6px 0px 4px; background: url(../images/bg-gradients.png) repeat-x 0px -220px; /*+placement:shift 4px 0px;*/ position: relative; @@ -6819,7 +7374,7 @@ div.panel.ui-dialog div.list-view div.fixed-header { text-shadow: 0px 1px #FFFFFF; } -.multi-edit .disabled .button.add-vm { +.multi-edit .disabled .button.add-vm .button.custom-action { /*+opacity:50%;*/ filter: alpha(opacity=50); -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=50); @@ -6912,10 +7467,19 @@ div.panel.ui-dialog div.list-view div.fixed-header { border-left: none; border-right: 1px solid #CFC9C9; height: 15px; - overflow: hidden; + overflow: auto; padding-right: 0; } +.multi-edit .data .data-body .data-item > table tbody tr td span { + overflow: hidden; + max-width: 78px; + display: block; + float: left; + text-overflow: ellipsis; + white-space: nowrap; +} + .multi-edit .data .data-body .data-item table tbody tr td.blank { } @@ -6924,6 +7488,7 @@ div.panel.ui-dialog div.list-view div.fixed-header { } .multi-edit .data .data-body .data-item table tbody tr td.name span { + width: 53px; color: #4C5D78; font-weight: bold; } @@ -6960,6 +7525,7 @@ div.panel.ui-dialog div.list-view div.fixed-header { .multi-edit .data .data-body .data-item tr td .expand { width: 14px; height: 15px; + display: block; cursor: pointer; background: #FFFFFF url(../images/sprites.png) -541px -499px; border: 1px solid #D0D0D0; @@ -7548,7 +8114,7 @@ div.panel.ui-dialog div.list-view div.fixed-header { max-width: 98px; max-height: 21px; padding: 7px; - font-size: 14px; + font-size: 10px; position: absolute; overflow: hidden; color: #485563; @@ -7794,6 +8360,16 @@ div.panel.ui-dialog div.list-view div.fixed-header { background-color: #35404B; } +.system-dashboard.zone .status_box li .icon { + background: url(../images/infrastructure-icons.png) no-repeat 0px 0px; + padding: 65px 65px 5px; + /*+placement:shift 25px 19px;*/ + position: relative; + left: 25px; + top: 19px; + position: absolute; +} + .system-dashboard .status_box li span { color: #FFFFFF; /*+text-shadow:0px 1px 1px #000000;*/ @@ -7903,11 +8479,11 @@ div.panel.ui-dialog div.list-view div.fixed-header { } .system-dashboard .status_box li span.overview.total { - font-size: 71px; - /*+placement:shift 8px 26px;*/ + font-size: 56px; + /*+placement:shift 9px 29px;*/ position: relative; - left: 8px; - top: 26px; + left: 9px; + top: 29px; position: absolute; font-weight: normal; } @@ -8013,6 +8589,47 @@ div.panel.ui-dialog div.list-view div.fixed-header { margin: 8px 0 0 9px; } +/** Infrastructure icons*/ +.system-dashboard.zone .status_box li.zones .icon { + background-position: -36px -105px; +} + +.system-dashboard.zone .status_box li.pods .icon { + background-position: -229px -105px; +} + +.system-dashboard.zone .status_box li.clusters .icon { + background-position: -411px -96px; +} + +.system-dashboard.zone .status_box li.hosts .icon { + background-position: -601px -102px; +} + +.system-dashboard.zone .status_box li.primary-storage .icon { + background-position: -32px -404px; + /*+placement:shift 37px 68px;*/ + position: relative; + left: 37px; + top: 68px; +} + +.system-dashboard.zone .status_box li.secondary-storage .icon { + background-position: -216px -404px; + /*+placement:shift 37px 68px;*/ + position: relative; + left: 37px; + top: 68px; +} + +.system-dashboard.zone .status_box li.system-vms .icon { + background-position: -408px -399px; +} + +.system-dashboard.zone .status_box li.virtual-routers .icon { + background-position: -601px -400px; +} + /*Projects ** View switcher*/ #header .view-switcher { @@ -8180,6 +8797,7 @@ div.panel.ui-dialog div.list-view div.fixed-header { .project-selector .listing .data ul li { padding: 10px 0 10px 7px; cursor: pointer; + font-size: 12px; } .project-selector .listing .data ul li.odd { @@ -8203,8 +8821,8 @@ div.panel.ui-dialog div.list-view div.fixed-header { text-shadow: 0px 1px 1px #FFFFFF; text-align: left; color: #4F6171; - font-size: 12px; - padding: 2px 2px 3px 7px; + font-size: 11px; + padding: 3px 2px 3px 7px; border-bottom: 1px solid #FFFFFF; position: absolute; left: 0; @@ -8217,17 +8835,14 @@ div.panel.ui-dialog div.list-view div.fixed-header { border-radius: 4px 4px 4px 4px; font-size: 13px; font-weight: bold; + padding: 8px 20px; float: none; cursor: pointer; color: #838181; - /*+placement:shift 488px 9px;*/ - position: relative; - left: 488px; - top: 9px; left: 170px; top: -8px; - margin: 19px 0 0 0px; width: 54px; + margin: auto auto 17px; } .project-selector .button.cancel:hover { @@ -8592,9 +9207,9 @@ div.panel.ui-dialog div.list-view div.fixed-header { } .info-boxes .info-box ul li .date { - font-size: 13px; + font-size: 11px; text-align: center; - margin: 0; + margin: 1px 0 0; } .info-boxes .info-box ul li .date span { @@ -8613,7 +9228,10 @@ div.panel.ui-dialog div.list-view div.fixed-header { top: 8px; display: inline-block; padding-bottom: 13px; - max-width: 171px; + max-width: 153px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; } .info-boxes .info-box ul li .total span { @@ -9001,6 +9619,39 @@ div.panel.ui-dialog div.list-view div.fixed-header { background: #DFE1E3; } +/*Tooltip*/ +.tooltip-box { + width: 15%; + height: auto; + display: inline-block; + padding: 4px; + background: #FFFFFF; + border: 1px solid #BEB8B8; + padding: 10px; + /*+border-radius:4px;*/ + -moz-border-radius: 4px; + -webkit-border-radius: 4px; + -khtml-border-radius: 4px; + border-radius: 4px; + margin-left: 23px; + /*+box-shadow:0px 1px 12px #353535;*/ + -moz-box-shadow: 0px 1px 12px #353535; + -webkit-box-shadow: 0px 1px 12px #353535; + -o-box-shadow: 0px 1px 12px #353535; + box-shadow: 0px 1px 12px #353535; +} + +.tooltip-box .arrow { + width: 19px; + height: 30px; + background: url(../images/sprites.png) -585px -947px; + /*+placement:shift -16px 3px;*/ + position: relative; + left: -16px; + top: 3px; + position: absolute; +} + /*Tagger*/ .tagger { width: 94%; @@ -9779,6 +10430,272 @@ div.ui-dialog div.acl div.multi-edit div.data div.data-body div.data-item table max-height: 600px; } +div.container div.panel div#details-tab-network.detail-group div div.multi-edit table.multi-edit tbody tr td, +div.container div.panel div#details-tab-network.detail-group div div.multi-edit table.multi-edit thead tr th { + min-width: 80px; + max-width: 80px; + font-size: 10px; +} + +.ui-dialog div.autoscaler .detail-actions { +} + +.ui-dialog div.autoscaler .detail-actions .buttons { + float: right; + margin-right: 6px; +} + +.ui-dialog div.autoscaler .detail-actions .buttons .action { + width: 32px; + float: left; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=securityGroups] { + display: block; + width: 370px; + float: left; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=diskOfferingId] { + display: inline-block; + width: 370px; + float: left; + position: relative; + margin-top: 1px; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=minInstance] { + display: block; + width: 50%; + float: left; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=maxInstance] { + display: inline-block; + width: 50%; + float: left; + left: -30px; + position: relative; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=interval] { + display: block; + width: 50%; + float: left; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=quietTime] { + display: inline-block; + width: 50%; + float: left; + left: -15px; + position: relative; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=snmpCommunity] { + display: block; + width: 50%; + float: left; +} + +.ui-dialog div.autoscaler div.form-container div.form-item[rel=snmpPort] { + display: inline-block; + width: 50%; + float: left; + left: -15px; + position: relative; +} + +.ui-dialog div.autoscaler div.form-container div.value select { + width: 88%; + float: left; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title div.form-container { + height: 55px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title div.form-container { + height: 55px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy div.multi-edit { + margin-top: 0px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy div.multi-edit { + margin-top: 0px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title { + color: #0055BB; + margin-left: -650px; + margin-top: 40px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title label { + font-size: 13px; + margin-left: 200px; + margin-right: 10px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title hr.policy-divider { + border-left: 1px none #38546D; + border-right: 1px none #16222C; + border-top: 1px none #38546D; + margin-bottom: 12px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title hr.policy-divider { + border-left: 1px none #38546D; + border-right: 1px none #16222C; + border-top: 1px none #38546D; + margin-bottom: 12px; +} + +div.ui-dialog div.autoscaler div.field-group.bottom-fields hr.policy-divider { + border-left: 1px none #38546D; + border-right: 1px none #16222C; + border-top: 1px none #38546D; + margin-top: 15px; + margin-bottom: -1px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title label { + font-size: 13px; + margin-left: 170px; + margin-right: 10px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title { + color: #0055BB; + margin-left: -620px; + margin-top: 10px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title div.form-container div.form-item div.value input[type=text] { + margin-left: 729px; + width: 30%; + margin-top: -17px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy-title div.form-container div.form-item div.name { + margin-left: 420px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title div.form-container div.form-item div.value input[type=text] { + margin-left: 698px; + width: 30%; + margin-top: -16px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy-title div.form-container div.form-item div.name { + margin-left: 420px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy div.multi-edit div.data div.data-body div.data-item { + margin-bottom: 0px; + margin-right: 22px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy div.multi-edit div.data div.data-body div.data-item { + margin-bottom: 0px; + margin-right: 22px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy div.slide-label { + color: #A5A3A7; + font-size: 14px; + margin-bottom: 3px; + margin-left: 755px; + width: 12px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy div.slide-label { + color: #A5A3A7; + font-size: 14px; + margin-bottom: 3px; + margin-left: 755px; + width: 12px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy div.hide { + background: #FFFFFF url("../images/minus.png") no-repeat 38% 59%; + border: 1px solid #D0D0D0; + border-radius: 9px 9px 9px 9px; + cursor: pointer; + float: right; + height: 15px; + margin: -20px 45px 0 11px; + width: 14px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy div.hide { + background: #FFFFFF url("../images/minus.png") no-repeat 31% 54%; + border: 1px solid #D0D0D0; + border-radius: 9px 9px 9px 9px; + cursor: pointer; + float: right; + height: 15px; + margin: -20px 45px 0 11px; + width: 14px; +} + +div.ui-dialog div.autoscaler div.scale-up-policy div.expand { + background: #FFFFFF url("../images/sprites.png") repeat -541px -499px; + border: 1px solid #D0D0D0; + border-radius: 9px 9px 9px 9px; + cursor: pointer; + float: right; + height: 15px; + margin: -20px 45px 0 11px; + width: 14px; +} + +div.ui-dialog div.autoscaler div.scale-down-policy div.expand { + background: #FFFFFF url("../images/sprites.png") repeat -541px -499px; + border: 1px solid #D0D0D0; + border-radius: 9px 9px 9px 9px; + cursor: pointer; + float: right; + height: 15px; + margin: -20px 45px 0 11px; + width: 14px; +} + +div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-item div.name label { + font-size: 11px; +} + +/*List state BG colors*/ +.list-view .body td.item-state-on { + background: #C0FFC0; + border-bottom: 1px solid #09BC09; +} + +.list-view .body td.item-state-off { + background: #FFD8CF; + border-bottom: 1px solid #FF9F9F; +} + +.list-view .body tr.selected td.item-state-on, +.list-view .body tr.selected td.item-state-off { + background-color: inherit; + border-color: inherit; +} + +/*Autoscaler*/ +.ui-dialog div.autoscaler { + overflow: auto; + max-height: 600px; +} + +div.container div.panel div#details-tab-network.detail-group div div.multi-edit table.multi-edit tbody tr td, +div.container div.panel div#details-tab-network.detail-group div div.multi-edit table.multi-edit thead tr th { + min-width: 72px; + font-size: 10px; +} + .ui-dialog div.autoscaler .detail-actions { } @@ -10009,15 +10926,6 @@ div.ui-dialog div.autoscaler div.field-group div.form-container form div.form-it font-size: 11px; } -/*CS-16413: Disable infrastructure totals*/ -.system-dashboard.zone .status_box li span.header { - display: block; - width: 156px; - font-size: 16px; - text-align: center; - top: 31px; -} - /*Action icons*/ .action.edit .icon { background-position: 1px -1px; @@ -10271,11 +11179,19 @@ 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 9457e30af79..203c9daa52e 100644 --- a/ui/dictionary.jsp +++ b/ui/dictionary.jsp @@ -25,6 +25,26 @@ under the License. <% long now = System.currentTimeMillis(); %> diff --git a/ui/images/bg-what-is-cloudplatform.png b/ui/images/bg-what-is-cloudplatform.png deleted file mode 100644 index 138c63bbaea..00000000000 Binary files a/ui/images/bg-what-is-cloudplatform.png and /dev/null differ diff --git a/ui/images/citrix-logo-darkbg.png b/ui/images/citrix-logo-darkbg.png deleted file mode 100644 index 22d99b828b8..00000000000 Binary files a/ui/images/citrix-logo-darkbg.png and /dev/null differ diff --git a/ui/images/icons.png b/ui/images/icons.png index 63c10b02631..ea1a39cdf7f 100644 Binary files a/ui/images/icons.png and b/ui/images/icons.png differ diff --git a/ui/images/infrastructure-icons.png b/ui/images/infrastructure-icons.png new file mode 100644 index 00000000000..7d4f8f9f082 Binary files /dev/null and b/ui/images/infrastructure-icons.png differ diff --git a/ui/images/logo-cloudplatform.png b/ui/images/logo-cloudplatform.png deleted file mode 100644 index f749ec74d6a..00000000000 Binary files a/ui/images/logo-cloudplatform.png and /dev/null differ diff --git a/ui/images/logo-login.png b/ui/images/logo-login.png deleted file mode 100644 index 0c7e38e665e..00000000000 Binary files a/ui/images/logo-login.png and /dev/null differ diff --git a/ui/images/minus.png b/ui/images/minus.png new file mode 100644 index 00000000000..077db991d49 Binary files /dev/null and b/ui/images/minus.png differ diff --git a/ui/images/sprites.png b/ui/images/sprites.png index db95cca7b6e..a3ad9e4862f 100644 Binary files a/ui/images/sprites.png and b/ui/images/sprites.png differ diff --git a/ui/index.jsp b/ui/index.jsp index 74a6f6d4b8c..a9b83e6fdd5 100644 --- a/ui/index.jsp +++ b/ui/index.jsp @@ -68,10 +68,13 @@ under the License.
@@ -477,19 +480,34 @@ under the License.

-
+
-
+
+ +
+
+ +
+ + +
+
+ +
+ + +
+
@@ -530,10 +548,11 @@ under the License.
    • " class="traffic-type-draggable management">
      +   Edit
      @@ -547,10 +566,11 @@ under the License.
      • " class="traffic-type-draggable public">
        +   Edit
        @@ -564,10 +584,11 @@ under the License.
        • " class="traffic-type-draggable guest">
          +   Edit
          @@ -581,10 +602,11 @@ under the License.
          • " class="traffic-type-draggable storage">
            +   Edit
            @@ -949,57 +971,65 @@ under the License.
    • -
    • +
    • +   " view-all-target="zones">
    • -
    • +
    • +   " view-all-target="pods">
    • -
    • +
    • +   " view-all-target="clusters">
    • -
    • +
    • +   " view-all-target="hosts">
    • -
    • +
    • +   " view-all-target="primaryStorage">
    • -
    • +
    • +   " view-all-target="secondaryStorage">
    • -
    • +
    • +   " view-all-target="systemVms">
    • -
    • +
    • +   " @@ -1605,13 +1635,15 @@ under the License. - + + + @@ -1639,7 +1671,8 @@ under the License. - + + diff --git a/ui/scripts/accounts.js b/ui/scripts/accounts.js index 15da5218aea..59e9d8bbd15 100644 --- a/ui/scripts/accounts.js +++ b/ui/scripts/accounts.js @@ -79,13 +79,15 @@ fields: { username: { label: 'label.username', - validation: { required: true } + validation: { required: true }, + docID: 'helpAccountUsername' }, password: { label: 'label.password', validation: { required: true }, isPassword: true, - id: 'password' + id: 'password', + docID: 'helpAccountPassword' }, 'password-confirm': { label: 'label.confirm.password', @@ -93,22 +95,27 @@ required: true, equalTo: '#password' }, - isPassword: true + isPassword: true, + docID: 'helpAccountConfirmPassword' }, email: { label: 'label.email', - validation: { required: true, email:true } + validation: { required: true, email:true }, + docID: 'helpAccountEmail' }, firstname: { label: 'label.first.name', - validation: { required: true } + validation: { required: true }, + docID: 'helpAccountFirstName' }, lastname: { label: 'label.last.name', - validation: { required: true } + validation: { required: true }, + docID: 'helpAccountLastName' }, domainid: { label: 'label.domain', + docID: 'helpAccountDomain', validation: { required: true }, select: function(args) { var data = {}; @@ -139,10 +146,12 @@ } }, account: { - label: 'label.account' + label: 'label.account', + docID: 'helpAccountAccount' }, accounttype: { label: 'label.type', + docID: 'helpAccountType', validation: { required: true }, select: function(args) { var items = []; @@ -153,6 +162,7 @@ }, timezone: { label: 'label.timezone', + docID: 'helpAccountTimezone', select: function(args) { var items = []; items.push({id: "", description: ""}); @@ -163,54 +173,70 @@ }, networkdomain: { label: 'label.network.domain', + docID: 'helpAccountNetworkDomain', validation: { required: false } } } }, action: function(args) { - var array1 = []; - array1.push("&username=" + todb(args.data.username)); - var errorMsg = ""; + var data = { + username: args.data.username + }; + var password = args.data.password; - if (md5Hashed) - password = $.md5(password); - else - password = todb(password); - array1.push("&password=" + password); - - array1.push("&email=" + todb(args.data.email)); - array1.push("&firstname=" + todb(args.data.firstname)); - array1.push("&lastname=" + todb(args.data.lastname)); - - array1.push("&domainid=" + args.data.domainid); + if (md5Hashed) { + password = $.md5(password); + } + $.extend(data, { + password: password + }); + + $.extend(data, { + email: args.data.email, + firstname: args.data.firstname, + lastname: args.data.lastname, + domainid: args.data.domainid + }); var account = args.data.account; - if(account == null || account.length == 0) + if(account == null || account.length == 0) { account = args.data.username; - array1.push("&account=" + todb(account)); - + } + $.extend(data, { + account: account + }); + var accountType = args.data.accounttype; - if (args.data.accounttype == "1" && args.data.domainid != rootDomainId) //if account type is admin, but domain is not Root domain - accountType = "2"; // Change accounttype from root-domain("1") to domain-admin("2") - array1.push("&accounttype=" + accountType); + if (args.data.accounttype == "1" && args.data.domainid != rootDomainId) { //if account type is admin, but domain is not Root domain + accountType = "2"; // Change accounttype from root-domain("1") to domain-admin("2") + } + $.extend(data, { + accounttype: accountType + }); + + if(args.data.timezone != null && args.data.timezone.length > 0) { + $.extend(data, { + timezone: args.data.timezone + }); + } - if(args.data.timezone != null && args.data.timezone.length > 0) - array1.push("&timezone=" + todb(args.data.timezone)); - - if(args.data.networkdomain != null && args.data.networkdomain.length > 0) - array1.push("&networkdomain=" + todb(args.data.networkdomain)); + if(args.data.networkdomain != null && args.data.networkdomain.length > 0) { + $.extend(data, { + networkdomain: args.data.networkdomain + }); + } $.ajax({ - url: createURL("createAccount" + array1.join("")), - dataType: "json", + url: createURL('createAccount'), + type: "POST", + data: data, success: function(json) { var item = json.createaccountresponse.account; args.response.success({data:item}); }, - error: function(XMLHttpResponse) { - var errorMsg = parseXMLHttpResponse(XMLHttpResponse); - args.response.error(errorMsg); + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); } }); }, @@ -226,23 +252,18 @@ }, dataProvider: function(args) { - var array1 = []; - if(args.filterBy != null) { - if(args.filterBy.search != null && args.filterBy.search.by != null && args.filterBy.search.value != null) { - switch(args.filterBy.search.by) { - case "name": - if(args.filterBy.search.value.length > 0) - array1.push("&keyword=" + args.filterBy.search.value); - break; - } - } - } - - if("domains" in args.context) - array1.push("&domainid=" + args.context.domains[0].id); + var data = {}; + listViewDataProvider(args, data); + + if("domains" in args.context) { + $.extend(data, { + domainid: args.context.domains[0].id + }); + } + $.ajax({ - url: createURL("listAccounts" + "&page=" + args.page + "&pagesize=" + pageSize + array1.join("") + '&listAll=true'), - dataType: "json", + url: createURL('listAccounts'), + data: data, async: true, success: function(json) { var items = json.listaccountsresponse.account; @@ -261,31 +282,40 @@ actions: { edit: { label: 'message.edit.account', - action: function(args) { - var errorMsg = ""; + compactLabel: 'label.edit', + action: function(args) { var accountObj = args.context.accounts[0]; - var array1 = []; - array1.push("&newname=" + todb(args.data.name)); - array1.push("&networkdomain=" + todb(args.data.networkdomain)); + var data = { + domainid: accountObj.domainid, + account: accountObj.name, + newname: args.data.name, + networkdomain: args.data.networkdomain + }; + $.ajax({ - url: createURL("updateAccount&domainid=" + accountObj.domainid + "&account=" + accountObj.name + array1.join("")), - dataType: "json", + url: createURL('updateAccount'), + data: data, async: false, success: function(json) { accountObj = json.updateaccountresponse.account; }, error: function(json) { - errorMsg = parseXMLHttpResponse(json); + var errorMsg = parseXMLHttpResponse(json); args.response.error(errorMsg); - } - + } }); if(args.data.vmLimit != null) { + var data = { + resourceType: 0, + max: args.data.vmLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("updateResourceLimit&resourceType=0&max=" + todb(args.data.vmLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["vmLimit"] = args.data.vmLimit; @@ -294,9 +324,15 @@ } if(args.data.ipLimit != null) { + var data = { + resourceType: 1, + max: args.data.ipLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("updateResourceLimit&resourceType=1&max=" + todb(args.data.ipLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["ipLimit"] = args.data.ipLimit; @@ -305,9 +341,15 @@ } if(args.data.volumeLimit != null) { + var data = { + resourceType: 2, + max: args.data.volumeLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("updateResourceLimit&resourceType=2&max=" + todb(args.data.volumeLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["volumeLimit"] = args.data.volumeLimit; @@ -316,9 +358,15 @@ } if(args.data.snapshotLimit != null) { + var data = { + resourceType: 3, + max: args.data.snapshotLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("updateResourceLimit&resourceType=3&max=" + todb(args.data.snapshotLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["snapshotLimit"] = args.data.snapshotLimit; @@ -327,9 +375,15 @@ } if(args.data.templateLimit != null) { + var data = { + resourceType: 4, + max: args.data.templateLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("updateResourceLimit&resourceType=4&max=" + todb(args.data.templateLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["templateLimit"] = args.data.templateLimit; @@ -338,9 +392,16 @@ } if(args.data.vpcLimit != null) { + var data = { + resourceType: 7, + max: args.data.vpcLimit, + domainid: accountObj.domainid, + account: accountObj.name + }; + $.ajax({ - url: createURL("updateResourceLimit&resourceType=7&max=" + todb(args.data.vpcLimit) + "&account=" + accountObj.name + "&domainid=" + accountObj.domainid), - dataType: "json", + url: createURL('updateResourceLimit'), + data: data, async: false, success: function(json) { accountObj["vpcLimit"] = args.data.vpcLimit; @@ -348,7 +409,6 @@ }); } - if(errorMsg == "") args.response.success({data: accountObj}); } }, @@ -365,9 +425,14 @@ }, action: function(args) { var accountObj = args.context.accounts[0]; + var data = { + domainid: accountObj.domainid, + account: accountObj.name + }; + $.ajax({ - url: createURL("updateResourceCount&domainid=" + accountObj.domainid + "&account=" + accountObj.name), - dataType: "json", + url: createURL('updateResourceCount'), + data: data, async: true, success: function(json) { //var resourcecounts= json.updateresourcecountresponse.resourcecount; //do nothing @@ -397,9 +462,15 @@ }, action: function(args) { var accountObj = args.context.accounts[0]; + var data = { + lock: false, + domainid: accountObj.domainid, + account: accountObj.name + }; + $.ajax({ - url: createURL("disableAccount&lock=false&domainid=" + accountObj.domainid + "&account=" + accountObj.name), - dataType: "json", + url: createURL('disableAccount'), + data: data, async: true, success: function(json) { var jid = json.disableaccountresponse.jobid; @@ -435,9 +506,15 @@ }, action: function(args) { var accountObj = args.context.accounts[0]; + var data = { + lock: true, + domainid: accountObj.domainid, + account: accountObj.name + }; + $.ajax({ - url: createURL("disableAccount&lock=true&domainid=" + accountObj.domainid + "&account=" + accountObj.name), - dataType: "json", + url: createURL('disableAccount'), + data: data, async: true, success: function(json) { var jid = json.disableaccountresponse.jobid; @@ -473,9 +550,13 @@ }, action: function(args) { var accountObj = args.context.accounts[0]; + var data = { + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("enableAccount&domainid=" + accountObj.domainid + "&account=" + accountObj.name), - dataType: "json", + url: createURL('enableAccount'), + data: data, async: true, success: function(json) { args.response.success({data: json.enableaccountresponse.account}); @@ -502,9 +583,12 @@ } }, action: function(args) { + var data = { + id: args.context.accounts[0].id + }; $.ajax({ - url: createURL("deleteAccount&id=" + args.context.accounts[0].id), - dataType: "json", + url: createURL('deleteAccount'), + data: data, async: true, success: function(json) { var jid = json.deleteaccountresponse.jobid; @@ -635,15 +719,21 @@ ], dataProvider: function(args) { + var data = { + id: args.context.accounts[0].id + }; $.ajax({ - url: createURL("listAccounts&id=" + args.context.accounts[0].id), - dataType: "json", + url: createURL('listAccounts'), + data: data, success: function(json) { var accountObj = json.listaccountsresponse.account[0]; - + var data = { + domainid: accountObj.domainid, + account: accountObj.name + }; $.ajax({ - url: createURL("listResourceLimits&domainid=" + accountObj.domainid + "&account=" + todb(accountObj.name)), - dataType: "json", + url: createURL('listResourceLimits'), + data: data, success: function(json) { var limits = json.listresourcelimitsresponse.resourcelimit; if (limits != null) { @@ -698,24 +788,19 @@ firstname: { label: 'label.first.name' }, lastname: { label: 'label.last.name' } }, - dataProvider: function(args) { - var array1 = []; - if(args.filterBy != null) { - if(args.filterBy.search != null && args.filterBy.search.by != null && args.filterBy.search.value != null) { - switch(args.filterBy.search.by) { - case "name": - if(args.filterBy.search.value.length > 0) - array1.push("&keyword=" + args.filterBy.search.value); - break; - } - } - } - + dataProvider: function(args) { var accountObj = args.context.accounts[0]; + if(isAdmin() || isDomainAdmin()) { + var data = { + domainid: accountObj.domainid, + account: accountObj.name + }; + listViewDataProvider(args, data); + $.ajax({ - url: createURL("listUsers&domainid=" + accountObj.domainid + "&account=" + todb(accountObj.name) + "&page=" + args.page + "&pagesize=" + pageSize + array1.join("")), - dataType: "json", + url: createURL('listUsers'), + data: data, success: function(json) { args.response.success({ actionFilter: userActionfilter, @@ -753,16 +838,19 @@ fields: { username: { label: 'label.username', - validation: { required: true } + validation: { required: true }, + docID: 'helpUserUsername' }, password: { label: 'label.password', isPassword: true, validation: { required: true }, - id: 'password' + id: 'password', + docID: 'helpUserPassword' }, 'password-confirm': { label: 'label.confirm.password', + docID: 'helpUserConfirmPassword', validation: { required: true, equalTo: '#password' @@ -771,18 +859,22 @@ }, email: { label: 'label.email', + docID: 'helpUserEmail', validation: { required: true, email: true } }, firstname: { label: 'label.first.name', + docID: 'helpUserFirstName', validation: { required: true } }, lastname: { label: 'label.last.name', + docID: 'helpUserLastName', validation: { required: true } }, timezone: { label: 'label.timezone', + docID: 'helpUserTimezone', select: function(args) { var items = []; items.push({id: "", description: ""}); @@ -797,29 +889,40 @@ action: function(args) { var accountObj = args.context.accounts[0]; - var array1 = []; - array1.push("&username=" + todb(args.data.username)); - + var data = { + username: args.data.username + }; + var password = args.data.password; - if (md5Hashed) - password = $.md5(password); - else - password = todb(password); - array1.push("&password=" + password); - - array1.push("&email=" + todb(args.data.email)); - array1.push("&firstname=" + todb(args.data.firstname)); - array1.push("&lastname=" + todb(args.data.lastname)); - if(args.data.timezone != null && args.data.timezone.length > 0) - array1.push("&timezone=" + todb(args.data.timezone)); - - array1.push("&domainid=" + accountObj.domainid); - array1.push("&account=" + todb(accountObj.name)); - array1.push("&accounttype=" + accountObj.accounttype); - + if (md5Hashed) { + password = $.md5(password); + } + $.extend(data, { + password: password + }); + + $.extend(data, { + email: args.data.email, + firstname: args.data.firstname, + lastname: args.data.lastname + }); + + if(args.data.timezone != null && args.data.timezone.length > 0) { + $.extend(data, { + timezone: args.data.timezone + }); + } + + $.extend(data, { + domainid: accountObj.domainid, + account: accountObj.name, + accounttype: accountObj.accounttype + }); + $.ajax({ - url: createURL("createUser" + array1.join("")), - dataType: "json", + url: createURL('createUser'), + type: "POST", + data: data, success: function(json) { var item = json.createuserresponse.user; args.response.success({data: item}); @@ -846,15 +949,17 @@ edit: { label: 'label.edit', action: function(args) { - var array1 = []; - array1.push("&username=" + todb(args.data.username)); - array1.push("&email=" + todb(args.data.email)); - array1.push("&firstname=" + todb(args.data.firstname)); - array1.push("&lastname=" + todb(args.data.lastname)); - array1.push("&timezone=" + todb(args.data.timezone)); + var data = { + id: args.context.users[0].id, + username: args.data.username, + email: args.data.email, + firstname: args.data.firstname, + lastname: args.data.lastname, + timezone: args.data.timezone + }; $.ajax({ - url: createURL("updateUser&id=" + args.context.users[0].id + array1.join("")), - dataType: "json", + url: createURL('updateUser'), + data: data, success: function(json) { var item = json.updateuserresponse.user; args.response.success({data:item}); @@ -897,11 +1002,15 @@ var password = args.data.newPassword; if (md5Hashed) password = $.md5(password); - else - password = todb(password); + + var data = { + id: args.context.users[0].id, + password: password + }; + $.ajax({ - url: createURL("updateUser&id=" + args.context.users[0].id + "&password=" + password), - dataType: "json", + url: createURL('updateUser'), + data: data, async: true, success: function(json) { args.response.success({data: json.updateuserresponse.user}); @@ -926,10 +1035,12 @@ } }, action: function(args) { + var data = { + id: args.context.users[0].id + }; $.ajax({ - url: createURL("registerUserKeys&id=" + args.context.users[0].id), - dataType: "json", - async: true, + url: createURL('registerUserKeys'), + data: data, success: function(json) { args.response.success({data: json.registeruserkeysresponse.userkeys}); } @@ -953,10 +1064,12 @@ } }, action: function(args) { + var data = { + id: args.context.users[0].id + }; $.ajax({ - url: createURL("disableUser&id=" + args.context.users[0].id), - dataType: "json", - async: true, + url: createURL('disableUser'), + data: data, success: function(json) { var jid = json.disableuserresponse.jobid; args.response.success( @@ -990,10 +1103,12 @@ } }, action: function(args) { + var data = { + id: args.context.users[0].id + }; $.ajax({ - url: createURL("enableUser&id=" + args.context.users[0].id), - dataType: "json", - async: true, + url: createURL('enableUser'), + data: data, success: function(json) { args.response.success({data: json.enableuserresponse.user}); }, @@ -1020,10 +1135,12 @@ } }, action: function(args) { + var data = { + id: args.context.users[0].id + }; $.ajax({ - url: createURL("deleteUser&id=" + args.context.users[0].id), - dataType: "json", - async: true, + url: createURL('deleteUser'), + data: data, success: function(json) { args.response.success(); } @@ -1133,22 +1250,20 @@ if (jsonObj.state == 'Destroyed') return []; if(isAdmin()) { - allowedActions.push("edit"); //updating networkdomain is allowed on any account, including system-generated default admin account - if(!(jsonObj.domain == "ROOT" && jsonObj.name == "admin" && jsonObj.accounttype == 1)) { //if not system-generated default admin account - if(jsonObj.state == "enabled") { - allowedActions.push("disable"); - allowedActions.push("lock"); + allowedActions.push("edit"); //updating networkdomain is allowed on any account, including system-generated default admin account + if(!(jsonObj.domain == "ROOT" && jsonObj.name == "admin" && jsonObj.accounttype == 1)) { //if not system-generated default admin account + if(jsonObj.state == "enabled") { + allowedActions.push("disable"); + allowedActions.push("lock"); + } else if(jsonObj.state == "disabled" || jsonObj.state == "locked") { + allowedActions.push("enable"); + } + allowedActions.push("remove"); } - else if(jsonObj.state == "disabled" || jsonObj.state == "locked") { - allowedActions.push("enable"); - } - allowedActions.push("remove"); - } - allowedActions.push("updateResourceCount"); - } - else if(isDomainAdmin()) { - allowedActions.push("updateResourceCount"); - } + allowedActions.push("updateResourceCount"); + } else if(isDomainAdmin()) { + allowedActions.push("updateResourceCount"); + } return allowedActions; } @@ -1166,6 +1281,11 @@ allowedActions.push("enable"); allowedActions.push("remove"); } + } else { + if(isSelfOrChildDomainUser(jsonObj.username, jsonObj.accounttype, jsonObj.domainid, jsonObj.iscallerchilddomain)) { + allowedActions.push("changePassword"); + allowedActions.push("generateKeys"); + } } return allowedActions; } diff --git a/ui/scripts/autoscaler.js b/ui/scripts/autoscaler.js new file mode 100644 index 00000000000..a56fd94e441 --- /dev/null +++ b/ui/scripts/autoscaler.js @@ -0,0 +1,1431 @@ +// 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. + +(function($,cloudstack) { + var scaleUpData = []; + var totalScaleUpCondition = 0; + var scaleDownData = []; + var totalScaleDownCondition = 0; + + cloudStack.autoscaler = { + // UI actions to appear in dialog + autoscaleActions: { + enable: { + label: 'Enable Autoscale', + action: function(args) { + $.ajax({ + url: createURL('enableAutoScaleVmGroup'), + data: { + id: args.context.originalAutoscaleData.context.autoscaleVmGroup.id + }, + success: function(json) { + var jid = json.enableautoscalevmGroupresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.autoscalevmgroup; + }, + getActionFilter: function() { + return cloudStack.autoscaler.actionFilter; + } + }, + notification: { + poll: pollAsyncJobResult + } + }); + } + }); + } + }, + disable: { + label: 'Disable Autoscale', + action: function(args) { + $.ajax({ + url: createURL('disableAutoScaleVmGroup'), + data: { + id: args.context.originalAutoscaleData.context.autoscaleVmGroup.id + }, + success: function(json) { + var jid = json.disableautoscalevmGroupresponse.jobid; + args.response.success({ + _custom: { + jobId: jid, + getUpdatedItem: function(json) { + return json.queryasyncjobresultresponse.jobresult.autoscalevmgroup; + }, + getActionFilter: function() { + return cloudStack.autoscaler.actionFilter; + } + }, + notification: { + poll: pollAsyncJobResult + } + }); + } + }); + } + } + }, + actionFilter: function(args) { + var allowedActions = []; + if(args.context.originalAutoscaleData == null) { //new LB rule + //no actions for new LB rule + } + else { //existing LB rule + if(args.context.originalAutoscaleData[0].afterActionIsComplete == null) { + if(args.context.originalAutoscaleData[0].context.autoscaleVmGroup.state == 'disabled') + allowedActions.push('enable'); + else if(args.context.originalAutoscaleData[0].context.autoscaleVmGroup.state == 'enabled') + allowedActions.push('disable'); + } + else { + if(args.context.originalAutoscaleData[0].afterActionIsComplete.state == 'disabled') + allowedActions.push('enable'); + else if(args.context.originalAutoscaleData[0].afterActionIsComplete.state == 'enabled') + allowedActions.push('disable'); + } + } + return allowedActions; + }, + dataProvider: function(args) { + // Reset data + scaleUpData = []; + totalScaleUpCondition = 0; + scaleDownData = []; + totalScaleDownCondition = 0; + + if(!('multiRules' in args.context)) { //from a new LB + args.response.success({ data: null }); + } + else { //from an existing LB + $.ajax({ + url: createURL('listAutoScaleVmGroups'), + data: { + listAll: true, + lbruleid: args.context.multiRules[0].id + }, + success: function(json) { + var autoscaleVmGroup = json.listautoscalevmgroupsresponse.autoscalevmgroup[0]; + + $.ajax({ + url: createURL('listAutoScaleVmProfiles'), + data: { + listAll: true, + id: autoscaleVmGroup.vmprofileid + }, + success: function(json) { + var autoscaleVmProfile = json.listautoscalevmprofilesresponse.autoscalevmprofile[0]; + + var scaleUpPolicy = { + id: autoscaleVmGroup.scaleuppolicies[0].id, + duration: autoscaleVmGroup.scaleuppolicies[0].duration, + conditions: [] + }; + $(autoscaleVmGroup.scaleuppolicies[0].conditions).each(function(){ + var condition = { + id: this.id, + counterid: this.counter[0].id, + relationaloperator: this.relationaloperator, + threshold: this.threshold + }; + scaleUpPolicy.conditions.push(condition); + }); + + var scaleDownPolicy = { + id: autoscaleVmGroup.scaledownpolicies[0].id, + duration: autoscaleVmGroup.scaledownpolicies[0].duration, + conditions: [] + }; + $(autoscaleVmGroup.scaledownpolicies[0].conditions).each(function(){ + var condition = { + id: this.id, + counterid: this.counter[0].id, + relationaloperator: this.relationaloperator, + threshold: this.threshold.toString() + }; + scaleDownPolicy.conditions.push(condition); + }); + + var diskOfferingId, securityGroups; + var otherdeployparams = autoscaleVmProfile.otherdeployparams; + if(otherdeployparams != null && otherdeployparams.length > 0) { + var array1 = otherdeployparams.split('&'); + $(array1).each(function(){ + var array2 = this.split('='); + if(array2[0] == 'diskofferingid') + diskOfferingId= array2[1]; + if(array2[0] == 'securitygroupids') + securityGroups = array2[1]; + }); + } + + var originalAutoscaleData = { + templateNames: autoscaleVmProfile.templateid, + serviceOfferingId: autoscaleVmProfile.serviceofferingid, + minInstance: autoscaleVmGroup.minmembers, + maxInstance: autoscaleVmGroup.maxmembers, + scaleUpPolicy: scaleUpPolicy, + scaleDownPolicy: scaleDownPolicy, + interval: autoscaleVmGroup.interval, + quietTime: autoscaleVmGroup.scaleuppolicies[0].quiettime, + destroyVMgracePeriod: autoscaleVmProfile.destroyvmgraceperiod, + securityGroups: securityGroups, + diskOfferingId: diskOfferingId, + snmpCommunity: autoscaleVmProfile.counterparam.snmpcommunity, + snmpPort: autoscaleVmProfile.counterparam.snmpport, + username: autoscaleVmProfile.autoscaleuserid, + context: { + autoscaleVmGroup: autoscaleVmGroup, + autoscaleVmProfile: autoscaleVmProfile + } + //isAdvanced: false // Set this to true if any advanced field data is present + }; + + args.response.success({ data: originalAutoscaleData }); + } + }); + } + }); + } + }, + + // -- + // Add the following object blocks: + // + // topFields: { } + // bottomFields: { }, + // scaleUpPolicy: { }, + // scaleDownPolicy: { } + // -- + // + forms: { + topFields: { + //** + //** Disabled due to UI issues + //** + // templateCategory: { + // label: 'Template', + // id: 'templatecategory', + // select: function(args) { + // args.response.success({ + // data: [ + // { id: 'all', description: _l('ui.listView.filters.all') }, + // { id: 'featured', description: _l('label.featured') }, + // { id: 'Community', description: _l('label.menu.community.templates') }, + // { id: 'self', description: _l('ui.listView.filters.mine') } + // ] + // }); + // } + // }, + //** + + templateNames: { + label: 'label.template', + id: 'templatename', + select: function(args) { + var templates; + var templateIdMap = {}; + $.ajax({ + url: createURL('listTemplates'), + data: { + templatefilter: 'featured', + zoneid: args.context.networks[0].zoneid + }, + async: false, + success: function(json) { + templates = json.listtemplatesresponse.template; + if (templates == null) + templates = []; + $(templates).each(function() { + templateIdMap[this.id] = 1; + }); + } + }); + + $.ajax({ + url: createURL('listTemplates'), + data: { + templatefilter: 'community', + zoneid: args.context.networks[0].zoneid + }, + async: false, + success: function(json) { + var items = json.listtemplatesresponse.template; + $(items).each(function() { + if(!(this.id in templateIdMap)) { + templates.push(this); + templateIdMap[this.id] = 1; + } + }); + } + }); + + $.ajax({ + url: createURL('listTemplates'), + data: { + templatefilter: 'selfexecutable', + zoneid: args.context.networks[0].zoneid + }, + async: false, + success: function(json) { + var items = json.listtemplatesresponse.template; + $(items).each(function() { + if(!(this.id in templateIdMap)) { + templates.push(this); + templateIdMap[this.id] = 1; + } + }); + } + }); + + args.response.success({ + data: $.map(templates, function(template) { + return { + id: template.id, + description: template.name + }; + }) + }); + } + }, + + serviceOfferingId: { + label: 'label.compute.offering', + select: function(args) { + $.ajax({ + url: createURL("listServiceOfferings&issystem=false"), + dataType: "json", + async: true, + success: function(json) { + var serviceofferings = json.listserviceofferingsresponse.serviceoffering; + args.response.success({ + data: $.map(serviceofferings, function(serviceoffering) { + return { + id: serviceoffering.id, + description: serviceoffering.name + }; + }) + }); + } + }); + } + }, + + minInstance: { + label: 'Min Instances', + defaultValue: '3', + validation: { + required: true, + number: true + } + }, + + maxInstance: { + label: 'Max Instances', + defaultValue: '10', + validation: { + required: true, + number: true + } + } + }, + + bottomFields: { + isAdvanced: { isBoolean: true, label: 'Show advanced settings' }, + interval: { + label: 'Polling Interval (in sec)', + defaultValue: '30', + validation: { + required: true, + number: true + } + }, + + quietTime: { + label: 'Quiet Time (in sec)', + defaultValue: '300', + validation: { + required: true, + number: true + } + }, + + destroyVMgracePeriod: { + label: 'Destroy VM Grace Period', + defaultValue: '30', + isHidden:true, + dependsOn:'isAdvanced', + validation: { + required: true, + number: true + } + }, + securityGroups: { + label: 'label.menu.security.groups', + isHidden: true, + dependsOn: 'isAdvanced', + select: function(args) { + $.ajax({ + url: createURL("listSecurityGroups&listAll=true"), + dataType: "json", + async: true, + success: function(json) { + var securitygroups = json.listsecuritygroupsresponse.securitygroup; + var items = []; + items.push({id: "", description: ""}); + $(securitygroups).each(function(){ + items.push({id: this.id, description: this.name}); + }); + args.response.success({ data: items }); + } + }); + } + }, + + diskOfferingId: { + label: 'label.menu.disk.offerings', + isHidden: true, + dependsOn: 'isAdvanced', + select: function(args) { + $.ajax({ + url: createURL("listDiskOfferings&listAll=true"), + dataType: "json", + async: true, + success: function(json) { + var diskofferings = json.listdiskofferingsresponse.diskoffering; + var items = []; + items.push({id: "", description: ""}); + $(diskofferings).each(function(){ + items.push({id: this.id, description: this.name}); + }); + args.response.success({ data: items }); + } + }); + } + }, + + snmpCommunity: { + isHidden: true, + dependsOn: 'isAdvanced', + label: 'SNMP Community', + defaultValue: 'public', + validation: { required: true } + }, + + snmpPort: { + isHidden: true, + dependsOn: 'isAdvanced', + label: 'SNMP Port', + defaultValue: '161', + validation: { + required: true, + number: true + } + }, + + username: { + isHidden: true, + dependsOn: 'isAdvanced', + label: 'User', + select: function(args) { + var items = []; + if(args.context.originalAutoscaleData == null) { //new LB rule + if(isAdmin() || isDomainAdmin()) { + $.ajax({ + url: createURL('listUsers'), + data: { + domainid: g_domainid, + account: g_account + }, + success: function(json) { + var users = json.listusersresponse.user; + $(users).each(function(){ + items.push({id: this.id, description: this.username}); + }); + args.response.success({ data: items }); + } + }); + } + else { //regular user doesn't have access to listUers API call. + items.push({id: "", description: ""}); + args.response.success({ data: items }); + } + } + else { //existing LB rule + if(isAdmin() || isDomainAdmin()) { + $.ajax({ + url: createURL('listUsers'), + data: { + domainid: args.context.originalAutoscaleData.context.autoscaleVmProfile.domainid, + account: args.context.originalAutoscaleData.context.autoscaleVmProfile.account + }, + success: function(json) { + var users = json.listusersresponse.user; + $(users).each(function(){ + items.push({id: this.id, description: this.username}); + }); + args.response.success({ data: items }); + } + }); + } + else { //regular user doesn't have access to listUers API call. + items.push({id: "", description: ""}); + args.response.success({ data: items }); + } + } + } + } + }, + scaleUpPolicy: { + title: 'ScaleUp Policy', + label: 'SCALE UP POLICY', + noSelect: true, + noHeaderActionsColumn: true, + ignoreEmptyFields: true, + fields: { + 'counterid': { + label: 'Counter', + select: function(args) { + $.ajax({ + url: createURL("listCounters"), + dataType: "json", + async: false, + success: function(json) { + var counters = json.counterresponse.counter; + + args.response.success({ + data: $.map(counters, function(counter) { + return { + name: counter.id, + description: counter.name + }; + }) + }); + } + }); + } + }, + 'relationaloperator': { + label: 'Operator', + select: function(args) { + args.response.success({ + data: [ + { name: 'GT', description: 'greater-than' }, + { name: 'GE', description: 'greater-than or equals to' }, + { name: 'LT', description: 'less-than' }, + { name: 'LE', description: 'less-than or equals to' }, + { name: 'EQ', description: 'equals-to' } + ] + }); + } + }, + 'threshold': { edit: true, label: 'Threshold' }, + 'add-scaleUpcondition': { + label: 'label.add', + addButton: true + } + }, + add: { + label: 'label.add', + action: function(args) { + scaleUpData.push($.extend(args.data, { + index: totalScaleUpCondition + })); + + totalScaleUpCondition++; + args.response.success(); + } + }, + actions: { + destroy: { + label: '', + action: function(args) { + scaleUpData = $.grep(scaleUpData, function(item) { + return item.index != args.context.multiRule[0].index; + }); + totalScaleUpCondition--; + args.response.success(); + } + } + }, + dataProvider: function(args) { + var data = scaleUpData; + var $autoscaler = $('.ui-dialog .autoscaler'); + var initialData = $autoscaler.data('autoscaler-scale-up-data'); + + if ($.isArray(initialData)) { + $(initialData).each(function() { + this.index = totalScaleUpCondition; + totalScaleUpCondition++; + scaleUpData.push(this); + }); + + $autoscaler.data('autoscaler-scale-up-data', null); + } + + args.response.success({ + data: scaleUpData + }); + } + }, + + scaleDownPolicy: { + title: 'ScaleDown Policy', + noSelect: true, + noHeaderActionsColumn: true, + ignoreEmptyFields: true, + fields: { + 'counterid': { + label: 'Counter', + select: function(args) { + $.ajax({ + url: createURL("listCounters"), + dataType: "json", + async: false, + success: function(json) { + var counters = json.counterresponse.counter; + + args.response.success({ + data: $.map(counters, function(counter) { + return { + name: counter.id, + description: counter.name + }; + }) + }); + } + }); + } + }, + 'relationaloperator': { + label: 'Operator', + select: function(args) { + args.response.success({ + data: [ + { name: 'GT', description: 'greater-than' }, + { name: 'GE', description: 'greater-than or equals to' }, + { name: 'LT', description: 'less-than' }, + { name: 'LE', description: 'less-than or equals to' }, + { name: 'EQ', description: 'equals-to' } + ] + }); + } + }, + 'threshold': { edit: true, label: 'Threshold'}, + 'add-scaleDowncondition': { + label: 'label.add', + addButton: true + } + }, + add: { + label: 'label.add', + action: function(args) { + scaleDownData.push($.extend(args.data, { + index: totalScaleDownCondition + })); + totalScaleDownCondition++; + args.response.success(); + } + }, + actions: { + destroy: { + label: '', + action: function(args) { + scaleDownData = $.grep(scaleDownData, function(item) { + return item.index != args.context.multiRule[0].index; + }); + totalScaleDownCondition--; + args.response.success(); + } + } + }, + dataProvider: function(args) { + var data = scaleDownData; + var $autoscaler = $('.ui-dialog .autoscaler'); + var initialData = $autoscaler.data('autoscaler-scale-down-data'); + + if ($.isArray(initialData)) { + $(initialData).each(function() { + this.index = totalScaleDownCondition; + totalScaleDownCondition++; + scaleDownData.push(this); + }); + + $autoscaler.data('autoscaler-scale-down-data', null); + } + + args.response.success({ + data: scaleDownData + }); + } + } + }, + + actions: { + apply: function(args) { + //validation (begin) ***** + if(!('multiRules' in args.context)) { //from a new LB + if(args.formData.name == '' || args.formData.publicport == '' || args.formData.privateport == '') { + args.response.error('Name, Public Port, Private Port of Load Balancing are required. Please close this dialog box and fill Name, Public Port, Private Port first.'); + return; + } + } + else { //from an existing LB + if(args.context.originalAutoscaleData.afterActionIsComplete == null) { + if(args.context.originalAutoscaleData.context.autoscaleVmGroup.state != 'disabled') { + args.response.error('An Autoscale VM Group can be updated only if it is in disabled state. Please disable the Autoscale VM Group first.'); + return; + } + } + else { + if(args.context.originalAutoscaleData.afterActionIsComplete.state != 'disabled') { + args.response.error('An Autoscale VM Group can be updated only if it is in disabled state. Please disable the Autoscale VM Group first.'); + return; + } + } + } + + if(isAdmin() || isDomainAdmin()) { //only admin and domain-admin has access to listUers API + var havingApiKeyAndSecretKey = false; + $.ajax({ + url: createURL('listUsers'), + data: { + id: args.data.username + }, + async: false, + success: function(json) { + if(json.listusersresponse.user[0].apikey != null && json.listusersresponse.user[0].secretkey != null) { + havingApiKeyAndSecretKey = true; + } + } + }); + if(havingApiKeyAndSecretKey == false) { + args.response.error('The selected user in advanced settings does not have API key or secret key'); + return; + } + } + + if(isAdmin()) { //only admin has access to listConfigurations API + var hasValidEndpointeUrl = false; + $.ajax({ + url: createURL('listConfigurations'), + data: { + name: 'endpointe.url' + }, + async: false, + success: function(json) { + if(json.listconfigurationsresponse.configuration != null) { + if(json.listconfigurationsresponse.configuration[0].value.indexOf('localhost') == -1) { + hasValidEndpointeUrl = true; + } + } + } + }); + if(hasValidEndpointeUrl == false) { + args.response.error("Global setting endpointe.url has to be set to the Management Server's API end point"); + return; + } + } + + //Scale Up Policy + if(args.data.scaleUpDuration == null || args.data.scaleUpDuration.length == 0) { + args.response.error("Duration of Scale Up Policy is required."); + return; + } + if(isNaN(args.data.scaleUpDuration)) { + args.response.error("Duration of Scale Up Policy should be a number."); + return; + } + if(parseInt(args.data.scaleUpDuration) < parseInt(args.data.interval)) { + args.response.error("Duration of Scale Up Policy must be greater than or equal to Polling Interval."); + return; + } + if(scaleUpData.length == 0) { + args.response.error("At least one condition is required in Scale Up Policy."); + return; + } + + //Scale Down Policy + if(args.data.scaleDownDuration == null || args.data.scaleDownDuration.length == 0) { + args.response.error("Duration of Scale Down Policy is required."); + return; + } + if(isNaN(args.data.scaleDownDuration)) { + args.response.error("Duration of Scale Down Policy should be a number."); + return; + } + if(parseInt(args.data.scaleDownDuration) < parseInt(args.data.interval)) { + args.response.error("Duration of Scale Down Policy must be greater than or equal to Polling Interval."); + return; + } + if(scaleDownData.length == 0) { + args.response.error("At least one condition is required in Scale Down Policy."); + return; + } + //validation (end) ***** + + var scaleVmProfileResponse = []; + var loadBalancerResponse = []; + var scaleVmGroupResponse = []; + var scaleUpConditionIds = []; + var scaleDownConditionIds = []; + + var scaleUp = function(args){ + var scaleUpConditionIds = []; + $(scaleUpData).each(function(){ + var data = { + counterid: this.counterid, + relationaloperator: this.relationaloperator, + threshold: this.threshold + }; + $.ajax({ + url: createURL('createCondition'), + data: data, + success: function(json) { + var createConditionIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobid=" + json.conditionresponse.jobid), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if(result.jobstatus == 0) { + return; + } + else { + clearInterval(createConditionIntervalID); + if(result.jobstatus == 1) { + var item = json.queryasyncjobresultresponse.jobresult.condition; + scaleUpConditionIds.push(item.id); + if (scaleUpConditionIds.length == scaleUpData.length) { + if(!('multiRules' in args.context)) { //from a new LB + var data = { + action: 'scaleup', + conditionids: scaleUpConditionIds.join(","), + duration: args.data.scaleUpDuration, + quiettime: args.data.quietTime + }; + $.ajax({ + url: createURL('createAutoScalePolicy'), + data: data, + success: function(json) { + var jobId = json.autoscalepolicyresponse.jobid; + var createAutoScalePolicyInterval = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(createAutoScalePolicyInterval); + if (result.jobstatus == 1) { //AutoScalePolicy successfully created + var item = result.jobresult.autoscalepolicy; + scaleDown($.extend(args, { + scaleUpPolicyResponse: item + })); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + else { //from an existing LB + var data = { + id: args.context.originalAutoscaleData.scaleUpPolicy.id, + conditionids: scaleUpConditionIds.join(","), + duration: args.data.scaleUpDuration, + quiettime: args.data.quietTime + }; + + $.ajax({ + url: createURL('updateAutoScalePolicy'), + data: data, + success: function(json) { + var updateAutoScalePolicyInterval = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId=" + json.updateautoscalepolicyresponse.jobid), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(updateAutoScalePolicyInterval); + if (result.jobstatus == 1) { + var item = result.jobresult.autoscalepolicy; + + //delete old conditions which are orphans now. Don't need to call queryAsyncJobResult because subsequent API calls have no dependency on deleteCondition. + $(args.context.originalAutoscaleData.scaleUpPolicy.conditions).each(function(){ + $.ajax({ + url: createURL('deleteCondition'), + data: { + id: this.id + } + }); + }); + + scaleDown($.extend(args, { + scaleUpPolicyResponse: item + })); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + } + } + else if(result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + }); + }; + + var scaleDown = function(args){ + var scaleDownConditionIds = []; + $(scaleDownData).each(function(){ + var data = { + counterid: this.counterid, + relationaloperator: this.relationaloperator, + threshold: this.threshold + }; + $.ajax({ + url: createURL('createCondition'), + data: data, + success: function(json) { + var createConditionIntervalID = setInterval(function() { + $.ajax({ + url: createURL("queryAsyncJobResult&jobid=" + json.conditionresponse.jobid), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if(result.jobstatus == 0) { + return; + } + else { + clearInterval(createConditionIntervalID); + if(result.jobstatus == 1) { + var item = json.queryasyncjobresultresponse.jobresult.condition; + scaleDownConditionIds.push(item.id); + if (scaleDownConditionIds.length == scaleDownData.length) { + if(!('multiRules' in args.context)) { //from a new LB + var data = { + action: 'scaledown', + conditionids: scaleDownConditionIds.join(","), + duration: args.data.scaleDownDuration, + quiettime: args.data.quietTime + }; + $.ajax({ + url: createURL('createAutoScalePolicy'), + data: data, + success: function(json) { + var jobId = json.autoscalepolicyresponse.jobid; + var createAutoScalePolicyInterval = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(createAutoScalePolicyInterval); + if (result.jobstatus == 1) { //AutoScalePolicy successfully created + var item = result.jobresult.autoscalepolicy; + createOrUpdateVmProfile($.extend(args, { + scaleDownPolicyResponse: item + })); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + else { //from an existing LB + var data = { + id: args.context.originalAutoscaleData.scaleDownPolicy.id, + conditionids: scaleDownConditionIds.join(","), + duration: args.data.scaleDownDuration, + quiettime: args.data.quietTime + }; + + $.ajax({ + url: createURL('updateAutoScalePolicy'), + data: data, + success: function(json) { + var jobId = json.updateautoscalepolicyresponse.jobid; + var updateAutoScalePolicyInterval = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(updateAutoScalePolicyInterval); + if (result.jobstatus == 1) { + var item = result.jobresult.autoscalepolicy; + + //delete old conditions which are orphans now. Don't need to call queryAsyncJobResult because subsequent API calls have no dependency on deleteCondition. + $(args.context.originalAutoscaleData.scaleDownPolicy.conditions).each(function(){ + $.ajax({ + url: createURL('deleteCondition'), + data: { + id: this.id + } + }); + }); + + createOrUpdateVmProfile($.extend(args, { + scaleDownPolicyResponse: item + })); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + } + } + else if(result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + }, 3000); + } + }); + }); + }; + + var createOrUpdateVmProfile = function(args){ + var array1 = []; + var apiCmd, apiCmdRes; + if(!('multiRules' in args.context)) { //from a new LB + var data = { + zoneid: args.context.networks[0].zoneid, + serviceofferingid: args.data.serviceOfferingId, + templateid: args.data.templateNames, + destroyvmgraceperiod: args.data.destroyVMgracePeriod, + snmpcommunity: args.data.snmpCommunity, + snmpport: args.data.snmpPort + }; + + var allParamNames=$.map(data,function(value,key){ + return key; + }); + + var notParams =['zoneid','serviceofferingid','templateid','destroyvmgraceperiod']; + var index=0; + $(allParamNames).each(function() { + var param='counterparam[' + index + ']'; + var name = this.toString(); + var value = data[name]; + if(!value || $.inArray(name,notParams) >-1 ) return true; + data[param+ '.name']=name; + data[param+ '.value']=value; + index++; + delete data[name]; + + return true; + }); + + + if(args.data.username != null && args.data.username.length > 0) { + $.extend(data, { + autoscaleuserid: args.data.username + }); + } + + var array2 = []; + if(args.data.diskOfferingId != null && args.data.diskOfferingId.length > 0) + array2.push("diskofferingid=" + args.data.diskOfferingId); + if(args.data.securityGroups != null && args.data.securityGroups.length > 0){ + if(array2.length > 0) + array2.push("&securitygroupids=" + args.data.securityGroups); + else + array2.push("securitygroupids=" + args.data.securityGroups); + } + if(array2.length > 0) { + $.extend(data, { + otherdeployparams: array2.join("") + }); + } + + $.ajax({ + url: createURL('createAutoScaleVmProfile'), + data: data, + success: function(json) { + var jobId = json.autoscalevmprofileresponse.jobid; + var autoscaleVmProfileTimer = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(autoscaleVmProfileTimer); + if (result.jobstatus == 1) { + scaleVmProfileResponse = result.jobresult.autoscalevmprofile; + loadBalancer(args); //create a load balancer rule + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + else { //from an existing LB + var data = { + id: args.context.originalAutoscaleData.context.autoscaleVmProfile.id, + templateid: args.data.templateNames, + destroyvmgraceperiod: args.data.destroyVMgracePeriod, + snmpcommunity: args.data.snmpCommunity, + snmpport: args.data.snmpPort + }; + + var allParamNames=$.map(data,function(value,key){ + return key; + }); + + var notParams =['id','templateid','destroyvmgraceperiod']; + var index=0; + $(allParamNames).each(function() { + var param='counterparam[' + index + ']'; + var name = this.toString(); + var value = data[name]; + if(!value || $.inArray(name,notParams) >-1 ) return true; + data[param+ '.name']=name; + data[param+ '.value']=value; + index++; + delete data[name]; + + return true; + }); + + + + + if(args.data.username != null && args.data.username.length > 0) { + $.extend(data, { + autoscaleuserid: args.data.username + }); + } + + $.ajax({ + url: createURL('updateAutoScaleVmProfile'), + data: data, + success: function(json) { + var jobId = json.updateautoscalevmprofileresponse.jobid; + var autoscaleVmProfileTimer = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(autoscaleVmProfileTimer); + if (result.jobstatus == 1) { + scaleVmProfileResponse = result.jobresult.autoscalevmprofile; + autoScaleVmGroup(args); //update autoScaleVmGroup + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + }; + + var loadBalancer = function(args){ + var networkid; + if('vpc' in args.context) { //from VPC section + if(args.data.tier == null) { + cloudStack.dialog.notice({ message: 'Tier is required' }); + return; + } + networkid = args.data.tier; + } + else if('networks' in args.context) { //from Guest Network section + networkid = args.context.networks[0].id; + } + var data = { + algorithm: args.formData.algorithm, + name: args.formData.name, + privateport: args.formData.privateport, + publicport: args.formData.publicport, + openfirewall: false, + networkid: networkid + }; + if(args.context.ipAddresses != null) { + data = $.extend(data, { + publicipid: args.context.ipAddresses[0].id + }); + } + else { + data = $.extend(data, { + domainid: g_domainid, + account: g_account + }); + } + + $.ajax({ + url: createURL('createLoadBalancerRule'), + dataType: 'json', + data: data, + async: true, + success: function(json) { + var jobId = json.createloadbalancerruleresponse.jobid; + var loadBalancerTimer = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(loadBalancerTimer); + if (result.jobstatus == 1) { //LoadBalancerRule successfully created + loadBalancerResponse = result.jobresult.loadbalancer; + autoScaleVmGroup(args); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + }; + + var autoScaleVmGroup = function(args){ + if(!('multiRules' in args.context)) { //from a new LB + var array1 = []; + array1.push("&lbruleid=" + loadBalancerResponse.id); + array1.push("&minMembers=" + args.data.minInstance); + array1.push("&maxMembers=" + args.data.maxInstance ); + array1.push("&vmprofileid=" + scaleVmProfileResponse.id); + array1.push("&interval=" + args.data.interval); + array1.push("&scaleuppolicyids=" + args.scaleUpPolicyResponse.id); + array1.push("&scaledownpolicyids=" + args.scaleDownPolicyResponse.id ); + $.ajax({ + url: createURL('createAutoScaleVmGroup' + array1.join("")), + dataType: 'json', + async: true, + success: function(json) { + var jobId = json.autoscalevmgroupresponse.jobid; + var scaleVmGroupTimer = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(scaleVmGroupTimer); + if (result.jobstatus == 1) { //autoscale Vm group successfully created + scaleVmGroupResponse = result.jobresult.autoscalevmgroup; + args.response.success(); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + else { //from an existing LB + var data = { + id: args.context.originalAutoscaleData.context.autoscaleVmGroup.id, + minmembers: args.data.minInstance, + maxmembers: args.data.maxInstance, + interval: args.data.interval, + scaleuppolicyids: args.context.originalAutoscaleData.scaleUpPolicy.id, + scaledownpolicyids: args.context.originalAutoscaleData.scaleDownPolicy.id + }; + + $.ajax({ + url: createURL('updateAutoScaleVmGroup'), + data: data, + success: function(json) { + var jobId = json.updateautoscalevmgroupresponse.jobid; + var updateAutoScaleVmGroupTimer = setInterval(function(){ + $.ajax({ + url: createURL("queryAsyncJobResult&jobId="+jobId), + dataType: "json", + success: function(json) { + var result = json.queryasyncjobresultresponse; + if (result.jobstatus == 0) { + return; //Job has not completed + } + else { + clearInterval(updateAutoScaleVmGroupTimer); + if (result.jobstatus == 1) { //autoscale Vm group successfully created + args.response.success(); + } + else if (result.jobstatus == 2) { + args.response.error(_s(result.jobresult.errortext)); + } + } + } + }); + }, 3000); + }, + error: function(XMLHttpResponse) { + args.response.error(parseXMLHttpResponse(XMLHttpResponse)); + } + }); + } + }; + + //*** API calls start!!! ******** + scaleUp(args); + + }, + destroy: function(args) { + $.ajax({ + url: createURL('') + }); + } + }, + + dialog: function(args) { + return function(args) { + var context = args.context; + + var $dialog= $('
      '); + $dialog.dialog ({ + title: 'AutoScale Configuration Wizard', + closeonEscape: false, + + draggable:true, + width: 825 , + height :600, + buttons: { + 'Cancel': function() { + $(this).dialog("close"); + $('.overlay').remove(); + }, + + + 'Apply': function() { + $(':ui-dialog').remove(); + $('.overlay').remove(); + } + } + }).closest('.ui-dialog').overlay(); + + $("buttons").each(function() { + $(this).attr('style','float: right'); + }); + var $field = $('
      ').addClass('field username'); + var $input = $('').attr({ name: 'username' }); + var $inputLabel = $('