From aa49f9f98b4abdc33a26147f54903865bfc583a2 Mon Sep 17 00:00:00 2001 From: Chiradeep Vittal Date: Mon, 23 Aug 2010 18:40:06 -0700 Subject: [PATCH 001/235] Initial checkin of systemvm builder for debian-based systemvm --- tools/systemvm/buildsystemvm.sh | 293 ++++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100755 tools/systemvm/buildsystemvm.sh diff --git a/tools/systemvm/buildsystemvm.sh b/tools/systemvm/buildsystemvm.sh new file mode 100755 index 00000000000..63ce5c89fe7 --- /dev/null +++ b/tools/systemvm/buildsystemvm.sh @@ -0,0 +1,293 @@ +#!/bin/bash + +IMAGENAME=systemvm +LOCATION=/var/lib/images/systemvm2 +PASSWORD=password +APT_PROXY= +HOSTNAME=systemvm +SIZE=2000 +DEBIAN_MIRROR=ftp.us.debian.org/debian + +baseimage() { + mkdir -p $LOCATION + dd if=/dev/zero of=$IMAGELOC bs=1M seek=$((SIZE - 1)) count=1 + loopdev=$(losetup -f) + losetup $loopdev $IMAGELOC + parted $loopdev -s 'mklabel msdos' + parted $loopdev -s 'mkpart primary ext3 512B 2097151000B' + losetup -d $loopdev + loopdev=$(losetup --show -o 512 -f $IMAGELOC ) + mkfs.ext3 -L ROOT $loopdev + mkdir -p $MOUNTPOINT + tune2fs -c 100 -i 0 $loopdev + losetup -d $loopdev + + mount -o loop,offset=512 $IMAGELOC $MOUNTPOINT + + #debootstrap --variant=minbase --keyring=/usr/share/keyrings/debian-archive-keyring.gpg squeeze $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR} + debootstrap --variant=minbase --arch=i386 squeeze $MOUNTPOINT http://${APT_PROXY}${DEBIAN_MIRROR} +} + + +fixapt() { + if [ "$APT_PROXY" != "" ]; then + cat >> etc/apt/apt.conf.d/01proxy << EOF +Acquire::http::Proxy "http://${APT_PROXY}"; +EOF + fi + + cat > etc/apt/sources.list << EOF +deb http://ftp.us.debian.org/debian/ squeeze main non-free +deb-src http://ftp.us.debian.org/debian/ squeeze main non-free + +deb http://security.debian.org/ squeeze/updates main +deb-src http://security.debian.org/ squeeze/updates main + +deb http://volatile.debian.org/debian-volatile squeeze/volatile main +deb-src http://volatile.debian.org/debian-volatile squeeze/volatile main + +deb http://ftp.us.debian.org/debian testing main contrib non-free +EOF + + cat >> etc/apt/apt.conf << EOF +APT::Default-Release "stable"; +EOF + + cat >> etc/apt/preferences << EOF +Package: * +Pin: release o=Debian,a=stable +Pin-Priority: 900 + +Package: * +Pin: release o=Debian,a=testing +Pin-Priority: 400 +EOF + + #apt-key exportall | chroot . apt-key add - && + chroot . apt-get update && + echo "Apt::Install-Recommends 0;" > etc/apt/apt.conf.d/local-recommends + + cat >> usr/sbin/policy-rc.d << EOF +#!/bin/sh +exit 101 +EOF + chmod a+x usr/sbin/policy-rc.d + + cat >> etc/default/locale << EOF +LANG=en_US.UTF-8 +LC_ALL=en_US.UTF-8 +EOF + + cat >> etc/locale.gen << EOF +en_US.UTF-8 UTF-8 +EOF + + DEBIAN_FRONTEND=noninteractive + DEBIAN_PRIORITY=critical + export DEBIAN_FRONTEND DEBIAN_PRIORITY + chroot . dpkg-reconfigure debconf --frontend=noninteractive + chroot . apt-get -q -y install locales +} + +network() { + + echo "$HOSTNAME" > etc/hostname && + cat > etc/hosts << EOF +127.0.0.1 localhost +# The following lines are desirable for IPv6 capable hosts +::1 localhost ip6-localhost ip6-loopback +fe00::0 ip6-localnet +ff00::0 ip6-mcastprefix +ff02::1 ip6-allnodes +ff02::2 ip6-allrouters +ff02::3 ip6-allhosts +EOF + + cat >> etc/network/interfaces << EOF +auto lo +iface lo inet loopback + +# The primary network interface +allow-hotplug eth0 +iface eth0 inet dhcp + +EOF +} + +install_kernel() { + DEBIAN_FRONTEND=noninteractive + DEBIAN_PRIORITY=critical + export DEBIAN_FRONTEND DEBIAN_PRIORITY + + chroot . apt-get -qq -y --force-yes install grub && + cp -av usr/lib/grub/i386-pc boot/grub + #for some reason apt-get install grub does not install grub/stage1 etc + loopd=$(losetup -f --show $1) + grub-install $loopd --root-directory=$MOUNTPOINT + losetup -d $loopd + grub << EOF && +device (hd0) $1 +root (hd0,0) +setup (hd0) +quit +EOF + # install a kernel image + cat > etc/kernel-img.conf << EOF && +do_symlinks = yes +link_in_boot = yes +do_initrd = yes +EOF + chroot . apt-get install -qq -y --force-yes linux-image-686-bigmem + cat >> etc/kernel-img.conf << EOF +postinst_hook = /usr/sbin/update-grub +postrm_hook = /usr/sbin/update-grub +EOF +} + + +fixgrub() { + cat > boot/grub/menu.lst << EOF +default 0 +timeout 2 +color cyan/blue white/blue + +### BEGIN AUTOMAGIC KERNELS LIST +# kopt=root=LABEL=ROOT ro + +## ## End Default Options ## +title Debian GNU/Linux, kernel 2.6.32-5-686-bigmem +root (hd0,0) +kernel /boot/vmlinuz-2.6.32-5-686-bigmem root=LABEL=ROOT ro console=tty0 xencons=ttyS0,115200 console=hvc0 quiet +initrd /boot/initrd.img-2.6.32-5-686-bigmem + +### END DEBIAN AUTOMAGIC KERNELS LIST +EOF + (cd boot/grub; ln -s menu.lst grub.conf) +} + +fixinittab() { + cat >> etc/inittab << EOF + +vc:2345:respawn:/sbin/getty 38400 hvc0 +EOF +} + +fixfstab() { + cat > etc/fstab << EOF +# +proc /proc proc defaults 0 0 +LABEL=ROOT / ext3 errors=remount-ro 0 1 +EOF +} + +fixacpid() { + cat >> etc/acpi/events/power << EOF +event=button/power.* +action=/usr/local/sbin/power.sh "%e" +EOF + cat >> usr/local/sbin/power.sh << EOF +#!/bin/bash +/sbin/poweroff +EOF + chmod a+x usr/local/sbin/power.sh +} + +packages() { + DEBIAN_FRONTEND=noninteractive + DEBIAN_PRIORITY=critical + DEBCONF_DB_OVERRIDE=’File{/root/config.dat}’ + export DEBIAN_FRONTEND DEBIAN_PRIORITY DEBCONF_DB_OVERRIDE + + chroot . apt-get --no-install-recommends -q -y --force-yes install rsyslog chkconfig insserv net-tools ifupdown vim netbase iptables openssh-server grub e2fsprogs dhcp3-client dnsmasq tcpdump socat wget apache2 python2.5 bzip2 sed gawk diff grep gzip less tar telnet xl2tpd traceroute openswan psmisc + + chroot . apt-get --no-install-recommends -q -y --force-yes -t backports install haproxy nfs-common + + echo "***** getting additional modules *********" + chroot . apt-get --no-install-recommends -q -y --force-yes install iproute acpid iptables-persistent + + echo "***** getting sun jre 6*********" + DEBIAN_FRONTEND=readline + export DEBIAN_FRONTEND + chroot . echo sun-java6-jdk shared/accepted-sun-dlj-v1-1 boolean true | debconf-set-selections + chroot . apt-get --no-install-recommends -q -y install sun-java6-jre + +} + +password() { + chroot . echo "root:$PASSWORD" | chroot . chpasswd +} + +cleanup() { + rm -f usr/sbin/policy-rc.d + rm -f etc/apt/apt.conf.d/01proxy +} + +mkdir -p $IMAGENAME +mkdir -p $LOCATION +MOUNTPOINT=/mnt/$IMAGENAME/ +IMAGELOC=$LOCATION/$IMAGENAME.img +scriptdir=$(dirname $PWD/$0) + +rm -f $IMAGELOC + +echo "*************INSTALLING BASEIMAGE********************" +baseimage + +cp $scriptdir/config.dat $MOUNTPOINT/root/ +cd $MOUNTPOINT + +mount -o bind /proc $MOUNTPOINT/proc +mount -o bind /dev $MOUNTPOINT/dev + +echo "*************CONFIGURING APT********************" +fixapt +echo "*************DONE CONFIGURING APT********************" + +echo "*************CONFIGURING NETWORK********************" +network +echo "*************DONE CONFIGURING NETWORK********************" + +echo "*************INSTALLING KERNEL********************" +install_kernel $IMAGELOC +echo "*************DONE INSTALLING KERNEL********************" + +echo "*************CONFIGURING GRUB********************" +fixgrub $IMAGELOC +echo "*************DONE CONFIGURING GRUB********************" + + +echo "*************CONFIGURING INITTAB********************" +fixinittab +echo "*************DONE CONFIGURING INITTAB********************" + +echo "*************CONFIGURING FSTAB********************" +fixfstab +echo "*************DONE CONFIGURING FSTAB********************" + +echo "*************CONFIGURING ACPID********************" +fixacpid +echo "*************DONE CONFIGURING ACPID********************" + +#cp etc/inittab etc/inittab.hvm +#cp $scriptdir/inittab.xen etc/inittab.xen +#cp $scriptdir/inittab.xen etc/inittab +#cp $scriptdir/fstab.xen etc/fstab.xen +#cp $scriptdir/fstab.xen etc/fstab +#cp $scriptdir/fstab etc/fstab + +echo "*************INSTALLING PACKAGES********************" +packages +echo "*************DONE INSTALLING PACKAGES********************" + +echo "*************CONFIGURING PASSWORD********************" +password + +echo "*************CLEANING UP********************" +cleanup + +cd $scriptdir + +umount $MOUNTPOINT/proc +umount $MOUNTPOINT/dev +umount $MOUNTPOINT + From 49900a8985ba7ba660db77bdb9e956f6b1599195 Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Tue, 24 Aug 2010 18:58:38 -0700 Subject: [PATCH 002/235] 1) Add VMDK format 2) Make console proxy servlet explictly return content-type header for console proxy page (this is a bug fix change) --- api/src/com/cloud/storage/Storage.java | 3 ++- server/src/com/cloud/servlet/ConsoleProxyServlet.java | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index 106616673b3..24ceb5b3fec 100644 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -22,7 +22,8 @@ public class Storage { QCOW2(true, true, false), RAW(false, false, false), VHD(true, true, true), - ISO(false, false, false); + ISO(false, false, false), + VMDK(true, true, true); private final boolean thinProvisioned; private final boolean supportSparse; diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 851860f8a04..03372cbd82a 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -281,7 +281,7 @@ public class ConsoleProxyServlet extends HttpServlet { } private void sendResponse(HttpServletResponse resp, String content) { - try { + try { resp.getWriter().print(content); } catch(IOException e) { if(s_logger.isInfoEnabled()) From 45cb68e7e2861efc613cf0fb037c24698b5252ba Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Tue, 24 Aug 2010 22:58:05 -0700 Subject: [PATCH 003/235] add templates.vmware.sql modify build to deploy vmware database records --- build/developer.xml | 9 ++++++++- server/src/com/cloud/servlet/ConsoleProxyServlet.java | 1 + setup/db/templates.xenserver.sql | 2 -- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/build/developer.xml b/build/developer.xml index 0928e48dfd6..77d760b2af7 100755 --- a/build/developer.xml +++ b/build/developer.xml @@ -169,11 +169,18 @@ + + + - + + + + + diff --git a/server/src/com/cloud/servlet/ConsoleProxyServlet.java b/server/src/com/cloud/servlet/ConsoleProxyServlet.java index 03372cbd82a..2c364122854 100644 --- a/server/src/com/cloud/servlet/ConsoleProxyServlet.java +++ b/server/src/com/cloud/servlet/ConsoleProxyServlet.java @@ -282,6 +282,7 @@ public class ConsoleProxyServlet extends HttpServlet { private void sendResponse(HttpServletResponse resp, String content) { try { + resp.setContentType("text/html"); resp.getWriter().print(content); } catch(IOException e) { if(s_logger.isInfoEnabled()) diff --git a/setup/db/templates.xenserver.sql b/setup/db/templates.xenserver.sql index 5ecd912f575..0432c97716f 100644 --- a/setup/db/templates.xenserver.sql +++ b/setup/db/templates.xenserver.sql @@ -72,6 +72,4 @@ INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (58, INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (59, 7, 'Other install media', 'Ubuntu'); INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (60, 7, 'Other install media', 'Other'); --- temporarily added for vmware, will be moved when vmware support is fully in-place -INSERT INTO `cloud`.`host_master`(`type`, `service_address`, `admin`, `password`) VALUES('VSphere', 'vsphere-1.lab.vmops.com', 'Administrator', 'Suite219'); From e3af2edc1d4f8ee162d658348b544c6e4aacb28c Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Wed, 25 Aug 2010 09:48:31 -0700 Subject: [PATCH 004/235] add vmware DB initial sql scripts for templates and guest OSes --- setup/db/templates.vmware.sql | 82 +++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 setup/db/templates.vmware.sql diff --git a/setup/db/templates.vmware.sql b/setup/db/templates.vmware.sql new file mode 100644 index 00000000000..cc9ac751b5b --- /dev/null +++ b/setup/db/templates.vmware.sql @@ -0,0 +1,82 @@ +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) + VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '31cd7ce94fe68c973d5dc37c3349d02e', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); +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) + VALUES (2, 'fedora11-x86', 'Fedora 11 x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); + +INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'Windows'); +INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Linux'); +INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (3, 'Novell Netware'); +INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (4, 'Solaris'); +INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (5, 'Other'); + +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (1, 1, 'Microsoft Windows 7(32-bit)', 'Microsoft Windows 7(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (2, 1, 'Microsoft Windows 7(64-bit)', 'Microsoft Windows 7(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (3, 1, 'Microsoft Windows Server 2008 R2(64-bit)', 'Microsoft Windows Server 2008 R2(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (4, 1, 'Microsoft Windows Server 2008(32-bit)', 'Microsoft Windows Server 2008(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (5, 1, 'Microsoft Windows Server 2008(64-bit)', 'Windows Windows Server 2008(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (6, 1, 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (7, 1, 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)', 'Microsoft Windows Server 2003, Enterprise Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (8, 1, 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (9, 1, 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)', 'Microsoft Windows Server 2003, Datacenter Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (10, 1, 'Microsoft Windows Server 2003, Standard Edition (32-bit)', 'Microsoft Windows Server 2003, Standard Edition (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (11, 1, 'Microsoft Windows Server 2003, Standard Edition (64-bit)', 'Microsoft Windows Server 2003, Standard Edition (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (12, 1, 'Microsoft Windows Server 2003, Web Edition', 'Microsoft Windows Server 2003, Web Edition'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (13, 1, 'Microsoft Small Bussiness Server 2003', 'Microsoft Small Bussiness Server 2003'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (14, 1, 'Microsoft Windows Vista (32-bit)', 'Microsoft Windows Vista (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (15, 1, 'Microsoft Windows Vista (64-bit)', 'Microsoft Windows Vista (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (16, 1, 'Microsoft Windows XP Professional (32-bit)', 'Microsoft Windows XP Professional (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (17, 1, 'Microsoft Windows XP Professional (64-bit)', 'Microsoft Windows XP Professional (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (18, 1, 'Microsoft Windows 2000 Advanced Server', 'Microsoft Windows 2000 Advanced Server'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (19, 1, 'Microsoft Windows 2000 Server', 'Microsoft Windows 2000 Server'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (20, 1, 'Microsoft Windows 2000 Professional', 'Microsoft Windows 2000 Professional'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (21, 1, 'Microsoft Windows 98', 'Microsoft Windows 98'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (22, 1, 'Microsoft Windows 95', 'Microsoft Windows 95'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (23, 1, 'Microsoft Windows NT 4', 'Microsoft Windows NT 4'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (24, 1, 'Microsoft Windows 3.1', 'Microsoft Windows 3.1'); + +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (25, 2, 'Red Hat Enterprise Linux 5(32-bit)', 'Red Hat Enterprise Linux 5(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (26, 2, 'Red Hat Enterprise Linux 5(64-bit)', 'Red Hat Enterprise Linux 5(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (27, 2, 'Red Hat Enterprise Linux 4(32-bit)', 'Red Hat Enterprise Linux 4(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (28, 2, 'Red Hat Enterprise Linux 4(64-bit)', 'Red Hat Enterprise Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (29, 2, 'Red Hat Enterprise Linux 3(32-bit)', 'Red Hat Enterprise Linux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (30, 2, 'Red Hat Enterprise Linux 3(64-bit)', 'Red Hat Enterprise Linux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (31, 2, 'Red Hat Enterprise Linux 2', 'Red Hat Enterprise Linux 2'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (32, 2, 'Suse Linux Enterprise 11(32-bit)', 'Suse Linux Enterprise 11(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (33, 2, 'Suse Linux Enterprise 11(64-bit)', 'Suse Linux Enterprise 11(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (34, 2, 'Suse Linux Enterprise 10(32-bit)', 'Suse Linux Enterprise 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (35, 2, 'Suse Linux Enterprise 10(64-bit)', 'Suse Linux Enterprise 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (36, 2, 'Suse Linux Enterprise 8/9(32-bit)', 'Suse Linux Enterprise 8/9(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (37, 2, 'Suse Linux Enterprise 8/9(64-bit)', 'Suse Linux Enterprise 8/9(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (38, 2, 'Open Enterprise Server', 'Open Enterprise Server'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (39, 2, 'Asianux 3(32-bit)', 'Asianux 3(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (40, 2, 'Asianux 3(64-bit)', 'Asianux 3(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (41, 2, 'Debian GNU/Linux 5(32-bit)', 'Debian GNU/Linux 5(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (42, 2, 'Debian GNU/Linux 5(64-bit)', 'Debian GNU/Linux 5(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (43, 2, 'Debian GNU/Linux 4(32-bit)', 'Debian GNU/Linux 4(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (44, 2, 'Debian GNU/Linux 4(64-bit)', 'Debian GNU/Linux 4(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (45, 2, 'Ubuntu Linux (32-bit)', 'Ubuntu Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (46, 2, 'Ubuntu Linux (64-bit)', 'Ubuntu Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (47, 2, 'Other 2.6x Linux (32-bit)', 'Other 2.6x Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (48, 2, 'Other 2.6x Linux (64-bit)', 'Other 2.6x Linux (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (49, 2, 'Other Linux (32-bit)', 'Other Linux (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (50, 2, 'Other Linux (64-bit)', 'Other Linux (64-bit)'); + +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (51, 3, 'Novell Netware 6.x', 'Novell Netware 6.x'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (52, 3, 'Novell Netware 5.1', 'Novell Netware 5.1'); + +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (53, 4, 'Sun Solaris 10(32-bit)', 'Sun Solaris 10(32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (54, 4, 'Sun Solaris 10(64-bit)', 'Sun Solaris 10(64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (55, 4, 'Sun Solaris 9(Experimental)', 'Sun Solaris 9(Experimental)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (56, 4, 'Sun Solaris 8(Experimental)', 'Sun Solaris 8(Experimental)'); + +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (57, 5, 'FreeBSD (32-bit)', 'FreeBSD (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (58, 5, 'FreeBSD (64-bit)', 'FreeBSD (64-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (59, 5, 'OS/2', 'OS/2'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (60, 5, 'SCO OpenServer 5', 'SCO OpenServer 5'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (61, 5, 'SCO UnixWare 7', 'SCO UnixWare 7'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (62, 5, 'DOS', 'DOS'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (63, 5, 'Other (32-bit)', 'Other (32-bit)'); +INSERT INTO `cloud`.`guest_os` (id, category_id, name, display_name) VALUES (64, 5, 'Other (64-bit)', 'Other (64-bit)'); + +-- temporarily added for vmware, will be moved when vmware support is fully in-place +INSERT INTO `cloud`.`host_master`(`type`, `service_address`, `admin`, `password`) VALUES('VSphere', 'vsphere-1.lab.vmops.com', 'Administrator', 'Suite219'); From 0682d70ce60aab521220a80bb1d1fdf2ac7b990f Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Wed, 25 Aug 2010 11:07:27 -0700 Subject: [PATCH 005/235] add correct check sum to default vmware template records Let StoragePoolMonitor be aware of vmware hypervisor --- server/src/com/cloud/storage/StorageManagerImpl.java | 4 ++++ server/src/com/cloud/storage/listener/StoragePoolMonitor.java | 3 ++- setup/db/templates.vmware.sql | 4 ++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index 99c13301707..d3f2156f79d 100644 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -1062,6 +1062,8 @@ public class StorageManagerImpl implements StorageManager { String hypervisoType = configDao.getValue("hypervisor.type"); if (hypervisoType.equalsIgnoreCase("KVM")) { _hypervisorType = Hypervisor.Type.KVM; + } else if(hypervisoType.equalsIgnoreCase("vmware")) { + _hypervisorType = Hypervisor.Type.VmWare; } _agentMgr.registerForHostEvents(new StoragePoolMonitor(this, _hostDao, _storagePoolDao), true, false, true); @@ -1256,6 +1258,8 @@ public class StorageManagerImpl implements StorageManager { if (hypervisorType == null) { if (_hypervisorType == Hypervisor.Type.KVM) { hypervisorType = Hypervisor.Type.KVM; + } else if(_hypervisorType == Hypervisor.Type.VmWare) { + hypervisorType = Hypervisor.Type.VmWare; } else { s_logger.debug("Couldn't find a host to serve in the server pool"); return null; diff --git a/server/src/com/cloud/storage/listener/StoragePoolMonitor.java b/server/src/com/cloud/storage/listener/StoragePoolMonitor.java index b66ffe2a374..7017ed83c2a 100755 --- a/server/src/com/cloud/storage/listener/StoragePoolMonitor.java +++ b/server/src/com/cloud/storage/listener/StoragePoolMonitor.java @@ -70,7 +70,8 @@ public class StoragePoolMonitor implements Listener { public boolean processConnect(HostVO host, StartupCommand cmd) { if (cmd instanceof StartupRoutingCommand) { StartupRoutingCommand scCmd = (StartupRoutingCommand)cmd; - if (scCmd.getHypervisorType() == Hypervisor.Type.XenServer || scCmd.getHypervisorType() == Hypervisor.Type.KVM) { + if (scCmd.getHypervisorType() == Hypervisor.Type.XenServer || scCmd.getHypervisorType() == Hypervisor.Type.KVM || + scCmd.getHypervisorType() == Hypervisor.Type.VmWare) { List pools = _poolDao.listBy(host.getDataCenterId(), host.getPodId(), host.getClusterId()); for (StoragePoolVO pool : pools) { Long hostId = host.getId(); diff --git a/setup/db/templates.vmware.sql b/setup/db/templates.vmware.sql index cc9ac751b5b..572e42107a9 100644 --- a/setup/db/templates.vmware.sql +++ b/setup/db/templates.vmware.sql @@ -1,7 +1,7 @@ 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) - VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '31cd7ce94fe68c973d5dc37c3349d02e', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); + VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); 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) - VALUES (2, 'fedora11-x86', 'Fedora 11 x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', 'b63d854a9560c013142567bbae8d98cf', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); + VALUES (2, 'fedora11-x86', 'Fedora 11 x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'Windows'); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Linux'); From 63ebb004346ec25ae6c65c80b9462fd3e536025d Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Wed, 25 Aug 2010 11:59:18 -0700 Subject: [PATCH 006/235] Add VMDK processor for template processing at secondary storage --- .../storage/template/DownloadManagerImpl.java | 5 ++ .../cloud/storage/template/VmdkProcessor.java | 67 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 core/src/com/cloud/storage/template/VmdkProcessor.java diff --git a/core/src/com/cloud/storage/template/DownloadManagerImpl.java b/core/src/com/cloud/storage/template/DownloadManagerImpl.java index 2ec957a6d8a..8d41e293e6a 100644 --- a/core/src/com/cloud/storage/template/DownloadManagerImpl.java +++ b/core/src/com/cloud/storage/template/DownloadManagerImpl.java @@ -781,6 +781,11 @@ public class DownloadManagerImpl implements DownloadManager { processor = new QCOW2Processor(); processor.configure("QCOW2 Processor", params); processors.add(processor); + + processor = new VmdkProcessor(); + processor.configure("VMDK Processor", params); + processors.add(processor); + // Add more processors here. threadPool = Executors.newFixedThreadPool(numInstallThreads); return true; diff --git a/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java new file mode 100644 index 00000000000..b8d037c3538 --- /dev/null +++ b/core/src/com/cloud/storage/template/VmdkProcessor.java @@ -0,0 +1,67 @@ +package com.cloud.storage.template; + +import java.io.File; +import java.util.Map; + +import javax.naming.ConfigurationException; + +import org.apache.log4j.Logger; + +import com.cloud.exception.InternalErrorException; +import com.cloud.storage.StorageLayer; +import com.cloud.storage.Storage.ImageFormat; + +public class VmdkProcessor implements Processor { + private static final Logger s_logger = Logger.getLogger(VmdkProcessor.class); + + String _name; + StorageLayer _storage; + + @Override + public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { + if (format != null) { + s_logger.debug("We currently don't handle conversion from " + format + " to VMDK."); + return null; + } + + s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); + String templateFilePath = templatePath + File.separator + templateName + ".tar.bz2"; + if (!_storage.exists(templateFilePath)) { + s_logger.debug("Unable to find the vmware template file: " + templateFilePath); + return null; + } + + FormatInfo info = new FormatInfo(); + info.format = ImageFormat.VMDK; + info.filename = templateName + ".tar.bz2"; + info.size = _storage.getSize(templateFilePath); + info.virtualSize = info.size; + return info; + } + + @Override + public boolean configure(String name, Map params) throws ConfigurationException { + _name = name; + _storage = (StorageLayer)params.get(StorageLayer.InstanceConfigKey); + if (_storage == null) { + throw new ConfigurationException("Unable to get storage implementation"); + } + + return true; + } + + @Override + public String getName() { + return _name; + } + + @Override + public boolean start() { + return true; + } + + @Override + public boolean stop() { + return true; + } +} From 4fe1d8f335d909f1fc378256066aa5c3d89dc189 Mon Sep 17 00:00:00 2001 From: edison Date: Wed, 25 Aug 2010 12:25:05 -0700 Subject: [PATCH 007/235] add a web-based Ip Allocator: In external-ip mode, management server can get user VM's ip from direct.attach.network.externalIpAllocator.url. This simple tool provides such kind of ip allocator service. How to: 1. setup the dnsmasq: add the following in dnsmasq.conf: dhcp-range=starting-ip-allocate-to-vm,end-ip,netmask,static dhcp-option=option:router,gateway 2. run cloud-web-ipallocator, The default listing port is 8080, if it's used by others, change the port by: cloud-web-ipallocator other-port 3. set the following in direct.attach.network.externalIpAllocator.url: http://your-host-ip:listening-port/ipallocator --- python/bindir/cloud-web-ipallocator.in | 136 +++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100755 python/bindir/cloud-web-ipallocator.in diff --git a/python/bindir/cloud-web-ipallocator.in b/python/bindir/cloud-web-ipallocator.in new file mode 100755 index 00000000000..3a278d29e56 --- /dev/null +++ b/python/bindir/cloud-web-ipallocator.in @@ -0,0 +1,136 @@ +#! /usr/bin/python +import web +import socket, struct +import cloud_utils +from cloud_utils import Command +urls = ("/ipallocator", "ipallocator") +app = web.application(urls, globals()) + +augtool = Command("augtool") +service = Command("service") +class dhcp: + _instance = None + def __init__(self): + self.availIP=[] + self.router=None + self.netmask=None + self.initialized=False + + options = augtool.match("/files/etc/dnsmasq.conf/dhcp-option").stdout.strip() + for option in options.splitlines(): + if option.find("option:router") != -1: + self.router = option.split("=")[1].strip().split(",")[1] + print self.router + + dhcp_range = augtool.get("/files/etc/dnsmasq.conf/dhcp-range").stdout.strip() + dhcp_start = dhcp_range.split("=")[1].strip().split(",")[0] + dhcp_end = dhcp_range.split("=")[1].strip().split(",")[1] + self.netmask = dhcp_range.split("=")[1].strip().split(",")[2] + print dhcp_start, dhcp_end, self.netmask + + start_ip_num = self.ipToNum(dhcp_start); + end_ip_num = self.ipToNum(dhcp_end) + print start_ip_num, end_ip_num + + for ip in range(start_ip_num, end_ip_num + 1): + self.availIP.append(ip) + print self.availIP[0], self.availIP[len(self.availIP) - 1] + + #load the ip already allocated + self.reloadAllocatedIP() + + def ipToNum(self, ip): + return struct.unpack("!I", socket.inet_aton(ip))[0] + + def numToIp(self, num): + return socket.inet_ntoa(struct.pack('!I', num)) + + def getFreeIP(self): + if len(self.availIP) > 0: + ip = self.numToIp(self.availIP[0]) + self.availIP.remove(self.availIP[0]) + return ip + else: + return None + + def getNetmask(self): + return self.netmask + + def getRouter(self): + return self.router + + def getInstance(): + if not dhcp._instance: + dhcp._instance = dhcp() + return dhcp._instance + getInstance = staticmethod(getInstance) + + def reloadAllocatedIP(self): + dhcp_hosts = augtool.match("/files/etc/dnsmasq.conf/dhcp-host").stdout.strip().splitlines() + + for host in dhcp_hosts: + if host.find("dhcp-host") != -1: + allocatedIP = self.ipToNum(host.split("=")[1].strip().split(",")[1]) + if allocatedIP in self.availIP: + self.availIP.remove(allocatedIP) + + def allocateIP(self, mac): + newIP = self.getFreeIP() + dhcp_host = augtool.match("/files/etc/dnsmasq.conf/dhcp-host").stdout.strip() + cnt = len(dhcp_host.splitlines()) + 1 + script = """set %s %s + save"""%("/files/etc/dnsmasq.conf/dhcp-host[" + str(cnt) + "]", str(mac) + "," + newIP) + augtool < script + #reset dnsmasq + service("dnsmasq", "restart", stdout=None, stderr=None) + return newIP + + def releaseIP(self, ip): + dhcp_host = augtool.match("/files/etc/dnsmasq.conf/dhcp-host").stdout.strip() + path = None + for host in dhcp_host.splitlines(): + if host.find(ip) != -1: + path = host.split("=")[0].strip() + + if path == None: + print "Can't find " + str(ip) + " in conf file" + return None + + print path + script = """rm %s + save"""%(path) + augtool < script + + #reset dnsmasq + service("dnsmasq", "restart", stdout=None, stderr=None) + +class ipallocator: + def GET(self): + try: + user_data = web.input() + command = user_data.command + print "Processing: " + command + + dhcpInit = dhcp.getInstance() + + if command == "getIpAddr": + mac = user_data.mac + zone_id = user_data.dc + pod_id = user_data.pod + print mac, zone_id, pod_id + freeIP = dhcpInit.allocateIP(mac) + if not freeIP: + return "0,0,0" + print "Find an available IP: " + freeIP + + return freeIP + "," + dhcpInit.getNetmask() + "," + dhcpInit.getRouter() + elif command == "releaseIpAddr": + ip = user_data.ip + zone_id = user_data.dc + pod_id = user_data.pod + dhcpInit.releaseIP(ip) + except: + return None + +if __name__ == "__main__": + app.run() From 0a35a8120ddacff63127fce9b24e326f104efef0 Mon Sep 17 00:00:00 2001 From: edison Date: Mon, 16 Aug 2010 19:35:08 -0700 Subject: [PATCH 008/235] Oh, why there is so many un-compatible libvirt... --- .../computing/LibvirtComputingResource.java | 21 ++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index 574b3669113..fdc050d7cca 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -1189,10 +1189,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv s_logger.debug(result); return new CreateAnswer(cmd, result); } + + vol = createVolume(primaryPool, tmplVol); - LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(UUID.randomUUID().toString(), tmplVol.getInfo().capacity, volFormat.QCOW2, tmplVol.getPath(), volFormat.QCOW2); - s_logger.debug(volDef.toString()); - vol = primaryPool.storageVolCreateXML(volDef.toString(), 0); if (vol == null) { return new Answer(cmd, false, " Can't create storage volume on storage pool"); } @@ -3502,6 +3501,22 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } } + private StorageVol createVolume(StoragePool destPool, StorageVol tmplVol) throws LibvirtException { + if (isCentosHost()) { + LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(UUID.randomUUID().toString(), tmplVol.getInfo().capacity, volFormat.QCOW2, null, null); + s_logger.debug(volDef.toString()); + StorageVol vol = destPool.storageVolCreateXML(volDef.toString(), 0); + + /*create qcow2 image based on the name*/ + Script.runSimpleBashScript("qemu-img create -f qcow2 -b " + tmplVol.getPath() + " " + vol.getPath() ); + return vol; + } else { + LibvirtStorageVolumeDef volDef = new LibvirtStorageVolumeDef(UUID.randomUUID().toString(), tmplVol.getInfo().capacity, volFormat.QCOW2, tmplVol.getPath(), volFormat.QCOW2); + s_logger.debug(volDef.toString()); + return destPool.storageVolCreateXML(volDef.toString(), 0); + } + } + private StorageVol getVolume(StoragePool pool, String volKey) { StorageVol vol = null; try { From 398d38b38c83579452e92ec817396189536b84ab Mon Sep 17 00:00:00 2001 From: edison Date: Tue, 17 Aug 2010 16:48:46 -0700 Subject: [PATCH 009/235] rename qemu-kvm to cloud-qemu-system* --- .../agent/resource/computing/LibvirtComputingResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index fdc050d7cca..755a739448d 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -2941,9 +2941,9 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } private String getHypervisorPath() { - File f =new File("/usr/bin/cloud-qemu-kvm"); + File f =new File("/usr/bin/cloud-qemu-system-x86_64"); if (f.exists()) { - return "/usr/bin/cloud-qemu-kvm"; + return "/usr/bin/cloud-qemu-system-x86_64"; } else { if (_conn == null) return null; From 867b49edb6401ba9a5639e524630586f81e07822 Mon Sep 17 00:00:00 2001 From: edison Date: Tue, 17 Aug 2010 16:52:52 -0700 Subject: [PATCH 010/235] Don't install console proxy agent on agent --- scripts/vm/hypervisor/kvm/setup_agent.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/vm/hypervisor/kvm/setup_agent.sh b/scripts/vm/hypervisor/kvm/setup_agent.sh index 7697aaa0d0b..1c0a18112df 100755 --- a/scripts/vm/hypervisor/kvm/setup_agent.sh +++ b/scripts/vm/hypervisor/kvm/setup_agent.sh @@ -174,4 +174,4 @@ done #install_cloud_agent $dflag #install_cloud_consoleP $dflag cloud_agent_setup $host $zone $pod $guid -cloud_consoleP_setup $host $zone $pod +#cloud_consoleP_setup $host $zone $pod From dc14cb4b3d3c0230d99860d087d3d1e0fefb1543 Mon Sep 17 00:00:00 2001 From: edison Date: Wed, 18 Aug 2010 12:26:43 -0700 Subject: [PATCH 011/235] fix vlan dev naming issue: don't naming it by ourself --- .../agent/resource/computing/LibvirtComputingResource.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index 755a739448d..67398b29f92 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -3097,7 +3097,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv brName = setVnetBrName(vnetId); String vnetDev = "vtap" + vnetId; createVnet(vnetId, _pifs.first()); - vnetNic.defBridgeNet(brName, vnetDev, guestMac, interfaceDef.nicModel.VIRTIO); + vnetNic.defBridgeNet(brName, null, guestMac, interfaceDef.nicModel.VIRTIO); } nics.add(vnetNic); @@ -3113,7 +3113,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv brName = setVnetBrName(vnetId); String vnetDev = "vtap" + vnetId; createVnet(vnetId, _pifs.second()); - pubNic.defBridgeNet(brName, vnetDev, pubMac, interfaceDef.nicModel.VIRTIO); + pubNic.defBridgeNet(brName, null, pubMac, interfaceDef.nicModel.VIRTIO); } nics.add(pubNic); return nics; From ea3bbcb4641a18a7456e127315d0a1bb58cf5297 Mon Sep 17 00:00:00 2001 From: edison Date: Wed, 18 Aug 2010 16:28:22 -0700 Subject: [PATCH 012/235] fix attaching disk --- .../agent/resource/computing/LibvirtComputingResource.java | 2 +- .../cloud/agent/resource/computing/LibvirtDomainXMLParser.java | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index 67398b29f92..fa346e79b1f 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -2360,7 +2360,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv Iterator> itr = entrySet.iterator(); while (itr.hasNext()) { Map.Entry entry = itr.next(); - if (entry.getValue().equalsIgnoreCase(sourceFile)) { + if ((entry.getValue() != null) && (entry.getValue().equalsIgnoreCase(sourceFile))) { diskDev = entry.getKey(); break; } diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java b/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java index 779962af0a4..b5271c8e62c 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtDomainXMLParser.java @@ -94,6 +94,8 @@ public class LibvirtDomainXMLParser extends LibvirtXMLParser { } else if (qName.equalsIgnoreCase("disk")) { diskMaps.put(diskDev, diskFile); _disk = false; + diskFile = null; + diskDev = null; } else if (qName.equalsIgnoreCase("description")) { _desc = false; } From 3ab4651cf0f38f4c5508fa4eecd9d9a8dfeb9add Mon Sep 17 00:00:00 2001 From: edison Date: Thu, 19 Aug 2010 21:36:51 -0700 Subject: [PATCH 013/235] Issue #: 5978 5977 5971 5972 Status 5978: resolved fixed Status 5977: resolved fixed Status 5971: resolved fixed Status 5972: resolved fixed --- .../computing/LibvirtComputingResource.java | 177 ++++++++++++++---- scripts/storage/qcow2/createtmplt.sh | 34 +++- scripts/storage/qcow2/managesnapshot.sh | 44 +++-- .../com/cloud/storage/StorageManagerImpl.java | 6 +- .../storage/snapshot/SnapshotManagerImpl.java | 4 +- .../src/com/cloud/vm/UserVmManagerImpl.java | 8 +- 6 files changed, 203 insertions(+), 70 deletions(-) diff --git a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java index fa346e79b1f..6ae752fd200 100644 --- a/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java +++ b/agent/src/com/cloud/agent/resource/computing/LibvirtComputingResource.java @@ -1228,21 +1228,46 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv protected ManageSnapshotAnswer execute(final ManageSnapshotCommand cmd) { String snapshotName = cmd.getSnapshotName(); String VolPath = cmd.getVolumePath(); + String snapshotPath = cmd.getSnapshotPath(); + String vmName = cmd.getVmName(); try { - StorageVol vol = getVolume(VolPath); - if (vol == null) { - return new ManageSnapshotAnswer(cmd, false, null); + DomainInfo.DomainState state = null; + Domain vm = null; + if (vmName != null) { + try { + vm = getDomain(cmd.getVmName()); + state = vm.getInfo().state; + } catch (LibvirtException e) { + + } } - Domain vm = getDomain(cmd.getVmName()); - String vmUuid = vm.getUUIDString(); - Object[] args = new Object[] {snapshotName, vmUuid}; - String snapshot = SnapshotXML.format(args); - s_logger.debug(snapshot); - if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) { - vm.snapshotCreateXML(snapshot); + + if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING) { + String vmUuid = vm.getUUIDString(); + Object[] args = new Object[] {snapshotName, vmUuid}; + String snapshot = SnapshotXML.format(args); + s_logger.debug(snapshot); + if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) { + vm.snapshotCreateXML(snapshot); + } else { + DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); + snap.delete(0); + } } else { - DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); - snap.delete(0); + /*VM is not running, create a snapshot by ourself*/ + final Script command = new Script(_manageSnapshotPath, _timeout, s_logger); + if (cmd.getCommandSwitch().equalsIgnoreCase(ManageSnapshotCommand.CREATE_SNAPSHOT)) { + command.add("-c", VolPath); + } else { + command.add("-d", snapshotPath); + } + + command.add("-n", snapshotName); + String result = command.execute(); + if (result != null) { + s_logger.debug("Failed to manage snapshot: " + result); + return new ManageSnapshotAnswer(cmd, false, "Failed to manage snapshot: " + result); + } } } catch (LibvirtException e) { s_logger.debug("Failed to manage snapshot: " + e.toString()); @@ -1259,28 +1284,52 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv String snapshotName = cmd.getSnapshotName(); String snapshotPath = cmd.getSnapshotUuid(); String snapshotDestPath = null; + String vmName = cmd.getVmName(); try { StoragePool secondaryStoragePool = getNfsSPbyURI(_conn, new URI(secondaryStoragePoolURL)); String ssPmountPath = _mountPoint + File.separator + secondaryStoragePool.getUUIDString(); snapshotDestPath = ssPmountPath + File.separator + dcId + File.separator + "snapshots" + File.separator + accountId + File.separator + volumeId; - final Script command = new Script(_manageSnapshotPath, _timeout, s_logger); + Script command = new Script(_manageSnapshotPath, _timeout, s_logger); command.add("-b", snapshotPath); command.add("-n", snapshotName); command.add("-p", snapshotDestPath); + command.add("-t", snapshotName); String result = command.execute(); if (result != null) { s_logger.debug("Failed to backup snaptshot: " + result); return new BackupSnapshotAnswer(cmd, false, result, null); } /*Delete the snapshot on primary*/ - Domain vm = getDomain(cmd.getVmName()); - String vmUuid = vm.getUUIDString(); - Object[] args = new Object[] {snapshotName, vmUuid}; - String snapshot = SnapshotXML.format(args); - s_logger.debug(snapshot); - DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); - snap.delete(0); + + DomainInfo.DomainState state = null; + Domain vm = null; + if (vmName != null) { + try { + vm = getDomain(cmd.getVmName()); + state = vm.getInfo().state; + } catch (LibvirtException e) { + + } + } + + if (state == DomainInfo.DomainState.VIR_DOMAIN_RUNNING) { + String vmUuid = vm.getUUIDString(); + Object[] args = new Object[] {snapshotName, vmUuid}; + String snapshot = SnapshotXML.format(args); + s_logger.debug(snapshot); + DomainSnapshot snap = vm.snapshotLookupByName(snapshotName); + snap.delete(0); + } else { + command = new Script(_manageSnapshotPath, _timeout, s_logger); + command.add("-d", snapshotPath); + command.add("-n", snapshotName); + result = command.execute(); + if (result != null) { + s_logger.debug("Failed to backup snapshot: " + result); + return new BackupSnapshotAnswer(cmd, false, "Failed to backup snapshot: " + result, null); + } + } } catch (LibvirtException e) { return new BackupSnapshotAnswer(cmd, false, e.toString(), null); } catch (URISyntaxException e) { @@ -1356,7 +1405,11 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv try { secondaryPool = getNfsSPbyURI(_conn, new URI(cmd.getSecondaryStoragePoolURL())); /*TODO: assuming all the storage pools mounted under _mountPoint, the mount point should be got from pool.dumpxml*/ - String templatePath = _mountPoint + File.separator + secondaryPool.getUUIDString() + File.separator + templateInstallFolder; + String templatePath = _mountPoint + File.separator + secondaryPool.getUUIDString() + File.separator + templateInstallFolder; + File f = new File(templatePath); + if (!f.exists()) { + f.mkdir(); + } String tmplPath = templateInstallFolder + File.separator + tmplFileName; Script command = new Script(_createTmplPath, _timeout, s_logger); command.add("-t", templatePath); @@ -1403,38 +1456,58 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv } protected CreatePrivateTemplateAnswer execute(CreatePrivateTemplateCommand cmd) { String secondaryStorageURL = cmd.getSecondaryStorageURL(); - String snapshotUUID = cmd.getSnapshotPath(); StoragePool secondaryStorage = null; - StoragePool privateTemplStorage = null; - StorageVol privateTemplateVol = null; - StorageVol snapshotVol = null; try { String templateFolder = cmd.getAccountId() + File.separator + cmd.getTemplateId() + File.separator; String templateInstallFolder = "/template/tmpl/" + templateFolder; - + secondaryStorage = getNfsSPbyURI(_conn, new URI(secondaryStorageURL)); /*TODO: assuming all the storage pools mounted under _mountPoint, the mount point should be got from pool.dumpxml*/ - String mountPath = _mountPoint + File.separator + secondaryStorage.getUUIDString() + templateInstallFolder; - File mpfile = new File(mountPath); + String tmpltPath = _mountPoint + File.separator + secondaryStorage.getUUIDString() + templateInstallFolder; + File mpfile = new File(tmpltPath); if (!mpfile.exists()) { mpfile.mkdir(); } + + Script command = new Script(_createTmplPath, _timeout, s_logger); + command.add("-f", cmd.getSnapshotPath()); + command.add("-c", cmd.getSnapshotName()); + command.add("-t", tmpltPath); + command.add("-n", cmd.getUniqueName() + ".qcow2"); + command.add("-s"); + String result = command.execute(); - // Create a SR for the secondary storage installation folder - privateTemplStorage = getNfsSPbyURI(_conn, new URI(secondaryStorageURL + templateInstallFolder)); - snapshotVol = getVolume(snapshotUUID); - - LibvirtStorageVolumeDef vol = new LibvirtStorageVolumeDef(UUID.randomUUID().toString(), snapshotVol.getInfo().capacity, volFormat.QCOW2, null, null); - s_logger.debug(vol.toString()); - privateTemplateVol = copyVolume(privateTemplStorage, vol, snapshotVol); + if (result != null) { + s_logger.debug("failed to create template: " + result); + return new CreatePrivateTemplateAnswer(cmd, + false, + result, + null, + 0, + null, + null); + } + + Map params = new HashMap(); + params.put(StorageLayer.InstanceConfigKey, _storage); + Processor qcow2Processor = new QCOW2Processor(); + + qcow2Processor.configure("QCOW2 Processor", params); + + FormatInfo info = qcow2Processor.process(tmpltPath, null, cmd.getUniqueName()); + + TemplateLocation loc = new TemplateLocation(_storage, tmpltPath); + loc.create(1, true, cmd.getUniqueName()); + loc.addFormat(info); + loc.save(); return new CreatePrivateTemplateAnswer(cmd, true, null, - templateInstallFolder + privateTemplateVol.getName(), - privateTemplateVol.getInfo().capacity/1024*1024, /*in Mega unit*/ - privateTemplateVol.getName(), + templateInstallFolder + cmd.getUniqueName() + ".qcow2", + info.virtualSize, + cmd.getUniqueName(), ImageFormat.QCOW2); } catch (URISyntaxException e) { return new CreatePrivateTemplateAnswer(cmd, @@ -1453,7 +1526,31 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv 0, null, null); - } + } catch (InternalErrorException e) { + return new CreatePrivateTemplateAnswer(cmd, + false, + e.toString(), + null, + 0, + null, + null); + } catch (IOException e) { + return new CreatePrivateTemplateAnswer(cmd, + false, + e.toString(), + null, + 0, + null, + null); + } catch (ConfigurationException e) { + return new CreatePrivateTemplateAnswer(cmd, + false, + e.toString(), + null, + 0, + null, + null); + } } private StoragePool getNfsSPbyURI(Connect conn, URI uri) throws LibvirtException { @@ -3165,7 +3262,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv String datadiskPath = tmplVol.getKey(); diskDef hda = new diskDef(); - hda.defFileBasedDisk(rootkPath, "vda", diskDef.diskBus.IDE, diskDef.diskFmtType.QCOW2); + hda.defFileBasedDisk(rootkPath, "hda", diskDef.diskBus.IDE, diskDef.diskFmtType.QCOW2); disks.add(hda); diskDef hdb = new diskDef(); diff --git a/scripts/storage/qcow2/createtmplt.sh b/scripts/storage/qcow2/createtmplt.sh index 55efe952af5..ef75c6270e9 100755 --- a/scripts/storage/qcow2/createtmplt.sh +++ b/scripts/storage/qcow2/createtmplt.sh @@ -80,6 +80,20 @@ create_from_file() { fi } +create_from_snapshot() { + local tmpltImg=$1 + local snapshotName=$2 + local tmpltfs=$3 + local tmpltname=$4 + + cloud-qemu-img convert -f qcow2 -O qcow2 -s $snapshotName $tmpltImg /$tmpltfs/$tmpltname >& /dev/null + if [ $? -gt 0 ] + then + printf "Failed to create template /$tmplfs/$tmpltname from snapshot $snapshotName on disk $tmpltImg " + exit 2 + fi +} + tflag= nflag= fflag= @@ -89,8 +103,9 @@ hvm=false cleanup=false dflag= cflag= +snapshotName= -while getopts 'uht:n:f:s:c:d:' OPTION +while getopts 'uht:n:f:sc:d:' OPTION do case $OPTION in t) tflag=1 @@ -103,10 +118,10 @@ do tmpltimg="$OPTARG" ;; s) sflag=1 - volsize="$OPTARG" + sflag=1 ;; c) cflag=1 - cksum="$OPTARG" + snapshotName="$OPTARG" ;; d) dflag=1 descr="$OPTARG" @@ -119,12 +134,6 @@ do esac done -if [ "$tflag$nflag$fflag" != "111" ] -then - usage - exit 2 -fi - if [ ! -d /$tmpltfs ] then @@ -148,7 +157,12 @@ then printf "failed to uncompress $tmpltimg\n" fi -create_from_file $tmpltfs $tmpltimg $tmpltname +if [ "$sflag" == "1" ] +then + create_from_snapshot $tmpltimg $snapshotName $tmpltfs $tmpltname +else + create_from_file $tmpltfs $tmpltimg $tmpltname +fi touch /$tmpltfs/template.properties echo -n "" > /$tmpltfs/template.properties diff --git a/scripts/storage/qcow2/managesnapshot.sh b/scripts/storage/qcow2/managesnapshot.sh index 3c7692161d6..d9b339267a0 100755 --- a/scripts/storage/qcow2/managesnapshot.sh +++ b/scripts/storage/qcow2/managesnapshot.sh @@ -16,13 +16,20 @@ create_snapshot() { local snapshotname=$2 local failed=0 - qemu-img snapshot -c $snapshotname $disk + if [ ! -f $disk ] + then + failed=1 + printf "No disk $disk exist\n" >&2 + return $failed + fi + + cloud-qemu-img snapshot -c $snapshotname $disk if [ $? -gt 0 ] then - failed=1 + failed=2 printf "***Failed to create snapshot $snapshotname for path $disk\n" >&2 - qemu-img snapshot -d $snapshotname $disk + cloud-qemu-img snapshot -d $snapshotname $disk if [ $? -gt 0 ] then @@ -34,21 +41,24 @@ create_snapshot() { } destroy_snapshot() { - local backupSnapDir=$1 + local disk=$1 local snapshotname=$2 local failed=0 - if [ -f $backupSnapDir/$snapshotname ] + if [ ! -f $disk ] then - rm -f $backupSnapDir/$snapshotname - - if [ $? -gt 0 ] - then - printf "***Failed to delete snapshot $snapshotname for path $backupSnapDir\n" >&2 - failed=1 - fi + failed=1 + printf "No disk $disk exist\n" >&2 + return $failed fi + cloud-qemu-img snapshot -d $snapshotname $disk + if [ $? -gt 0 ] + then + failed=2 + printf "Failed to delete snapshot $snapshotname for path $disk\n" >&2 + fi + return $failed } @@ -71,6 +81,7 @@ backup_snapshot() { local disk=$1 local snapshotname=$2 local destPath=$3 + local destName=$4 if [ ! -d $destPath ] then @@ -90,7 +101,7 @@ backup_snapshot() { return 1 fi - cloud-qemu-img convert -f qcow2 -O qcow2 -s $snapshotname $disk $destPath/$snapshotname >& /dev/null + cloud-qemu-img convert -f qcow2 -O qcow2 -s $snapshotname $disk $destPath/$destName >& /dev/null if [ $? -gt 0 ] then printf "Failed to backup $snapshotname for disk $disk to $destPath" >&2 @@ -107,8 +118,9 @@ bflag= nflag= pathval= snapshot= +tmplName= -while getopts 'c:d:r:n:b:p:' OPTION +while getopts 'c:d:r:n:b:p:t:' OPTION do case $OPTION in c) cflag=1 @@ -128,6 +140,8 @@ do ;; p) destPath="$OPTARG" ;; + t) tmplName="$OPTARG" + ;; ?) usage ;; esac @@ -144,7 +158,7 @@ then exit $? elif [ "$bflag" == "1" ] then - backup_snapshot $pathval $snapshot $destPath + backup_snapshot $pathval $snapshot $destPath $tmplName exit $? elif [ "$rflag" == "1" ] then diff --git a/server/src/com/cloud/storage/StorageManagerImpl.java b/server/src/com/cloud/storage/StorageManagerImpl.java index d3f2156f79d..53395a5a130 100644 --- a/server/src/com/cloud/storage/StorageManagerImpl.java +++ b/server/src/com/cloud/storage/StorageManagerImpl.java @@ -939,10 +939,12 @@ public class StorageManagerImpl implements StorageManager { if (vmId != null) { VMInstanceVO vmInstance = _vmInstanceDao.findById(vmId); if (vmInstance != null) { - return vmInstance.getHostId(); + Long hostId = vmInstance.getHostId(); + if (hostId != null && !avoidHosts.contains(vmInstance.getHostId())) + return hostId; } } - return null; + /*Can't find the vm where host resides on(vm is destroyed? or volume is detached from vm), randomly choose a host to send the cmd */ } List poolHosts = _poolHostDao.listByHostStatus(poolVO.getId(), Status.Up); Collections.shuffle(poolHosts); diff --git a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java index a372e17b6e8..c6f82d2f567 100644 --- a/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java +++ b/server/src/com/cloud/storage/snapshot/SnapshotManagerImpl.java @@ -287,7 +287,7 @@ public class SnapshotManagerImpl implements SnapshotManager { } txn.commit(); - VolumeVO volume = _volsDao.findById(volumeId); + VolumeVO volume = _volsDao.lock(volumeId, true); if (!shouldRunSnapshot(userId, volume, policyIds)) { // A null snapshot is interpreted as snapshot creation failed which is what we want to indicate @@ -477,7 +477,7 @@ public class SnapshotManagerImpl implements SnapshotManager { _snapshotDao.update(snapshot.getId(), snapshot); long volumeId = snapshot.getVolumeId(); - VolumeVO volume = _volsDao.findById(volumeId); + VolumeVO volume = _volsDao.lock(volumeId, true); String primaryStoragePoolNameLabel = _storageMgr.getPrimaryStorageNameLabel(volume); Long dcId = volume.getDataCenterId(); diff --git a/server/src/com/cloud/vm/UserVmManagerImpl.java b/server/src/com/cloud/vm/UserVmManagerImpl.java index 7a26cc7d100..721f73e3eb4 100755 --- a/server/src/com/cloud/vm/UserVmManagerImpl.java +++ b/server/src/com/cloud/vm/UserVmManagerImpl.java @@ -686,6 +686,7 @@ public class UserVmManagerImpl implements UserVmManager { } boolean started = false; + Transaction txn = Transaction.currentTxn(); try { @@ -736,6 +737,11 @@ public class UserVmManagerImpl implements UserVmManager { VolumeVO vol = rootVols.get(0); List vols = _volsDao.findCreatedByInstance(vm.getId()); + List vos = new ArrayList(); + /*compete with take snapshot*/ + for (VolumeVO userVmVol : vols) { + vos.add(_volsDao.lock(userVmVol.getId(), true)); + } Answer answer = null; int retry = _retry; @@ -2215,7 +2221,7 @@ public class UserVmManagerImpl implements UserVmManager { @Override @DB public SnapshotVO createTemplateSnapshot(long userId, long volumeId) { SnapshotVO createdSnapshot = null; - VolumeVO volume = _volsDao.findById(volumeId); + VolumeVO volume = _volsDao.lock(volumeId, true); Long id = null; From 3c92e52886fc8ee8fb8902ddc5f0185f970f88ae Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 15:48:08 -0700 Subject: [PATCH 014/235] Issue #: 5785 - support non-ascii character like euro character --- ui/scripts/cloud.core.configuration.js | 39 +++++++++++++------------- ui/scripts/cloud.core.instances.js | 12 ++++---- 2 files changed, 25 insertions(+), 26 deletions(-) diff --git a/ui/scripts/cloud.core.configuration.js b/ui/scripts/cloud.core.configuration.js index d3ffd9022ae..d648e4a53eb 100644 --- a/ui/scripts/cloud.core.configuration.js +++ b/ui/scripts/cloud.core.configuration.js @@ -1244,7 +1244,7 @@ function showConfigurationTab() { dialogEditService.find("#service_name").text(svcName); dialogEditService.find("#edit_service_name").val(svcName); - dialogEditService.find("#edit_service_display").val(template.find("#service_display").text()); + dialogEditService.find("#edit_service_display").val(template.find("#service_displaytext").text()); dialogEditService.find("#edit_service_offerha").val(toBooleanValue(template.find("#service_offerha").text())); dialogEditService @@ -1260,9 +1260,9 @@ function showConfigurationTab() { var moreCriteria = []; var name = trim(thisDialog.find("#edit_service_name").val()); - moreCriteria.push("&name="+encodeURIComponent(name)); + moreCriteria.push("&name="+encodeURIComponent(escape(name))); var displaytext = trim(thisDialog.find("#edit_service_display").val()); - moreCriteria.push("&displayText="+encodeURIComponent(displaytext)); + moreCriteria.push("&displayText="+encodeURIComponent(escape(displaytext))); var offerha = trim(thisDialog.find("#edit_service_offerha").val()); moreCriteria.push("&offerha="+offerha); @@ -1316,17 +1316,17 @@ function showConfigurationTab() { function serviceJSONToTemplate(json, template) { template.attr("id", "service_"+json.id); (index++ % 2 == 0)? template.addClass("smallrow_even"): template.addClass("smallrow_odd"); - template.data("svcId", json.id).data("svcName", sanitizeXSS(json.name)); + template.data("svcId", json.id).data("svcName", sanitizeXSS(unescape(json.name))); template.find("#service_id").text(json.id); - template.find("#service_name").text(json.name); - template.find("#service_displaytext").text(json.displaytext); + template.find("#service_name").text(unescape(json.name)); + template.find("#service_displaytext").text(unescape(json.displaytext)); template.find("#service_storagetype").text(json.storagetype); template.find("#service_cpu").text(json.cpunumber + " x " + convertHz(json.cpuspeed)); template.find("#service_memory").text(convertBytes(parseInt(json.memory)*1024*1024)); template.find("#service_offerha").text(toBooleanText(json.offerha)); template.find("#service_networktype").text(toNetworkType(json.usevirtualnetwork)); - template.find("#service_tags").text(json.tags); + template.find("#service_tags").text(unescape(json.tags)); setDateField(json.created, template.find("#service_created")); } @@ -1454,10 +1454,10 @@ function showConfigurationTab() { var array1 = []; var name = trim(thisDialog.find("#add_service_name").val()); - array1.push("&name="+encodeURIComponent(name)); + array1.push("&name="+encodeURIComponent(escape(name))); var display = trim(thisDialog.find("#add_service_display").val()); - array1.push("&displayText="+encodeURIComponent(display)); + array1.push("&displayText="+encodeURIComponent(escape(display))); var storagetype = trim(thisDialog.find("#add_service_storagetype").val()); array1.push("&storageType="+storagetype); @@ -1480,7 +1480,7 @@ function showConfigurationTab() { var tags = trim(thisDialog.find("#add_service_tags").val()); if(tags != null && tags.length > 0) - array1.push("&tags="+encodeURIComponent(tags)); + array1.push("&tags="+encodeURIComponent(escape(tags))); thisDialog.dialog("close"); $.ajax({ @@ -1544,17 +1544,17 @@ function showConfigurationTab() { var array1 = []; var name = trim(thisDialog.find("#add_disk_name").val()); - array1.push("&name="+encodeURIComponent(name)); + array1.push("&name="+encodeURIComponent(escape(name))); var description = trim(thisDialog.find("#add_disk_description").val()); - array1.push("&displaytext="+encodeURIComponent(description)); + array1.push("&displaytext="+encodeURIComponent(escape(description))); var disksize = trim(thisDialog.find("#add_disk_disksize").val()); array1.push("&disksize="+disksize); var tags = trim(thisDialog.find("#add_disk_tags").val()); if(tags != null && tags.length > 0) - array1.push("&tags="+encodeURIComponent(tags)); + array1.push("&tags="+encodeURIComponent(escape(tags))); thisDialog.dialog("close"); $.ajax({ @@ -1649,7 +1649,7 @@ function showConfigurationTab() { var dialogBox = $(this); dialogBox.dialog("close"); $.ajax({ - data: createURL("command=updateDiskOffering&name="+encodeURIComponent(name)+"&displayText="+encodeURIComponent(display)+"&id="+diskId+"&response=json"), + data: createURL("command=updateDiskOffering&name="+encodeURIComponent(escape(name))+"&displayText="+encodeURIComponent(escape(display))+"&id="+diskId+"&response=json"), dataType: "json", success: function(json) { template.find("#disk_description").text(display); @@ -1699,15 +1699,14 @@ function showConfigurationTab() { } else { template.addClass("smallrow_odd"); } - template.data("diskId", json.id).data("diskName", sanitizeXSS(json.name)); + template.data("diskId", json.id).data("diskName", sanitizeXSS(unescape(json.name))); template.find("#disk_id").text(json.id); - template.find("#disk_name").text(json.name); - template.find("#disk_description").text(json.displaytext); + template.find("#disk_name").text(unescape(json.name)); + template.find("#disk_description").text(unescape(json.displaytext)); template.find("#disk_disksize").text(convertBytes(json.disksize)); - template.find("#disk_tags").text(json.tags); - template.find("#disk_domain").text(json.domain); - template.find("#disk_ismirrored").text(json.ismirrored); + template.find("#disk_tags").text(unescape(json.tags)); + template.find("#disk_domain").text(unescape(json.domain)); } function listDiskOfferings() { diff --git a/ui/scripts/cloud.core.instances.js b/ui/scripts/cloud.core.instances.js index ab2bbf17837..e5a9865f48b 100644 --- a/ui/scripts/cloud.core.instances.js +++ b/ui/scripts/cloud.core.instances.js @@ -576,7 +576,7 @@ function showInstancesTab(p_domainId, p_account) { if (offerings != null && offerings.length > 0) { for (var i = 0; i < offerings.length; i++) { - var option = $("").data("name", offerings[i].name); + var option = $("").data("name", sanitizeXSS(unescape(offerings[i].name))); offeringSelect.append(option); } } @@ -611,7 +611,7 @@ function showInstancesTab(p_domainId, p_account) { vmInstance.find(".row_loading").show(); vmInstance.find(".loadingmessage_container .loadingmessage_top p").html("Your virtual instance has been upgraded. Please restart your virtual instance for the new service offering to take effect."); vmInstance.find(".loadingmessage_container").fadeIn("slow"); - vmInstance.find("#vm_service").html("Service: " + sanitizeXSS(result.virtualmachine[0].serviceofferingname)); + vmInstance.find("#vm_service").html("Service: " + sanitizeXSS(unescape(result.virtualmachine[0].serviceofferingname))); if (result.virtualmachine[0].haenable =='true') { vmInstance.find("#vm_ha").html("HA: Enabled"); vmInstance.find("#vm_action_ha").text("Disable HA"); @@ -1109,7 +1109,7 @@ function showInstancesTab(p_domainId, p_account) { instanceTemplate.find("#vm_ip_address").html("IP Address: " + instanceJSON.ipaddress); instanceTemplate.find("#vm_zone").html("Zone: " + sanitizeXSS(instanceJSON.zonename)); instanceTemplate.find("#vm_template").html("Template: " + sanitizeXSS(instanceJSON.templatename)); - instanceTemplate.find("#vm_service").html("Service: " + sanitizeXSS(instanceJSON.serviceofferingname)); + instanceTemplate.find("#vm_service").html("Service: " + sanitizeXSS(unescape(instanceJSON.serviceofferingname))); if (instanceJSON.haenable =='true') { instanceTemplate.find("#vm_ha").html("HA: Enabled"); instanceTemplate.find("#vm_action_ha").text("Disable HA"); @@ -1277,7 +1277,7 @@ function showInstancesTab(p_domainId, p_account) { continue; var checked = "checked"; if (first == false) checked = ""; - var listItem = $("
  • "); + var listItem = $("
  • "); $("#wizard_service_offering").append(listItem); first = false; } @@ -1306,14 +1306,14 @@ function showInstancesTab(p_domainId, p_account) { var html = "
  • " +"" - +"" + +"" +"
  • "; $("#wizard_root_disk_offering").append(html); var html2 = "
  • " +"" - +"" + +"" +"
  • "; $("#wizard_data_disk_offering").append(html2); } From 111f88a1dca2ed69f142c7767a7c3616231a4186 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 16:33:15 -0700 Subject: [PATCH 015/235] Issue #: 5953 - show remove link when host status is disconnected --- ui/scripts/cloud.core.hosts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/scripts/cloud.core.hosts.js b/ui/scripts/cloud.core.hosts.js index 3316b5b19b8..d89c2249f0b 100644 --- a/ui/scripts/cloud.core.hosts.js +++ b/ui/scripts/cloud.core.hosts.js @@ -569,7 +569,7 @@ function showHostsTab() { } else if (state == "Maintenance") { template.find(".grid_links").find("#host_action_reconnect_container, #host_action_enable_maint_container").hide(); } else if (state == "Disconnected") { - template.find(".grid_links").find("#host_action_reconnect_container, #host_action_enable_maint_container, #host_action_cancel_maint_container, #host_action_remove_container").hide(); + template.find(".grid_links").find("#host_action_reconnect_container, #host_action_enable_maint_container, #host_action_cancel_maint_container").hide(); } else { alert("Unsupported Host State: " + state); } From e5bdec33f9f316ad797a61ea46824d3ff905bd18 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 17:09:48 -0700 Subject: [PATCH 016/235] Issue #: 5979 - change text on VM Wizard Step 3. --- ui/content/tab_instances.html | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ui/content/tab_instances.html b/ui/content/tab_instances.html index 9bc3b94701d..55991f3ff01 100644 --- a/ui/content/tab_instances.html +++ b/ui/content/tab_instances.html @@ -704,8 +704,7 @@

    Step 3: Optional

    - To create a new instance, please first select a zone you wish to have your virtual - instance hosted on.

    + You can choose to name and group your virtual machine for easy identification. You can also choose additional data storage. (These options can be added at any time.)

    From 23a38bc2be53254659c58f923c44115b2ba845d2 Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Wed, 25 Aug 2010 18:17:20 -0700 Subject: [PATCH 017/235] Debug & Test template copy from secondary storage to primary stroage on vmware --- api/src/com/cloud/storage/Storage.java | 16 ++++++++++-- .../PrimaryStorageDownloadCommand.java | 26 +++++++++++++++++++ .../cloud/storage/template/VmdkProcessor.java | 10 ++++--- .../cloud/template/TemplateManagerImpl.java | 8 +++++- utils/src/com/cloud/utils/DateUtil.java | 14 ++++++++-- 5 files changed, 65 insertions(+), 9 deletions(-) diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index 24ceb5b3fec..7ebdc5e187e 100644 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -23,16 +23,25 @@ public class Storage { RAW(false, false, false), VHD(true, true, true), ISO(false, false, false), - VMDK(true, true, true); + VMDK(true, true, true, ".tar.bz2"); private final boolean thinProvisioned; private final boolean supportSparse; private final boolean supportSnapshot; + private final String fileExtension; private ImageFormat(boolean thinProvisioned, boolean supportSparse, boolean supportSnapshot) { this.thinProvisioned = thinProvisioned; this.supportSparse = supportSparse; this.supportSnapshot = supportSnapshot; + fileExtension = null; + } + + private ImageFormat(boolean thinProvisioned, boolean supportSparse, boolean supportSnapshot, String fileExtension) { + this.thinProvisioned = thinProvisioned; + this.supportSparse = supportSparse; + this.supportSnapshot = supportSnapshot; + this.fileExtension = fileExtension; } public boolean isThinProvisioned() { @@ -48,7 +57,10 @@ public class Storage { } public String getFileExtension() { - return toString().toLowerCase(); + if(fileExtension == null) + return toString().toLowerCase(); + + return fileExtension; } } diff --git a/core/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java b/core/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java index a9010d5782e..f11f17f1bb5 100644 --- a/core/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java +++ b/core/src/com/cloud/agent/api/storage/PrimaryStorageDownloadCommand.java @@ -28,6 +28,16 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { String localPath; String poolUuid; long poolId; + + // + // Temporary hacking to make vmware work quickly, expose NFS raw information to allow + // agent do quick copy over NFS. + // + // provide storage URL (it contains all information to help agent resource to mount the + // storage if needed, example of such URL may be as following + // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary + String secondaryStorageUrl; + String primaryStorageUrl; protected PrimaryStorageDownloadCommand() { } @@ -54,6 +64,22 @@ public class PrimaryStorageDownloadCommand extends AbstractDownloadCommand { 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/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java index b8d037c3538..fe060ab02de 100644 --- a/core/src/com/cloud/storage/template/VmdkProcessor.java +++ b/core/src/com/cloud/storage/template/VmdkProcessor.java @@ -20,20 +20,22 @@ public class VmdkProcessor implements Processor { @Override public FormatInfo process(String templatePath, ImageFormat format, String templateName) throws InternalErrorException { if (format != null) { - s_logger.debug("We currently don't handle conversion from " + format + " to VMDK."); + if(s_logger.isInfoEnabled()) + s_logger.info("We currently don't handle conversion from " + format + " to VMDK."); return null; } s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFilePath = templatePath + File.separator + templateName + ".tar.bz2"; + String templateFilePath = templatePath + File.separator + templateName + ImageFormat.VMDK.getFileExtension(); if (!_storage.exists(templateFilePath)) { - s_logger.debug("Unable to find the vmware template file: " + templateFilePath); + if(s_logger.isInfoEnabled()) + s_logger.info("Unable to find the vmware template file: " + templateFilePath); return null; } FormatInfo info = new FormatInfo(); info.format = ImageFormat.VMDK; - info.filename = templateName + ".tar.bz2"; + info.filename = templateName + ImageFormat.VMDK.getFileExtension(); info.size = _storage.getSize(templateFilePath); info.virtualSize = info.size; return info; diff --git a/server/src/com/cloud/template/TemplateManagerImpl.java b/server/src/com/cloud/template/TemplateManagerImpl.java index 700aa85c42c..71fe9be0052 100644 --- a/server/src/com/cloud/template/TemplateManagerImpl.java +++ b/server/src/com/cloud/template/TemplateManagerImpl.java @@ -223,7 +223,13 @@ public class TemplateManagerImpl implements TemplateManager { return templateStoragePoolRef; } String url = origUrl + "/" + templateHostRef.getInstallPath(); - PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(template.getUniqueName(), url, template.getFormat(), template.getAccountId(), pool.getId(), pool.getUuid()); + PrimaryStorageDownloadCommand dcmd = new PrimaryStorageDownloadCommand(template.getUniqueName(), url, template.getFormat(), + template.getAccountId(), pool.getId(), pool.getUuid()); + HostVO secondaryStorageHost = _hostDao.findSecondaryStorageHost(pool.getDataCenterId()); + assert(secondaryStorageHost != null); + dcmd.setSecondaryStorageUrl(secondaryStorageHost.getStorageUrl()); + // TODO temporary hacking, hard-coded to NFS primary data store + dcmd.setPrimaryStorageUrl("nfs://" + pool.getHostAddress() + pool.getPath()); for (StoragePoolHostVO vo : vos) { if (s_logger.isDebugEnabled()) { diff --git a/utils/src/com/cloud/utils/DateUtil.java b/utils/src/com/cloud/utils/DateUtil.java index 436bb8df231..c6659a7cfe1 100644 --- a/utils/src/com/cloud/utils/DateUtil.java +++ b/utils/src/com/cloud/utils/DateUtil.java @@ -18,6 +18,7 @@ package com.cloud.utils; +import java.net.URI; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -235,14 +236,22 @@ public class DateUtil { throw new CloudRuntimeException("Incorrect interval: "+type.toString()); } - return scheduleTime.getTime(); } // test only public static void main(String[] args) { - + try { + URI uri = new URI("nfs://192.168.10.231/export/home/kelven/vmware-test/secondary"); + System.out.println("protocol: " + uri.getScheme()); + System.out.println("Host: " + uri.getHost()); + System.out.println("path: " + uri.getPath()); + System.out.println("port: " + uri.getPort()); + } catch(Exception e) { + } + +/* TimeZone localTimezone = Calendar.getInstance().getTimeZone(); TimeZone gmtTimezone = TimeZone.getTimeZone("GMT"); TimeZone estTimezone = TimeZone.getTimeZone("EST"); @@ -265,6 +274,7 @@ public class DateUtil { System.out.println("Parsed TZ time string : "+ dtParsed.toString()); } catch (ParseException e) { } +*/ } } From f8c93cd5fa5a9dbcfb465b6ba3f057479fd2f740 Mon Sep 17 00:00:00 2001 From: will Date: Wed, 25 Aug 2010 18:20:49 -0700 Subject: [PATCH 018/235] Bug #:5975 Merge from 2.1.x - Fixed issue where listAccounts only return one less than the actual number of accounts in the system. That is because the SQL query asks for X accounts, but the API filters out the SYSTEM account. The fix is to add the filter of the system account in the actual query itself rather than have the code do it. Conflicts: server/src/com/cloud/api/commands/ListAccountsCmd.java --- .../cloud/api/commands/ListAccountsCmd.java | 408 +++++++++--------- .../cloud/server/ManagementServerImpl.java | 4 + 2 files changed, 207 insertions(+), 205 deletions(-) diff --git a/server/src/com/cloud/api/commands/ListAccountsCmd.java b/server/src/com/cloud/api/commands/ListAccountsCmd.java index 294248fabd0..f2f8561c23f 100644 --- a/server/src/com/cloud/api/commands/ListAccountsCmd.java +++ b/server/src/com/cloud/api/commands/ListAccountsCmd.java @@ -16,8 +16,8 @@ * */ -package com.cloud.api.commands; - +package com.cloud.api.commands; + import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -36,206 +36,204 @@ import com.cloud.user.UserStatisticsVO; import com.cloud.uservm.UserVm; import com.cloud.utils.Pair; import com.cloud.vm.State; - -public class ListAccountsCmd extends BaseCmd{ - public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); - private static final String s_name = "listaccountsresponse"; - private static final List> s_properties = new ArrayList>(); - - static { - s_properties.add(new Pair(BaseCmd.Properties.ID, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.NAME, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT_TYPE, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.STATE, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.IS_CLEANUP_REQUIRED, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.KEYWORD, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.DOMAIN_ID, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.PAGE, Boolean.FALSE)); - s_properties.add(new Pair(BaseCmd.Properties.PAGESIZE, Boolean.FALSE)); - } - - public String getName() { - return s_name; - } - public List> getProperties() { - return s_properties; - } - - @Override - public List> execute(Map params) { - Long id = (Long)params.get(BaseCmd.Properties.ID.getName()); - Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName()); - Long domainId = (Long)params.get(BaseCmd.Properties.DOMAIN_ID.getName()); - Long type = (Long)params.get(BaseCmd.Properties.ACCOUNT_TYPE.getName()); - String state = (String)params.get(BaseCmd.Properties.STATE.getName()); - Boolean needCleanup = (Boolean)params.get(BaseCmd.Properties.IS_CLEANUP_REQUIRED.getName()); - Integer page = (Integer)params.get(BaseCmd.Properties.PAGE.getName()); - Integer pageSize = (Integer)params.get(BaseCmd.Properties.PAGESIZE.getName()); - String keyword = (String)params.get(BaseCmd.Properties.KEYWORD.getName()); - boolean isAdmin = false; - Long accountId = null; - - String accountName = null; - - if ((account == null) || isAdmin(account.getType())) { - accountName = (String)params.get(BaseCmd.Properties.NAME.getName()); - isAdmin = true; - if (domainId == null) { - // default domainId to the admin's domain - domainId = ((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId()); - } else if (account != null) { - if (!getManagementServer().isChildDomain(account.getDomainId(), domainId)) { - throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid domain id (" + domainId + ") given, unable to list accounts"); - } - } - } else { - accountName = (String)params.get(BaseCmd.Properties.ACCOUNT.getName()); - accountId = account.getId(); - } - - Long startIndex = Long.valueOf(0); - int pageSizeNum = 50; - if (pageSize != null) { - pageSizeNum = pageSize.intValue(); - } - if (page != null) { - int pageNum = page.intValue(); - if (pageNum > 0) { - startIndex = Long.valueOf(pageSizeNum * (pageNum-1)); - } - } - Criteria c = new Criteria("id", Boolean.TRUE, startIndex, Long.valueOf(pageSizeNum)); - if (isAdmin == true) { - c.addCriteria(Criteria.ID, id); - if (keyword == null) { - c.addCriteria(Criteria.ACCOUNTNAME, accountName); - c.addCriteria(Criteria.DOMAINID, domainId); - c.addCriteria(Criteria.TYPE, type); - c.addCriteria(Criteria.STATE, state); - c.addCriteria(Criteria.ISCLEANUPREQUIRED, needCleanup); - } else { - c.addCriteria(Criteria.KEYWORD, keyword); - } - } else { - c.addCriteria(Criteria.ID, accountId); - } - - List accounts = getManagementServer().searchForAccounts(c); - - List> accountTags = new ArrayList>(); - Object[] aTag = new Object[accounts.size()]; - int i = 0; - for (AccountVO accountO : accounts) { - boolean accountIsAdmin = (accountO.getType() == Account.ACCOUNT_TYPE_ADMIN); - - if ((accountO.getRemoved() == null)&&(accountO.getId() != 1)) { - List> accountData = new ArrayList>(); - accountData.add(new Pair(BaseCmd.Properties.ID.getName(), Long.valueOf(accountO.getId()).toString())); - accountData.add(new Pair(BaseCmd.Properties.NAME.getName(), accountO.getAccountName())); - accountData.add(new Pair(BaseCmd.Properties.ACCOUNT_TYPE.getName(), Short.valueOf(accountO.getType()).toString())); - Domain domain = getManagementServer().findDomainIdById(accountO.getDomainId()); - accountData.add(new Pair(BaseCmd.Properties.DOMAIN_ID.getName(), Long.toString(domain.getId()))); - accountData.add(new Pair(BaseCmd.Properties.DOMAIN.getName(), domain.getName())); - - //get network stat - List stats = getManagementServer().listUserStatsBy(accountO.getId()); - if (stats == null) { - throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); - } - - long bytesSent = 0; - long bytesReceived = 0; - 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); - } - accountData.add(new Pair(BaseCmd.Properties.BYTES_RECEIVED.getName(), Long.valueOf(bytesReceived).toString())); - accountData.add(new Pair(BaseCmd.Properties.BYTES_SENT.getName(), Long.valueOf(bytesSent).toString())); - - // Get resource limits and counts - - long vmLimit = getManagementServer().findCorrectResourceLimit(ResourceType.user_vm, accountO.getId()); - String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); - long vmTotal = getManagementServer().getResourceCount(ResourceType.user_vm, accountO.getId()); - String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); - accountData.add(new Pair(BaseCmd.Properties.VM_LIMIT.getName(), vmLimitDisplay)); - accountData.add(new Pair(BaseCmd.Properties.VM_TOTAL.getName(), vmTotal)); - accountData.add(new Pair(BaseCmd.Properties.VM_AVAIL.getName(), vmAvail)); - - long ipLimit = getManagementServer().findCorrectResourceLimit(ResourceType.public_ip, accountO.getId()); - String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); - long ipTotal = getManagementServer().getResourceCount(ResourceType.public_ip, accountO.getId()); - String ipAvail = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit - ipTotal); - accountData.add(new Pair(BaseCmd.Properties.IP_LIMIT.getName(), ipLimitDisplay)); - accountData.add(new Pair(BaseCmd.Properties.IP_TOTAL.getName(), ipTotal)); - accountData.add(new Pair(BaseCmd.Properties.IP_AVAIL.getName(), ipAvail)); - - long volumeLimit = getManagementServer().findCorrectResourceLimit(ResourceType.volume, accountO.getId()); - String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); - long volumeTotal = getManagementServer().getResourceCount(ResourceType.volume, accountO.getId()); - String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); - accountData.add(new Pair(BaseCmd.Properties.VOLUME_LIMIT.getName(), volumeLimitDisplay)); - accountData.add(new Pair(BaseCmd.Properties.VOLUME_TOTAL.getName(), volumeTotal)); - accountData.add(new Pair(BaseCmd.Properties.VOLUME_AVAIL.getName(), volumeAvail)); - - long snapshotLimit = getManagementServer().findCorrectResourceLimit(ResourceType.snapshot, accountO.getId()); - String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); - long snapshotTotal = getManagementServer().getResourceCount(ResourceType.snapshot, accountO.getId()); - String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); - accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_LIMIT.getName(), snapshotLimitDisplay)); - accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_TOTAL.getName(), snapshotTotal)); - accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_AVAIL.getName(), snapshotAvail)); - - long templateLimit = getManagementServer().findCorrectResourceLimit(ResourceType.template, accountO.getId()); - String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); - long templateTotal = getManagementServer().getResourceCount(ResourceType.template, accountO.getId()); - String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); - accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_LIMIT.getName(), templateLimitDisplay)); - accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_TOTAL.getName(), templateTotal)); - accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_AVAIL.getName(), templateAvail)); - - // Get stopped and running VMs - - int vmStopped = 0; - int vmRunning = 0; - - Long[] accountIds = new Long[1]; - accountIds[0] = accountO.getId(); - - Criteria c1 = new Criteria(); - c1.addCriteria(Criteria.ACCOUNTID, accountIds); - List virtualMachines = getManagementServer().searchForUserVMs(c1); - - //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++; - } - } - - accountData.add(new Pair(BaseCmd.Properties.VM_STOPPED.getName(), vmStopped)); - accountData.add(new Pair(BaseCmd.Properties.VM_RUNNING.getName(), vmRunning)); - - //show this info to admins only - if (isAdmin == true) { - accountData.add(new Pair(BaseCmd.Properties.STATE.getName(), accountO.getState())); - accountData.add(new Pair(BaseCmd.Properties.IS_CLEANUP_REQUIRED.getName(), Boolean.valueOf(accountO.getNeedsCleanup()).toString())); - } - - aTag[i++] = accountData; - } - } - Pair accountTag = new Pair("account", aTag); - accountTags.add(accountTag); - return accountTags; - } -} + +public class ListAccountsCmd extends BaseCmd{ + public static final Logger s_logger = Logger.getLogger(ListAccountsCmd.class.getName()); + private static final String s_name = "listaccountsresponse"; + private static final List> s_properties = new ArrayList>(); + + static { + s_properties.add(new Pair(BaseCmd.Properties.ID, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.NAME, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT_TYPE, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.STATE, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.IS_CLEANUP_REQUIRED, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.KEYWORD, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT_OBJ, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.ACCOUNT, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.DOMAIN_ID, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.PAGE, Boolean.FALSE)); + s_properties.add(new Pair(BaseCmd.Properties.PAGESIZE, Boolean.FALSE)); + } + + public String getName() { + return s_name; + } + public List> getProperties() { + return s_properties; + } + + @Override + public List> execute(Map params) { + Long id = (Long)params.get(BaseCmd.Properties.ID.getName()); + Account account = (Account)params.get(BaseCmd.Properties.ACCOUNT_OBJ.getName()); + Long domainId = (Long)params.get(BaseCmd.Properties.DOMAIN_ID.getName()); + Long type = (Long)params.get(BaseCmd.Properties.ACCOUNT_TYPE.getName()); + String state = (String)params.get(BaseCmd.Properties.STATE.getName()); + Boolean needCleanup = (Boolean)params.get(BaseCmd.Properties.IS_CLEANUP_REQUIRED.getName()); + Integer page = (Integer)params.get(BaseCmd.Properties.PAGE.getName()); + Integer pageSize = (Integer)params.get(BaseCmd.Properties.PAGESIZE.getName()); + String keyword = (String)params.get(BaseCmd.Properties.KEYWORD.getName()); + boolean isAdmin = false; + Long accountId = null; + + String accountName = null; + + if ((account == null) || isAdmin(account.getType())) { + accountName = (String)params.get(BaseCmd.Properties.NAME.getName()); + isAdmin = true; + if (domainId == null) { + // default domainId to the admin's domain + domainId = ((account == null) ? Domain.ROOT_DOMAIN : account.getDomainId()); + } else if (account != null) { + if (!getManagementServer().isChildDomain(account.getDomainId(), domainId)) { + throw new ServerApiException(BaseCmd.PARAM_ERROR, "Invalid domain id (" + domainId + ") given, unable to list accounts"); + } + } + } else { + accountName = (String)params.get(BaseCmd.Properties.ACCOUNT.getName()); + accountId = account.getId(); + } + + Long startIndex = Long.valueOf(0); + int pageSizeNum = 50; + if (pageSize != null) { + pageSizeNum = pageSize.intValue(); + } + if (page != null) { + int pageNum = page.intValue(); + if (pageNum > 0) { + startIndex = Long.valueOf(pageSizeNum * (pageNum-1)); + } + } + Criteria c = new Criteria("id", Boolean.TRUE, startIndex, Long.valueOf(pageSizeNum)); + if (isAdmin == true) { + c.addCriteria(Criteria.ID, id); + if (keyword == null) { + c.addCriteria(Criteria.ACCOUNTNAME, accountName); + c.addCriteria(Criteria.DOMAINID, domainId); + c.addCriteria(Criteria.TYPE, type); + c.addCriteria(Criteria.STATE, state); + c.addCriteria(Criteria.ISCLEANUPREQUIRED, needCleanup); + } else { + c.addCriteria(Criteria.KEYWORD, keyword); + } + } else { + c.addCriteria(Criteria.ID, accountId); + } + + List accounts = getManagementServer().searchForAccounts(c); + + List> accountTags = new ArrayList>(); + Object[] aTag = new Object[accounts.size()]; + int i = 0; + for (AccountVO accountO : accounts) { + boolean accountIsAdmin = (accountO.getType() == Account.ACCOUNT_TYPE_ADMIN); + + List> accountData = new ArrayList>(); + accountData.add(new Pair(BaseCmd.Properties.ID.getName(), Long.valueOf(accountO.getId()).toString())); + accountData.add(new Pair(BaseCmd.Properties.NAME.getName(), accountO.getAccountName())); + accountData.add(new Pair(BaseCmd.Properties.ACCOUNT_TYPE.getName(), Short.valueOf(accountO.getType()).toString())); + Domain domain = getManagementServer().findDomainIdById(accountO.getDomainId()); + accountData.add(new Pair(BaseCmd.Properties.DOMAIN_ID.getName(), Long.toString(domain.getId()))); + accountData.add(new Pair(BaseCmd.Properties.DOMAIN.getName(), domain.getName())); + + //get network stat + List stats = getManagementServer().listUserStatsBy(accountO.getId()); + if (stats == null) { + throw new ServerApiException(BaseCmd.INTERNAL_ERROR, "Internal error searching for user stats"); + } + + long bytesSent = 0; + long bytesReceived = 0; + 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); + } + accountData.add(new Pair(BaseCmd.Properties.BYTES_RECEIVED.getName(), Long.valueOf(bytesReceived).toString())); + accountData.add(new Pair(BaseCmd.Properties.BYTES_SENT.getName(), Long.valueOf(bytesSent).toString())); + + // Get resource limits and counts + + long vmLimit = getManagementServer().findCorrectResourceLimit(ResourceType.user_vm, accountO.getId()); + String vmLimitDisplay = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit); + long vmTotal = getManagementServer().getResourceCount(ResourceType.user_vm, accountO.getId()); + String vmAvail = (accountIsAdmin || vmLimit == -1) ? "Unlimited" : String.valueOf(vmLimit - vmTotal); + accountData.add(new Pair(BaseCmd.Properties.VM_LIMIT.getName(), vmLimitDisplay)); + accountData.add(new Pair(BaseCmd.Properties.VM_TOTAL.getName(), vmTotal)); + accountData.add(new Pair(BaseCmd.Properties.VM_AVAIL.getName(), vmAvail)); + + long ipLimit = getManagementServer().findCorrectResourceLimit(ResourceType.public_ip, accountO.getId()); + String ipLimitDisplay = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit); + long ipTotal = getManagementServer().getResourceCount(ResourceType.public_ip, accountO.getId()); + String ipAvail = (accountIsAdmin || ipLimit == -1) ? "Unlimited" : String.valueOf(ipLimit - ipTotal); + accountData.add(new Pair(BaseCmd.Properties.IP_LIMIT.getName(), ipLimitDisplay)); + accountData.add(new Pair(BaseCmd.Properties.IP_TOTAL.getName(), ipTotal)); + accountData.add(new Pair(BaseCmd.Properties.IP_AVAIL.getName(), ipAvail)); + + long volumeLimit = getManagementServer().findCorrectResourceLimit(ResourceType.volume, accountO.getId()); + String volumeLimitDisplay = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit); + long volumeTotal = getManagementServer().getResourceCount(ResourceType.volume, accountO.getId()); + String volumeAvail = (accountIsAdmin || volumeLimit == -1) ? "Unlimited" : String.valueOf(volumeLimit - volumeTotal); + accountData.add(new Pair(BaseCmd.Properties.VOLUME_LIMIT.getName(), volumeLimitDisplay)); + accountData.add(new Pair(BaseCmd.Properties.VOLUME_TOTAL.getName(), volumeTotal)); + accountData.add(new Pair(BaseCmd.Properties.VOLUME_AVAIL.getName(), volumeAvail)); + + long snapshotLimit = getManagementServer().findCorrectResourceLimit(ResourceType.snapshot, accountO.getId()); + String snapshotLimitDisplay = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit); + long snapshotTotal = getManagementServer().getResourceCount(ResourceType.snapshot, accountO.getId()); + String snapshotAvail = (accountIsAdmin || snapshotLimit == -1) ? "Unlimited" : String.valueOf(snapshotLimit - snapshotTotal); + accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_LIMIT.getName(), snapshotLimitDisplay)); + accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_TOTAL.getName(), snapshotTotal)); + accountData.add(new Pair(BaseCmd.Properties.SNAPSHOT_AVAIL.getName(), snapshotAvail)); + + long templateLimit = getManagementServer().findCorrectResourceLimit(ResourceType.template, accountO.getId()); + String templateLimitDisplay = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit); + long templateTotal = getManagementServer().getResourceCount(ResourceType.template, accountO.getId()); + String templateAvail = (accountIsAdmin || templateLimit == -1) ? "Unlimited" : String.valueOf(templateLimit - templateTotal); + accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_LIMIT.getName(), templateLimitDisplay)); + accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_TOTAL.getName(), templateTotal)); + accountData.add(new Pair(BaseCmd.Properties.TEMPLATE_AVAIL.getName(), templateAvail)); + + // Get stopped and running VMs + + int vmStopped = 0; + int vmRunning = 0; + + Long[] accountIds = new Long[1]; + accountIds[0] = accountO.getId(); + + Criteria c1 = new Criteria(); + c1.addCriteria(Criteria.ACCOUNTID, accountIds); + List virtualMachines = getManagementServer().searchForUserVMs(c1); + + //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++; + } + } + + accountData.add(new Pair(BaseCmd.Properties.VM_STOPPED.getName(), vmStopped)); + accountData.add(new Pair(BaseCmd.Properties.VM_RUNNING.getName(), vmRunning)); + + //show this info to admins only + if (isAdmin == true) { + accountData.add(new Pair(BaseCmd.Properties.STATE.getName(), accountO.getState())); + accountData.add(new Pair(BaseCmd.Properties.IS_CLEANUP_REQUIRED.getName(), Boolean.valueOf(accountO.getNeedsCleanup()).toString())); + } + + aTag[i++] = accountData; + } + Pair accountTag = new Pair("account", aTag); + accountTags.add(accountTag); + return accountTags; + } +} diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index c477a6d226e..290bd49f0b3 100644 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -4402,6 +4402,7 @@ public class ManagementServerImpl implements ManagementServer { SearchBuilder sb = _accountDao.createSearchBuilder(); sb.and("accountName", sb.entity().getAccountName(), SearchCriteria.Op.LIKE); sb.and("id", sb.entity().getId(), SearchCriteria.Op.EQ); + sb.and("nid", sb.entity().getId(), SearchCriteria.Op.NEQ); 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); @@ -4433,6 +4434,9 @@ public class ManagementServerImpl implements ManagementServer { // I want to join on user_vm.domain_id = domain.id where domain.path like 'foo%' sc.setJoinParameters("domainSearch", "path", domain.getPath() + "%"); + sc.setParameters("nid", 1L); + } else { + sc.setParameters("nid", 1L); } if (type != null) { From 99c0c662a83eeec2b92a40bd6417363aa19faebc Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 18:01:59 -0700 Subject: [PATCH 019/235] Issue #: 5945 - replace index.html with index.jsp --- ui/index.jsp | 173 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100755 ui/index.jsp diff --git a/ui/index.jsp b/ui/index.jsp new file mode 100755 index 00000000000..8be1f714663 --- /dev/null +++ b/ui/index.jsp @@ -0,0 +1,173 @@ +<%@ page import="java.util.Date" %> + +<% +long milliseconds = new Date().getTime(); +%> + + + + + + + + + + + cloud.com - User Console + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Cloud.com CloudStack + + + + +
    +
    + + + + + + + + + +
    + + + + + + + + + +
    + + From 31081a681c6c645006bbb41191f03dd5fc0e3945 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 18:26:05 -0700 Subject: [PATCH 020/235] Issue #: 5945 - delete obsolete index.html Conflicts: ui/index.html --- ui/index.html | 168 -------------------------------------------------- 1 file changed, 168 deletions(-) delete mode 100644 ui/index.html diff --git a/ui/index.html b/ui/index.html deleted file mode 100644 index cd1ae182aa8..00000000000 --- a/ui/index.html +++ /dev/null @@ -1,168 +0,0 @@ - - - - - - - - - - cloud.com - User Console - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Cloud.com CloudStack - - - - -
    -
    - - - - - - - - - -
    - - - - - - - - - -
    - - From 73fb80e4248d4eb83958f1eacd411042bd9b0918 Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Wed, 25 Aug 2010 18:46:14 -0700 Subject: [PATCH 021/235] Swich back to vmdk extention temporarily --- api/src/com/cloud/storage/Storage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index 7ebdc5e187e..a9273b2c132 100644 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -23,7 +23,7 @@ public class Storage { RAW(false, false, false), VHD(true, true, true), ISO(false, false, false), - VMDK(true, true, true, ".tar.bz2"); + VMDK(true, true, true); private final boolean thinProvisioned; private final boolean supportSparse; From acb23b6158dc97d17bcb5dfda684fb778cdc0ba1 Mon Sep 17 00:00:00 2001 From: kishan Date: Thu, 26 Aug 2010 14:53:03 +0530 Subject: [PATCH 022/235] bug 5904,5474: added listCapabilities API --- client/tomcatconf/commands.properties.in | 3 +- .../com/cloud/server/ManagementServer.java | 1 + .../api/commands/ListCapabilitiesCmd.java | 58 +++++++++++++++++++ .../cloud/server/ManagementServerImpl.java | 20 +++++++ 4 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 server/src/com/cloud/api/commands/ListCapabilitiesCmd.java diff --git a/client/tomcatconf/commands.properties.in b/client/tomcatconf/commands.properties.in index fb62d18615e..47f934cabd4 100644 --- a/client/tomcatconf/commands.properties.in +++ b/client/tomcatconf/commands.properties.in @@ -139,6 +139,7 @@ listSystemVms=com.cloud.api.commands.ListSystemVMsCmd;1 updateConfiguration=com.cloud.api.commands.UpdateCfgCmd;1 listConfigurations=com.cloud.api.commands.ListCfgsByCmd;1 addConfig=com.cloud.api.commands.AddConfigCmd;15 +listCapabilities=com.cloud.api.commands.ListCapabilitiesCmd;15 #### pod commands createPod=com.cloud.api.commands.CreatePodCmd;1 @@ -207,4 +208,4 @@ listNetworkGroups=com.cloud.api.commands.ListNetworkGroupsCmd;11 registerPreallocatedLun=com.cloud.server.api.commands.RegisterPreallocatedLunCmd;1 deletePreallocatedLun=com.cloud.server.api.commands.DeletePreallocatedLunCmd;1 -listPreallocatedLuns=com.cloud.api.commands.ListPreallocatedLunsCmd;1 \ No newline at end of file +listPreallocatedLuns=com.cloud.api.commands.ListPreallocatedLunsCmd;1 diff --git a/core/src/com/cloud/server/ManagementServer.java b/core/src/com/cloud/server/ManagementServer.java index 840d9343ca6..85a3115ec07 100644 --- a/core/src/com/cloud/server/ManagementServer.java +++ b/core/src/com/cloud/server/ManagementServer.java @@ -2187,4 +2187,5 @@ public interface ManagementServer { boolean checkIfMaintenable(long hostId); + Map listCapabilities(); } diff --git a/server/src/com/cloud/api/commands/ListCapabilitiesCmd.java b/server/src/com/cloud/api/commands/ListCapabilitiesCmd.java new file mode 100644 index 00000000000..2532f3673d5 --- /dev/null +++ b/server/src/com/cloud/api/commands/ListCapabilitiesCmd.java @@ -0,0 +1,58 @@ +/** + * Copyright (C) 2010 Cloud.com, Inc. All rights reserved. + * + * This software is licensed under the GNU General Public License v3 or later. + * + * It is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or any later version. + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.cloud.api.commands; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; + +import com.cloud.api.BaseCmd; +import com.cloud.utils.Pair; + +public class ListCapabilitiesCmd extends BaseCmd { + public static final Logger s_logger = Logger.getLogger(ListCapabilitiesCmd.class.getName()); + + private static final String s_name = "listcapabilitiesresponse"; + private static final List> s_properties = new ArrayList>(); + + public String getName() { + return s_name; + } + public List> getProperties() { + return s_properties; + } + + @Override + public List> execute(Map params) { + + Map capabilities = null; + capabilities = getManagementServer().listCapabilities(); + + Iterator iterator = capabilities.keySet().iterator(); + List> capabilityPair = new ArrayList>(); + while (iterator.hasNext()) { + String capability = iterator.next(); + capabilityPair.add(new Pair(capability, capabilities.get(capability))); + } + return capabilityPair; + } +} diff --git a/server/src/com/cloud/server/ManagementServerImpl.java b/server/src/com/cloud/server/ManagementServerImpl.java index 290bd49f0b3..f83a482ac78 100644 --- a/server/src/com/cloud/server/ManagementServerImpl.java +++ b/server/src/com/cloud/server/ManagementServerImpl.java @@ -8594,6 +8594,26 @@ public class ManagementServerImpl implements ManagementServer { return false; } + @Override + public Map listCapabilities() { + Map capabilities = new HashMap(); + + String networkGroupsEnabled = _configs.get("direct.attach.network.groups.enabled"); + if(networkGroupsEnabled == null) + networkGroupsEnabled = "false"; + + capabilities.put("networkGroupsEnabled", networkGroupsEnabled); + + final Class c = this.getClass(); + String fullVersion = c.getPackage().getImplementationVersion(); + String version = "unknown"; + if(fullVersion.length() > 0){ + version = fullVersion.substring(0,fullVersion.lastIndexOf(".")); + } + capabilities.put("cloudStackVersion", version); + return capabilities; + } + } From fb99f95d7cb5c8dfa4219145d8d40ddbdcb1c013 Mon Sep 17 00:00:00 2001 From: kishan Date: Thu, 26 Aug 2010 21:02:37 +0530 Subject: [PATCH 023/235] bug 5730: update dns of systemVms during zone update --- client/tomcatconf/components.xml.in | 5 +- core/src/com/cloud/vm/dao/VMInstanceDao.java | 1 + .../com/cloud/vm/dao/VMInstanceDaoImpl.java | 15 ++++ .../ConfigurationManagerImpl.java | 79 +++++++++++++------ 4 files changed, 75 insertions(+), 25 deletions(-) diff --git a/client/tomcatconf/components.xml.in b/client/tomcatconf/components.xml.in index ce698854bbe..9365e78ead9 100755 --- a/client/tomcatconf/components.xml.in +++ b/client/tomcatconf/components.xml.in @@ -215,8 +215,9 @@ - - + + + diff --git a/core/src/com/cloud/vm/dao/VMInstanceDao.java b/core/src/com/cloud/vm/dao/VMInstanceDao.java index 653445ad331..d496a80f4f3 100644 --- a/core/src/com/cloud/vm/dao/VMInstanceDao.java +++ b/core/src/com/cloud/vm/dao/VMInstanceDao.java @@ -80,4 +80,5 @@ public interface VMInstanceDao extends GenericDao { List listByHostIdTypes(long hostid, VirtualMachine.Type... types); List listUpByHostIdTypes(long hostid, VirtualMachine.Type... types); + List listByZoneIdAndType(long zoneId, VirtualMachine.Type type); } diff --git a/core/src/com/cloud/vm/dao/VMInstanceDaoImpl.java b/core/src/com/cloud/vm/dao/VMInstanceDaoImpl.java index 3ec6b2a12dc..d625db08bf7 100644 --- a/core/src/com/cloud/vm/dao/VMInstanceDaoImpl.java +++ b/core/src/com/cloud/vm/dao/VMInstanceDaoImpl.java @@ -51,6 +51,7 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem protected final SearchBuilder HostSearch; protected final SearchBuilder LastHostSearch; protected final SearchBuilder ZoneSearch; + protected final SearchBuilder ZoneVmTypeSearch; protected final SearchBuilder ZoneTemplateNonExpungedSearch; protected final SearchBuilder NameLikeSearch; protected final SearchBuilder StateChangeSearch; @@ -79,6 +80,11 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem ZoneSearch = createSearchBuilder(); ZoneSearch.and("zone", ZoneSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); ZoneSearch.done(); + + ZoneVmTypeSearch = createSearchBuilder(); + ZoneVmTypeSearch.and("zone", ZoneVmTypeSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); + ZoneVmTypeSearch.and("type", ZoneVmTypeSearch.entity().getType(), SearchCriteria.Op.EQ); + ZoneVmTypeSearch.done(); ZoneTemplateNonExpungedSearch = createSearchBuilder(); ZoneTemplateNonExpungedSearch.and("zone", ZoneTemplateNonExpungedSearch.entity().getDataCenterId(), SearchCriteria.Op.EQ); @@ -193,6 +199,15 @@ public class VMInstanceDaoImpl extends GenericDaoBase implem return listActiveBy(sc); } + @Override + public List listByZoneIdAndType(long zoneId, VirtualMachine.Type type) { + SearchCriteria sc = ZoneVmTypeSearch.create(); + sc.setParameters("zone", zoneId); + sc.setParameters("type", type.toString()); + return listActiveBy(sc); + } + + @Override public List listNonExpungedByZoneAndTemplate(long zoneId, long templateId) { SearchCriteria sc = ZoneTemplateNonExpungedSearch.create(); diff --git a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java index 047da0d1bef..9978cee29b1 100644 --- a/server/src/com/cloud/configuration/ConfigurationManagerImpl.java +++ b/server/src/com/cloud/configuration/ConfigurationManagerImpl.java @@ -57,6 +57,7 @@ import com.cloud.offering.NetworkOffering.GuestIpType; import com.cloud.service.ServiceOfferingVO; import com.cloud.service.dao.ServiceOfferingDao; import com.cloud.storage.DiskOfferingVO; +import com.cloud.storage.SecondaryStorage; import com.cloud.storage.dao.DiskOfferingDao; import com.cloud.user.AccountVO; import com.cloud.user.UserVO; @@ -66,9 +67,14 @@ import com.cloud.utils.component.Inject; import com.cloud.utils.db.DB; import com.cloud.utils.db.Transaction; import com.cloud.utils.net.NetUtils; +import com.cloud.vm.ConsoleProxyVO; import com.cloud.vm.DomainRouterVO; +import com.cloud.vm.SecondaryStorageVmVO; import com.cloud.vm.VMInstanceVO; +import com.cloud.vm.VirtualMachine; +import com.cloud.vm.dao.ConsoleProxyDao; import com.cloud.vm.dao.DomainRouterDao; +import com.cloud.vm.dao.SecondaryStorageVmDao; import com.cloud.vm.dao.VMInstanceDao; @Local(value={ConfigurationManager.class}) @@ -91,6 +97,8 @@ public class ConfigurationManagerImpl implements ConfigurationManager { @Inject AccountDao _accountDao; @Inject EventDao _eventDao; @Inject UserDao _userDao; + @Inject ConsoleProxyDao _consoleDao; + @Inject SecondaryStorageVmDao _secStorageDao; public boolean _premium; @Override @@ -665,13 +673,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager { throw new InvalidParameterValueException("A zone with ID: " + zoneId + " does not exist."); } - // If DNS values are being changed, make sure there are no VMs in this zone - if (dns1 != null || dns2 != null || internalDns1 != null || internalDns2 != null) { - if (zoneHasVMs(zoneId)) { - throw new InternalErrorException("The zone is not editable because there are VMs in the zone."); - } - } - // If the Vnet range is being changed, make sure there are no allocated VNets if (vnetRange != null) { if (zoneHasAllocatedVnets(zoneId)) { @@ -679,22 +680,6 @@ public class ConfigurationManagerImpl implements ConfigurationManager { } } - //To modify a zone, we need to make sure there are no domr's associated with it - //1. List all the domain router objs - //2. Check if any of these has the current data center associated - //3. If yes, throw exception - //4, If no, edit - List allDomainRoutersAvailable = _domrDao.listAll(); - - for(DomainRouterVO domR : allDomainRoutersAvailable) - { - if(domR.getDataCenterId() == zoneId) - { - throw new InternalErrorException("The zone is not editable because there are domR's associated with the zone."); - } - } - - //5. Reached here, hence editable DataCenterVO zone = _zoneDao.findById(zoneId); String oldZoneName = zone.getName(); @@ -703,6 +688,12 @@ public class ConfigurationManagerImpl implements ConfigurationManager { newZoneName = oldZoneName; } + boolean dnsUpdate = false; + + if(dns1 != null || dns2 != null){ + dnsUpdate = true; + } + if (dns1 == null) { dns1 = zone.getDns1(); } @@ -742,6 +733,48 @@ public class ConfigurationManagerImpl implements ConfigurationManager { _zoneDao.addVnet(zone.getId(), begin, end); } + if(dnsUpdate){ + + //Update dns for domRs in zone + + List DomainRouters = _domrDao.listByDataCenter(zoneId); + + for(DomainRouterVO domR : DomainRouters) + { + domR.setDns1(dns1); + domR.setDns2(dns2); + _domrDao.update(domR.getId(), domR); + } + + //Update dns for console proxies in zone + List ConsoleProxies = _vmInstanceDao.listByZoneIdAndType(zoneId, VirtualMachine.Type.ConsoleProxy); + + for(VMInstanceVO consoleVm : ConsoleProxies) + { + ConsoleProxyVO proxy = _consoleDao.findById(consoleVm.getId()); + if( proxy!= null ){ + proxy.setDns1(dns1); + proxy.setDns2(dns2); + _consoleDao.update(proxy.getId(), proxy); + } + } + + //Update dns for secondary storage Vms in zone + List storageVms = _vmInstanceDao.listByZoneIdAndType(zoneId, VirtualMachine.Type.SecondaryStorageVm); + + for(VMInstanceVO storageVm : storageVms) + { + SecondaryStorageVmVO secStorageVm = _secStorageDao.findById(storageVm.getId()); + if( secStorageVm!= null ){ + secStorageVm.setDns1(dns1); + secStorageVm.setDns2(dns2); + _secStorageDao.update(secStorageVm.getId(), secStorageVm); + } + } + + } + + saveConfigurationEvent(userId, null, EventTypes.EVENT_ZONE_EDIT, "Successfully edited zone with name: " + zone.getName() + ".", "dcId=" + zone.getId(), "dns1=" + dns1, "dns2=" + dns2, "internalDns1=" + internalDns1, "internalDns2=" + internalDns2, "vnetRange=" + vnetRange, "guestCidr=" + guestCidr); return zone; From 0e2df1fe42b30e18c9ef1b6c653d84fb99dcb816 Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Thu, 26 Aug 2010 09:43:37 -0700 Subject: [PATCH 024/235] Use dummy template package to speed up debug --- api/src/com/cloud/storage/Storage.java | 2 +- setup/db/templates.vmware.sql | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/api/src/com/cloud/storage/Storage.java b/api/src/com/cloud/storage/Storage.java index a9273b2c132..81d94ad0331 100644 --- a/api/src/com/cloud/storage/Storage.java +++ b/api/src/com/cloud/storage/Storage.java @@ -23,7 +23,7 @@ public class Storage { RAW(false, false, false), VHD(true, true, true), ISO(false, false, false), - VMDK(true, true, true); + VMDK(true, true, true, "vmw.tar"); private final boolean thinProvisioned; private final boolean supportSparse; diff --git a/setup/db/templates.vmware.sql b/setup/db/templates.vmware.sql index 572e42107a9..680fb06e0da 100644 --- a/setup/db/templates.vmware.sql +++ b/setup/db/templates.vmware.sql @@ -1,7 +1,9 @@ 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) - VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); -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) - VALUES (2, 'fedora11-x86', 'Fedora 11 x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); + VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/dummydomr.tar.bz2', '54c578d2c02759de4a9a8be7bd533df1', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); + +-- +--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) +-- VALUES (2, 'fedora11-x86', 'Fedora11-x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'Windows'); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Linux'); From a3a503fecbf21b1e78a4afe77b0fe3f6a63fb01c Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Thu, 26 Aug 2010 10:07:13 -0700 Subject: [PATCH 025/235] Use ImageFormat.getFileExtension instead of toString() to retrieve template file extension name --- core/src/com/cloud/storage/template/DownloadManagerImpl.java | 2 +- core/src/com/cloud/storage/template/VmdkProcessor.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/com/cloud/storage/template/DownloadManagerImpl.java b/core/src/com/cloud/storage/template/DownloadManagerImpl.java index 8d41e293e6a..3a69471fbb9 100644 --- a/core/src/com/cloud/storage/template/DownloadManagerImpl.java +++ b/core/src/com/cloud/storage/template/DownloadManagerImpl.java @@ -303,7 +303,7 @@ public class DownloadManagerImpl implements DownloadManager { } // add options common to ISO and template - String extension = dnld.getFormat().toString().toLowerCase(); + String extension = dnld.getFormat().getFileExtension(); String templateName = ""; if( extension.equals("iso")) { templateName = jobs.get(jobId).getTmpltName().trim().replace(" ", "_"); diff --git a/core/src/com/cloud/storage/template/VmdkProcessor.java b/core/src/com/cloud/storage/template/VmdkProcessor.java index fe060ab02de..d1e522196b1 100644 --- a/core/src/com/cloud/storage/template/VmdkProcessor.java +++ b/core/src/com/cloud/storage/template/VmdkProcessor.java @@ -26,7 +26,7 @@ public class VmdkProcessor implements Processor { } s_logger.info("Template processing. templatePath: " + templatePath + ", templateName: " + templateName); - String templateFilePath = templatePath + File.separator + templateName + ImageFormat.VMDK.getFileExtension(); + String templateFilePath = templatePath + File.separator + templateName + "." + ImageFormat.VMDK.getFileExtension(); if (!_storage.exists(templateFilePath)) { if(s_logger.isInfoEnabled()) s_logger.info("Unable to find the vmware template file: " + templateFilePath); @@ -35,7 +35,7 @@ public class VmdkProcessor implements Processor { FormatInfo info = new FormatInfo(); info.format = ImageFormat.VMDK; - info.filename = templateName + ImageFormat.VMDK.getFileExtension(); + info.filename = templateName + "." + ImageFormat.VMDK.getFileExtension(); info.size = _storage.getSize(templateFilePath); info.virtualSize = info.size; return info; From 43169f3f96192a4b5f4ac7837431e08367e6e42f Mon Sep 17 00:00:00 2001 From: kishan Date: Thu, 26 Aug 2010 23:39:32 +0530 Subject: [PATCH 026/235] bug 5895: added config param to turn on/off md5 hash --- server/src/com/cloud/configuration/Config.java | 1 + 1 file changed, 1 insertion(+) diff --git a/server/src/com/cloud/configuration/Config.java b/server/src/com/cloud/configuration/Config.java index d46e8f28211..c97749a6bc8 100644 --- a/server/src/com/cloud/configuration/Config.java +++ b/server/src/com/cloud/configuration/Config.java @@ -146,6 +146,7 @@ public enum Config { DirectAttachNetworkExternalAPIURL("Advanced", ManagementServer.class, String.class, "direct.attach.network.externalIpAllocator.url", null, "Direct-attach VMs using external DHCP server (API url)", null), DirectAttachUntaggedVlanEnabled("Advanced", ManagementServer.class, String.class, "direct.attach.untagged.vlan.enabled", "false", "Indicate whether the system supports direct-attached untagged vlan", "true,false"), CheckPodCIDRs("Advanced", ManagementServer.class, String.class, "check.pod.cidrs", "true", "If true, different pods must belong to different CIDR subnets.", "true,false"), + MD5Hashed("Advanced", ManagementServer.class, Boolean.class, "security.password.md5hashed", "true", "If set to false password is sent in clear text or else md5hashed", null), // XenServer VmAllocationAlgorithm("Advanced", ManagementServer.class, String.class, "vm.allocation.algorithm", "random", "If 'random', hosts within a pod will be randomly considered for VM/volume allocation. If 'firstfit', they will be considered on a first-fit basis.", null), From bbb307c82dd8472f28816c837b424f4153da4f59 Mon Sep 17 00:00:00 2001 From: Kelven Yang Date: Thu, 26 Aug 2010 11:22:12 -0700 Subject: [PATCH 027/235] Explode vmware template file in place --- core/src/com/cloud/storage/template/DownloadManagerImpl.java | 1 + setup/db/templates.vmware.sql | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/src/com/cloud/storage/template/DownloadManagerImpl.java b/core/src/com/cloud/storage/template/DownloadManagerImpl.java index 3a69471fbb9..2d37f630fe3 100644 --- a/core/src/com/cloud/storage/template/DownloadManagerImpl.java +++ b/core/src/com/cloud/storage/template/DownloadManagerImpl.java @@ -353,6 +353,7 @@ public class DownloadManagerImpl implements DownloadManager { try { info = processor.process(templatePath, null, templateName); } catch (InternalErrorException e) { + s_logger.error("Template process exception ", e); return e.toString(); } if (info != null) { diff --git a/setup/db/templates.vmware.sql b/setup/db/templates.vmware.sql index 680fb06e0da..53080bc6277 100644 --- a/setup/db/templates.vmware.sql +++ b/setup/db/templates.vmware.sql @@ -1,9 +1,8 @@ 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) VALUES (1, 'routing', 'SystemVM Template', 0, now(), 'ext3', 0, 64, 1, 'http://nfs1.lab.vmops.com/templates/vmware/dummydomr.tar.bz2', '54c578d2c02759de4a9a8be7bd533df1', 0, 'SystemVM Template', 'VMDK', 47, 0, 1); --- ---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) --- VALUES (2, 'fedora11-x86', 'Fedora11-x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); +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) + VALUES (2, 'fedora11-x86', 'Fedora11-x86', 1, now(), 'ext3', 0, 32, 1, 'http://nfs1.lab.vmops.com/templates/vmware/fedora11-x86.tar.bz2', '7957ff05cae838689eb53c7600b2fbe4', 0, 'Fedora 11 x86', 'VMDK', 47, 1, 1); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (1, 'Windows'); INSERT INTO `cloud`.`guest_os_category` (id, name) VALUES (2, 'Linux'); From 01508aa6b341c4493706d4a97ca3a0ea9f921e2f Mon Sep 17 00:00:00 2001 From: jessica Date: Thu, 26 Aug 2010 11:51:33 -0700 Subject: [PATCH 028/235] Issue #: 5945 - replace all content/tab_xxxxxxx.html with jsp/tab_xxxxxxx.jsp --- .../tab_accounts.jsp} | 6 +++++- .../tab_configuration.jsp} | 6 +++++- .../tab_dashboard.jsp} | 0 ui/jsp/tab_domains.jsp | 7 +++++-- .../tab_events.html => jsp/tab_events.jsp} | 6 +++++- .../tab_hosts.html => jsp/tab_hosts.jsp} | 6 +++++- .../tab_instances.jsp} | 6 +++++- .../tab_networking.jsp} | 6 +++++- .../tab_storage.html => jsp/tab_storage.jsp} | 6 +++++- .../tab_templates.jsp} | 6 +++++- ui/scripts/cloud.core.domains.js | 6 +++--- ui/scripts/cloud.core.init.js | 20 +++++++++---------- 12 files changed, 58 insertions(+), 23 deletions(-) rename ui/{content/tab_accounts.html => jsp/tab_accounts.jsp} (98%) mode change 100644 => 100755 rename ui/{content/tab_configuration.html => jsp/tab_configuration.jsp} (99%) mode change 100644 => 100755 rename ui/{content/tab_dashboard.html => jsp/tab_dashboard.jsp} (100%) mode change 100644 => 100755 mode change 100644 => 100755 ui/jsp/tab_domains.jsp rename ui/{content/tab_events.html => jsp/tab_events.jsp} (98%) mode change 100644 => 100755 rename ui/{content/tab_hosts.html => jsp/tab_hosts.jsp} (98%) mode change 100644 => 100755 rename ui/{content/tab_instances.html => jsp/tab_instances.jsp} (99%) mode change 100644 => 100755 rename ui/{content/tab_networking.html => jsp/tab_networking.jsp} (99%) mode change 100644 => 100755 rename ui/{content/tab_storage.html => jsp/tab_storage.jsp} (99%) mode change 100644 => 100755 rename ui/{content/tab_templates.html => jsp/tab_templates.jsp} (99%) mode change 100644 => 100755 diff --git a/ui/content/tab_accounts.html b/ui/jsp/tab_accounts.jsp old mode 100644 new mode 100755 similarity index 98% rename from ui/content/tab_accounts.html rename to ui/jsp/tab_accounts.jsp index 5a63bb419c5..df4da1544c5 --- a/ui/content/tab_accounts.html +++ b/ui/jsp/tab_accounts.jsp @@ -1,4 +1,8 @@ - +<%@ page import="java.util.Date" %> +<% +long milliseconds = new Date().getTime(); +%> + ").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"}); +c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=j.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,show:function(c){if(!c|| +typeof c=="number"||f.fx.speeds[c])return this._show.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c])return this._hide.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||typeof c=="boolean"||f.isFunction(c))return this.__toggle.apply(this, +arguments);else{var a=j.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c, +a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+ +b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2, +10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)* +a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h
    ").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+ +e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery); +;/* + * jQuery UI Effects Fold 1.8.2 + * + * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Effects/Fold + * + * Depends: + * jquery.effects.core.js + */ +(function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","left"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1],10)/100* +f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery); +;/* + * jQuery UI Effects Highlight 1.8.2 + * + * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Effects/Highlight + * + * Depends: + * jquery.effects.core.js + */ +(function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="show"&&!b.support.opacity&& +this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery); +;/* + * jQuery UI Effects Pulsate 1.8.2 + * + * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about) + * Dual licensed under the MIT (MIT-LICENSE.txt) + * and GPL (GPL-LICENSE.txt) licenses. + * + * http://docs.jquery.com/UI/Effects/Pulsate + * + * Depends: + * jquery.effects.core.js + */ +(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c
    ').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments); +b.dequeue()})})}})(jQuery); +; \ No newline at end of file diff --git a/ui/new/scripts/jquery.cookies.js b/ui/new/scripts/jquery.cookies.js new file mode 100755 index 00000000000..6036754e815 --- /dev/null +++ b/ui/new/scripts/jquery.cookies.js @@ -0,0 +1,96 @@ +/** + * Cookie plugin + * + * Copyright (c) 2006 Klaus Hartl (stilbuero.de) + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + */ + +/** + * Create a cookie with the given name and value and other optional parameters. + * + * @example $.cookie('the_cookie', 'the_value'); + * @desc Set the value of a cookie. + * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); + * @desc Create a cookie with all available options. + * @example $.cookie('the_cookie', 'the_value'); + * @desc Create a session cookie. + * @example $.cookie('the_cookie', null); + * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain + * used when the cookie was set. + * + * @param String name The name of the cookie. + * @param String value The value of the cookie. + * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. + * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. + * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. + * If set to null or omitted, the cookie will be a session cookie and will not be retained + * when the the browser exits. + * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). + * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). + * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will + * require a secure protocol (like HTTPS). + * @type undefined + * + * @name $.cookie + * @cat Plugins/Cookie + * @author Klaus Hartl/klaus.hartl@stilbuero.de + */ + +/** + * Get the value of a cookie with the given name. + * + * @example $.cookie('the_cookie'); + * @desc Get the value of a cookie. + * + * @param String name The name of the cookie. + * @return The value of the cookie. + * @type String + * + * @name $.cookie + * @cat Plugins/Cookie + * @author Klaus Hartl/klaus.hartl@stilbuero.de + */ +jQuery.cookie = function(name, value, options) { + if (typeof value != 'undefined') { // name and value given, set cookie + options = options || {}; + if (value === null) { + value = ''; + options.expires = -1; + } + var expires = ''; + if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) { + var date; + if (typeof options.expires == 'number') { + date = new Date(); + date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); + } else { + date = options.expires; + } + expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE + } + // CAUTION: Needed to parenthesize options.path and options.domain + // in the following expressions, otherwise they evaluate to undefined + // in the packed version for some reason... + var path = options.path ? '; path=' + (options.path) : ''; + var domain = options.domain ? '; domain=' + (options.domain) : ''; + var secure = options.secure ? '; secure' : ''; + document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join(''); + } else { // only name given, get cookie + var cookieValue = null; + if (document.cookie && document.cookie != '') { + var cookies = document.cookie.split(';'); + for (var i = 0; i < cookies.length; i++) { + var cookie = jQuery.trim(cookies[i]); + // Does this cookie string begin with the name we want? + if (cookie.substring(0, name.length + 1) == (name + '=')) { + cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); + break; + } + } + } + return cookieValue; + } +}; \ No newline at end of file diff --git a/ui/new/scripts/jquery.md5.js b/ui/new/scripts/jquery.md5.js new file mode 100755 index 00000000000..54885ab451d --- /dev/null +++ b/ui/new/scripts/jquery.md5.js @@ -0,0 +1,229 @@ + /** + * jQuery MD5 hash algorithm function + * + * + * Calculate the md5 hash of a String + * String $.md5 ( String str ) + * + * + * Calculates the MD5 hash of str using the RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash. + * MD5 (Message-Digest algorithm 5) is a widely-used cryptographic hash function with a 128-bit hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of data. The generated hash is also non-reversable. Data cannot be retrieved from the message digest, the digest uniquely identifies the data. + * MD5 was developed by Professor Ronald L. Rivest in 1994. Its 128 bit (16 byte) message digest makes it a faster implementation than SHA-1. + * This script is used to process a variable length message into a fixed-length output of 128 bits using the MD5 algorithm. It is fully compatible with UTF-8 encoding. It is very useful when u want to transfer encrypted passwords over the internet. If you plan using UTF-8 encoding in your project don't forget to set the page encoding to UTF-8 (Content-Type meta tag). + * This function orginally get from the WebToolkit and rewrite for using as the jQuery plugin. + * + * Example + * Code + * + * $.md5("I'm Persian."); + * + * Result + * + * "b8c901d0f02223f9761016cfff9d68df" + * + * + * @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com > + * @link http://www.semnanweb.com/jquery-plugin/md5.html + * @see http://www.webtoolkit.info/ + * @license http://www.gnu.org/licenses/gpl.html [GNU General Public License] + * @param {jQuery} {md5:function(string)) + * @return string + */ + + (function($){ + + var rotateLeft = function(lValue, iShiftBits) { + return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits)); + } + + var addUnsigned = function(lX, lY) { + var lX4, lY4, lX8, lY8, lResult; + lX8 = (lX & 0x80000000); + lY8 = (lY & 0x80000000); + lX4 = (lX & 0x40000000); + lY4 = (lY & 0x40000000); + lResult = (lX & 0x3FFFFFFF) + (lY & 0x3FFFFFFF); + if (lX4 & lY4) return (lResult ^ 0x80000000 ^ lX8 ^ lY8); + if (lX4 | lY4) { + if (lResult & 0x40000000) return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); + else return (lResult ^ 0x40000000 ^ lX8 ^ lY8); + } else { + return (lResult ^ lX8 ^ lY8); + } + } + + var F = function(x, y, z) { + return (x & y) | ((~ x) & z); + } + + var G = function(x, y, z) { + return (x & z) | (y & (~ z)); + } + + var H = function(x, y, z) { + return (x ^ y ^ z); + } + + var I = function(x, y, z) { + return (y ^ (x | (~ z))); + } + + var FF = function(a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(F(b, c, d), x), ac)); + return addUnsigned(rotateLeft(a, s), b); + }; + + var GG = function(a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(G(b, c, d), x), ac)); + return addUnsigned(rotateLeft(a, s), b); + }; + + var HH = function(a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(H(b, c, d), x), ac)); + return addUnsigned(rotateLeft(a, s), b); + }; + + var II = function(a, b, c, d, x, s, ac) { + a = addUnsigned(a, addUnsigned(addUnsigned(I(b, c, d), x), ac)); + return addUnsigned(rotateLeft(a, s), b); + }; + + var convertToWordArray = function(string) { + var lWordCount; + var lMessageLength = string.length; + var lNumberOfWordsTempOne = lMessageLength + 8; + var lNumberOfWordsTempTwo = (lNumberOfWordsTempOne - (lNumberOfWordsTempOne % 64)) / 64; + var lNumberOfWords = (lNumberOfWordsTempTwo + 1) * 16; + var lWordArray = Array(lNumberOfWords - 1); + var lBytePosition = 0; + var lByteCount = 0; + while (lByteCount < lMessageLength) { + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount) << lBytePosition)); + lByteCount++; + } + lWordCount = (lByteCount - (lByteCount % 4)) / 4; + lBytePosition = (lByteCount % 4) * 8; + lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80 << lBytePosition); + lWordArray[lNumberOfWords - 2] = lMessageLength << 3; + lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29; + return lWordArray; + }; + + var wordToHex = function(lValue) { + var WordToHexValue = "", WordToHexValueTemp = "", lByte, lCount; + for (lCount = 0; lCount <= 3; lCount++) { + lByte = (lValue >>> (lCount * 8)) & 255; + WordToHexValueTemp = "0" + lByte.toString(16); + WordToHexValue = WordToHexValue + WordToHexValueTemp.substr(WordToHexValueTemp.length - 2, 2); + } + return WordToHexValue; + }; + + var uTF8Encode = function(string) { + string = string.replace(/\x0d\x0a/g, "\x0a"); + var output = ""; + for (var n = 0; n < string.length; n++) { + var c = string.charCodeAt(n); + if (c < 128) { + output += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + output += String.fromCharCode((c >> 6) | 192); + output += String.fromCharCode((c & 63) | 128); + } else { + output += String.fromCharCode((c >> 12) | 224); + output += String.fromCharCode(((c >> 6) & 63) | 128); + output += String.fromCharCode((c & 63) | 128); + } + } + return output; + }; + + $.extend({ + md5: function(string) { + var x = Array(); + var k, AA, BB, CC, DD, a, b, c, d; + var S11=7, S12=12, S13=17, S14=22; + var S21=5, S22=9 , S23=14, S24=20; + var S31=4, S32=11, S33=16, S34=23; + var S41=6, S42=10, S43=15, S44=21; + string = uTF8Encode(string); + x = convertToWordArray(string); + a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; + for (k = 0; k < x.length; k += 16) { + AA = a; BB = b; CC = c; DD = d; + a = FF(a, b, c, d, x[k+0], S11, 0xD76AA478); + d = FF(d, a, b, c, x[k+1], S12, 0xE8C7B756); + c = FF(c, d, a, b, x[k+2], S13, 0x242070DB); + b = FF(b, c, d, a, x[k+3], S14, 0xC1BDCEEE); + a = FF(a, b, c, d, x[k+4], S11, 0xF57C0FAF); + d = FF(d, a, b, c, x[k+5], S12, 0x4787C62A); + c = FF(c, d, a, b, x[k+6], S13, 0xA8304613); + b = FF(b, c, d, a, x[k+7], S14, 0xFD469501); + a = FF(a, b, c, d, x[k+8], S11, 0x698098D8); + d = FF(d, a, b, c, x[k+9], S12, 0x8B44F7AF); + c = FF(c, d, a, b, x[k+10], S13, 0xFFFF5BB1); + b = FF(b, c, d, a, x[k+11], S14, 0x895CD7BE); + a = FF(a, b, c, d, x[k+12], S11, 0x6B901122); + d = FF(d, a, b, c, x[k+13], S12, 0xFD987193); + c = FF(c, d, a, b, x[k+14], S13, 0xA679438E); + b = FF(b, c, d, a, x[k+15], S14, 0x49B40821); + a = GG(a, b, c, d, x[k+1], S21, 0xF61E2562); + d = GG(d, a, b, c, x[k+6], S22, 0xC040B340); + c = GG(c, d, a, b, x[k+11], S23, 0x265E5A51); + b = GG(b, c, d, a, x[k+0], S24, 0xE9B6C7AA); + a = GG(a, b, c, d, x[k+5], S21, 0xD62F105D); + d = GG(d, a, b, c, x[k+10], S22, 0x2441453); + c = GG(c, d, a, b, x[k+15], S23, 0xD8A1E681); + b = GG(b, c, d, a, x[k+4], S24, 0xE7D3FBC8); + a = GG(a, b, c, d, x[k+9], S21, 0x21E1CDE6); + d = GG(d, a, b, c, x[k+14], S22, 0xC33707D6); + c = GG(c, d, a, b, x[k+3], S23, 0xF4D50D87); + b = GG(b, c, d, a, x[k+8], S24, 0x455A14ED); + a = GG(a, b, c, d, x[k+13], S21, 0xA9E3E905); + d = GG(d, a, b, c, x[k+2], S22, 0xFCEFA3F8); + c = GG(c, d, a, b, x[k+7], S23, 0x676F02D9); + b = GG(b, c, d, a, x[k+12], S24, 0x8D2A4C8A); + a = HH(a, b, c, d, x[k+5], S31, 0xFFFA3942); + d = HH(d, a, b, c, x[k+8], S32, 0x8771F681); + c = HH(c, d, a, b, x[k+11], S33, 0x6D9D6122); + b = HH(b, c, d, a, x[k+14], S34, 0xFDE5380C); + a = HH(a, b, c, d, x[k+1], S31, 0xA4BEEA44); + d = HH(d, a, b, c, x[k+4], S32, 0x4BDECFA9); + c = HH(c, d, a, b, x[k+7], S33, 0xF6BB4B60); + b = HH(b, c, d, a, x[k+10], S34, 0xBEBFBC70); + a = HH(a, b, c, d, x[k+13], S31, 0x289B7EC6); + d = HH(d, a, b, c, x[k+0], S32, 0xEAA127FA); + c = HH(c, d, a, b, x[k+3], S33, 0xD4EF3085); + b = HH(b, c, d, a, x[k+6], S34, 0x4881D05); + a = HH(a, b, c, d, x[k+9], S31, 0xD9D4D039); + d = HH(d, a, b, c, x[k+12], S32, 0xE6DB99E5); + c = HH(c, d, a, b, x[k+15], S33, 0x1FA27CF8); + b = HH(b, c, d, a, x[k+2], S34, 0xC4AC5665); + a = II(a, b, c, d, x[k+0], S41, 0xF4292244); + d = II(d, a, b, c, x[k+7], S42, 0x432AFF97); + c = II(c, d, a, b, x[k+14], S43, 0xAB9423A7); + b = II(b, c, d, a, x[k+5], S44, 0xFC93A039); + a = II(a, b, c, d, x[k+12], S41, 0x655B59C3); + d = II(d, a, b, c, x[k+3], S42, 0x8F0CCC92); + c = II(c, d, a, b, x[k+10], S43, 0xFFEFF47D); + b = II(b, c, d, a, x[k+1], S44, 0x85845DD1); + a = II(a, b, c, d, x[k+8], S41, 0x6FA87E4F); + d = II(d, a, b, c, x[k+15], S42, 0xFE2CE6E0); + c = II(c, d, a, b, x[k+6], S43, 0xA3014314); + b = II(b, c, d, a, x[k+13], S44, 0x4E0811A1); + a = II(a, b, c, d, x[k+4], S41, 0xF7537E82); + d = II(d, a, b, c, x[k+11], S42, 0xBD3AF235); + c = II(c, d, a, b, x[k+2], S43, 0x2AD7D2BB); + b = II(b, c, d, a, x[k+9], S44, 0xEB86D391); + a = addUnsigned(a, AA); + b = addUnsigned(b, BB); + c = addUnsigned(c, CC); + d = addUnsigned(d, DD); + } + var tempValue = wordToHex(a) + wordToHex(b) + wordToHex(c) + wordToHex(d); + return tempValue.toLowerCase(); + } + }); + })(jQuery); diff --git a/ui/new/scripts/jquery.timers.js b/ui/new/scripts/jquery.timers.js new file mode 100755 index 00000000000..bb51157d405 --- /dev/null +++ b/ui/new/scripts/jquery.timers.js @@ -0,0 +1,138 @@ +/** + * jQuery.timers - Timer abstractions for jQuery + * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com) + * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/). + * Date: 2009/10/16 + * + * @author Blair Mitchelmore + * @version 1.2 + * + **/ + +jQuery.fn.extend({ + everyTime: function(interval, label, fn, times) { + return this.each(function() { + jQuery.timer.add(this, interval, label, fn, times); + }); + }, + oneTime: function(interval, label, fn) { + return this.each(function() { + jQuery.timer.add(this, interval, label, fn, 1); + }); + }, + stopTime: function(label, fn) { + return this.each(function() { + jQuery.timer.remove(this, label, fn); + }); + } +}); + +jQuery.extend({ + timer: { + global: [], + guid: 1, + dataKey: "jQuery.timer", + regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/, + powers: { + // Yeah this is major overkill... + 'ms': 1, + 'cs': 10, + 'ds': 100, + 's': 1000, + 'das': 10000, + 'hs': 100000, + 'ks': 1000000 + }, + timeParse: function(value) { + if (value == undefined || value == null) + return null; + var result = this.regex.exec(jQuery.trim(value.toString())); + if (result[2]) { + var num = parseFloat(result[1]); + var mult = this.powers[result[2]] || 1; + return num * mult; + } else { + return value; + } + }, + add: function(element, interval, label, fn, times) { + var counter = 0; + + if (jQuery.isFunction(label)) { + if (!times) + times = fn; + fn = label; + label = interval; + } + + interval = jQuery.timer.timeParse(interval); + + if (typeof interval != 'number' || isNaN(interval) || interval < 0) + return; + + if (typeof times != 'number' || isNaN(times) || times < 0) + times = 0; + + times = times || 0; + + var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {}); + + if (!timers[label]) + timers[label] = {}; + + fn.timerID = fn.timerID || this.guid++; + + var handler = function() { + if ((++counter > times && times !== 0) || fn.call(element, counter) === false) + jQuery.timer.remove(element, label, fn); + }; + + handler.timerID = fn.timerID; + + if (!timers[label][fn.timerID]) + timers[label][fn.timerID] = window.setInterval(handler,interval); + + this.global.push( element ); + + }, + remove: function(element, label, fn) { + var timers = jQuery.data(element, this.dataKey), ret; + + if ( timers ) { + + if (!label) { + for ( label in timers ) + this.remove(element, label, fn); + } else if ( timers[label] ) { + if ( fn ) { + if ( fn.timerID ) { + window.clearInterval(timers[label][fn.timerID]); + delete timers[label][fn.timerID]; + } + } else { + for ( var fn in timers[label] ) { + window.clearInterval(timers[label][fn]); + delete timers[label][fn]; + } + } + + for ( ret in timers[label] ) break; + if ( !ret ) { + ret = null; + delete timers[label]; + } + } + + for ( ret in timers ) break; + if ( !ret ) + jQuery.removeData(element, this.dataKey); + } + } + } +}); + +jQuery(window).bind("unload", function() { + jQuery.each(jQuery.timer.global, function(index, item) { + jQuery.timer.remove(item); + }); +}); From 27fd14ac148347101ff1c0996f640a1a624f79bd Mon Sep 17 00:00:00 2001 From: jessica Date: Tue, 24 Aug 2010 15:59:06 -0700 Subject: [PATCH 074/235] new UI - left menu, middle menu, instance --- ui/new/css/main.css | 39 ++ ui/new/index.html | 4 + ui/new/jsp/tab_instance.jsp | 595 ++++++++++++++++++++++++++ ui/new/scripts/cloud.core.instance.js | 5 + ui/new/scripts/cloud.core.js | 4 + 5 files changed, 647 insertions(+) create mode 100755 ui/new/jsp/tab_instance.jsp diff --git a/ui/new/css/main.css b/ui/new/css/main.css index ee883dd0bc7..0bcf04c026b 100644 --- a/ui/new/css/main.css +++ b/ui/new/css/main.css @@ -292,6 +292,7 @@ a:visited { padding:0; } +<<<<<<< HEAD .vmpopup_container_closebutton { width:13px; height:13px; @@ -307,6 +308,8 @@ a:visited { background:url(../images/vm_closebutton_hover.gif) no-repeat top left; } +======= +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance .vmpopup_container_top { width:737px; height:30px; @@ -1605,7 +1608,11 @@ a:visited { } .midmenu_textbox { +<<<<<<< HEAD width:165px; +======= + width:150px; +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance height:auto; float:left; margin:0 0 0 10px; @@ -1614,7 +1621,11 @@ a:visited { } .midmenu_textbox p { +<<<<<<< HEAD width:165px; +======= + width:150px; +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance height:auto; float:left; text-align:left; @@ -1928,6 +1939,7 @@ a:visited { background:url(../images/infoerror_icon.gif) no-repeat top left; } +<<<<<<< HEAD .info_detailbox { width:99%; height:auto; @@ -1953,3 +1965,30 @@ a:visited { background:#ffe5e5 repeat top left; color:#a90000; } +======= +.info_detailbox { + width:99%; + height:auto; + float:left; + background:#fffbe6 repeat top left; + border:1px dashed #CCC; + color:#333; + margin:0 0 0 0; + padding:0; +} + +.info_detailbox p{ + width:auto; + height:auto; + float:left; + text-align:left; + font-size:11px; + margin:10px; + padding:0; +} + +.info_detailbox.errorbox { + background:#ffe5e5 repeat top left; + color:#a90000; +} +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance diff --git a/ui/new/index.html b/ui/new/index.html index dc0cb91028f..244d8e85441 100755 --- a/ui/new/index.html +++ b/ui/new/index.html @@ -5,7 +5,11 @@ +<<<<<<< HEAD +======= + +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance diff --git a/ui/new/jsp/tab_instance.jsp b/ui/new/jsp/tab_instance.jsp new file mode 100755 index 00000000000..10e63a491b8 --- /dev/null +++ b/ui/new/jsp/tab_instance.jsp @@ -0,0 +1,595 @@ + + +<%@ page import="java.util.*" %> +<%@ page import="com.cloud.utils.*" %> + +<% + + Locale browserLocale = request.getLocale(); + CloudResourceBundle t = CloudResourceBundle.getBundle("resources/resource", browserLocale); +%> + + + + + + + + + + + + + + + + diff --git a/ui/new/scripts/cloud.core.instance.js b/ui/new/scripts/cloud.core.instance.js index ac59f63d2eb..e124795367c 100755 --- a/ui/new/scripts/cloud.core.instance.js +++ b/ui/new/scripts/cloud.core.instance.js @@ -287,9 +287,14 @@ function clickInstanceGroupHeader($arrowIcon) { $arrowIcon.removeClass("open").addClass("close"); $instanceGroupContainer.empty(); } +<<<<<<< HEAD //***** VM Detail (end) ******************************************************************************** $("#right_panel").load("content/tab_instance.htm", function() { +======= + //***** VM Detail (end) ******************************************************************************** + $("#right_panel").load("jsp/tab_instance.jsp", function() { +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance $rightPanelHeader = $("#right_panel_header"); $rightPanelContent = $("#right_panel_content"); diff --git a/ui/new/scripts/cloud.core.js b/ui/new/scripts/cloud.core.js index 9c527906e4e..366e089c0ab 100755 --- a/ui/new/scripts/cloud.core.js +++ b/ui/new/scripts/cloud.core.js @@ -16,7 +16,11 @@ * */ +<<<<<<< HEAD // Version: @VERSION@ +======= +// Version: 1.9.1.6 +>>>>>>> 10bc0b5... new UI - left menu, middle menu, instance var g_mySession = null; var g_sessionKey = null; var g_role = null; // roles - root, domain-admin, ro-admin, user From fc295b0fdd0385abed75f591d466c292aa6bf77a Mon Sep 17 00:00:00 2001 From: jessica Date: Tue, 24 Aug 2010 17:22:24 -0700 Subject: [PATCH 075/235] add createURL() to $.ajax() command --- ui/new/scripts/cloud.core.instance.js | 51 ++++----------------------- 1 file changed, 7 insertions(+), 44 deletions(-) diff --git a/ui/new/scripts/cloud.core.instance.js b/ui/new/scripts/cloud.core.instance.js index e124795367c..48406f147ba 100755 --- a/ui/new/scripts/cloud.core.instance.js +++ b/ui/new/scripts/cloud.core.instance.js @@ -287,14 +287,8 @@ function clickInstanceGroupHeader($arrowIcon) { $arrowIcon.removeClass("open").addClass("close"); $instanceGroupContainer.empty(); } -<<<<<<< HEAD - //***** VM Detail (end) ******************************************************************************** - - $("#right_panel").load("content/tab_instance.htm", function() { -======= //***** VM Detail (end) ******************************************************************************** $("#right_panel").load("jsp/tab_instance.jsp", function() { ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance $rightPanelHeader = $("#right_panel_header"); $rightPanelContent = $("#right_panel_content"); @@ -304,42 +298,11 @@ function clickInstanceGroupHeader($arrowIcon) { var $diskOfferingTemplate = $("#vm_popup_disk_offering_template"); var currentPageInTemplateGridInVmPopup =1; var selectedTemplateTypeInVmPopup; //selectedTemplateTypeInVmPopup will be set to "featured" when new VM dialog box opens - - /* - $vmPopup.find("#wizard_service_offering").bind("click", function(event){ - event.stopPropagation(); //do not use event.preventDetault(), otherwise, radio button won't be checked. - var serviceOfferingId = $vmPopup.find("#wizard_service_offering input[name=service]:checked").val(); - if(getDirectAttachNetworkGroupsEnabled() != "true") { - $vmPopup.find("#wizard_network_groups_container").hide(); - } - else { - $.ajax({ - data: "command=listServiceOfferings&response=json&id="+serviceOfferingId, - dataType: "json", - success: function(json) { - var offerings = json.listserviceofferingsresponse.serviceoffering; - if (offerings != null && offerings.length > 0) { - if(offerings[0].usevirtualnetwork =="true") { //virtual network - $vmPopup.find("#wizard_network_groups_container").hide(); - } - else { //direct attached - if($vmPopup.find("#wizard_network_groups").find("option").length == 0) - $vmPopup.find("#wizard_network_groups_container").hide(); - else - $vmPopup.find("#wizard_network_groups_container").show(); - } - - } - } - }); - } - }); - */ - + $("#add_link").unbind("click").bind("click", function(event) { vmWizardOpen(); $.ajax({ - data: "command=listZones&available=true&response=json", + data: createURL("command=listZones&available=true&response=json"), dataType: "json", success: function(json) { var zones = json.listzonesresponse.zone; @@ -354,7 +317,7 @@ function clickInstanceGroupHeader($arrowIcon) { }); $.ajax({ - data: "command=listServiceOfferings&response=json", + data: createURL("command=listServiceOfferings&response=json"), dataType: "json", async: false, success: function(json) { @@ -387,7 +350,7 @@ function clickInstanceGroupHeader($arrowIcon) { $.ajax({ - data: "command=listDiskOfferings&domainid=1&response=json", + data: createURL("command=listDiskOfferings&domainid=1&response=json"), dataType: "json", async: false, success: function(json) { @@ -599,7 +562,7 @@ function clickInstanceGroupHeader($arrowIcon) { $vmPopup.find("#prevPage").show(); $.ajax({ - data: commandString, + data: createURL(commandString), dataType: "json", async: false, success: function(json) { @@ -874,7 +837,7 @@ function clickInstanceGroupHeader($arrowIcon) { */ $.ajax({ - data: "command=deployVirtualMachine"+moreCriteria.join("")+"&response=json", + data: createURL("command=deployVirtualMachine"+moreCriteria.join("")+"&response=json"), dataType: "json", success: function(json) { var jobId = json.deployvirtualmachineresponse.jobid; @@ -887,7 +850,7 @@ function clickInstanceGroupHeader($arrowIcon) { timerKey, function() { $.ajax({ - data: "command=queryAsyncJobResult&jobId="+jobId+"&response=json", + data: createURL("command=queryAsyncJobResult&jobId="+jobId+"&response=json"), dataType: "json", success: function(json) { var result = json.queryasyncjobresultresponse; From c356c2070e00eef414c0bf36c47ed721551b6079 Mon Sep 17 00:00:00 2001 From: NIKITA Date: Tue, 24 Aug 2010 18:07:36 -0700 Subject: [PATCH 076/235] Merge issue --- ui/new/jsp/tab_instances.html | 128 --- ui/new/scripts/cloud.core.js | 1512 ++++++++++++++++----------------- 2 files changed, 754 insertions(+), 886 deletions(-) delete mode 100755 ui/new/jsp/tab_instances.html diff --git a/ui/new/jsp/tab_instances.html b/ui/new/jsp/tab_instances.html deleted file mode 100755 index 4cecc8f6626..00000000000 --- a/ui/new/jsp/tab_instances.html +++ /dev/null @@ -1,128 +0,0 @@ -
    -
    - Instance
    -

    - Name of the Instance Selected.. -

    -
    -
    -
    -
    - Details
    -
    - Volume
    -
    - Statistics
    -
    -
    -
    -
    -
    -
    -
    -
    - Running
    -
    -

    - 10.1.1.200

    -
    -
    -
    -
    -
    -
    - Zone:
    -
    -
    -
    - JW
    -
    -
    -
    -
    -
    - Template:
    -
    -
    -
    - Centos 5.3(x36.4) no GUI
    -
    -
    -
    -
    -
    - Service:
    -
    -
    -
    - Small Instance
    -
    -
    -
    -
    -
    - HA:
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    - Created:
    -
    -
    -
    - 07/20/2010 11:29:04 -
    -
    -
    -
    -
    -
    - Account:
    -
    -
    -
    - Admin
    -
    -
    -
    -
    -
    - Domain:
    -
    -
    -
    - ROOT
    -
    -
    -
    -
    -
    - Host:
    -
    -
    -
    - Xenserver-test5 -
    -
    -
    -
    -
    -
    - ISO:
    -
    -
    -
    -
    -
    -
    -
    -
    -
    -
    diff --git a/ui/new/scripts/cloud.core.js b/ui/new/scripts/cloud.core.js index 366e089c0ab..2ff90c72b3e 100755 --- a/ui/new/scripts/cloud.core.js +++ b/ui/new/scripts/cloud.core.js @@ -16,788 +16,784 @@ * */ -<<<<<<< HEAD -// Version: @VERSION@ -======= -// Version: 1.9.1.6 ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance -var g_mySession = null; -var g_sessionKey = null; -var g_role = null; // roles - root, domain-admin, ro-admin, user -var g_username = null; -var g_account = null; -var g_domainid = null; -var g_enableLogging = false; + +var g_mySession = null; +var g_sessionKey = null; +var g_role = null; // roles - root, domain-admin, ro-admin, user +var g_username = null; +var g_account = null; +var g_domainid = null; +var g_enableLogging = false; var g_timezoneoffset = null; -var g_timezone = null; - -// capabilities -var g_networkType = "vnet"; // vnet, vlan, direct -function getNetworkType() { return g_networkType; } - -var g_hypervisorType = "kvm"; -function getHypervisorType() { return g_hypervisorType; } - -var g_directAttachNetworkGroupsEnabled = "false"; +var g_timezone = null; + +// capabilities +var g_networkType = "vnet"; // vnet, vlan, direct +function getNetworkType() { return g_networkType; } + +var g_hypervisorType = "kvm"; +function getHypervisorType() { return g_hypervisorType; } + +var g_directAttachNetworkGroupsEnabled = "false"; function getDirectAttachNetworkGroupsEnabled() { return g_directAttachNetworkGroupsEnabled; } var g_directAttachedUntaggedEnabled = "false" -function getDirectAttachUntaggedEnabled() { return g_directAttachedUntaggedEnabled; } - +function getDirectAttachUntaggedEnabled() { return g_directAttachedUntaggedEnabled; } + var g_systemVmUseLocalStorage = "false" -function getSystemVmUseLocalStorage() { return g_systemVmUseLocalStorage; } - -//keyboard keycode -var keycode_Enter = 13; - -//dropdown field size -var maxPageSize = "&pagesize=500"; - -//XMLHttpResponse.status -var ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED = 401; -var ERROR_INTERNET_NAME_NOT_RESOLVED = 12007; -var ERROR_INTERNET_CANNOT_CONNECT = 12029; -var ERROR_VMOPS_ACCOUNT_ERROR = 531; - -var g_logger = new Logger(); -$(function() { - if(g_enableLogging) - g_logger.open(); -}); - -// Test Tool. Please comment this out or remove this when going production. -// This is intended to provide a simple test tool to create user accounts and -// domains. -function initializeTestTool() { - $("#launch_test").click(function(event) { - testWindow = window.open('/client/test'); +function getSystemVmUseLocalStorage() { return g_systemVmUseLocalStorage; } + +//keyboard keycode +var keycode_Enter = 13; + +//dropdown field size +var maxPageSize = "&pagesize=500"; + +//XMLHttpResponse.status +var ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED = 401; +var ERROR_INTERNET_NAME_NOT_RESOLVED = 12007; +var ERROR_INTERNET_CANNOT_CONNECT = 12029; +var ERROR_VMOPS_ACCOUNT_ERROR = 531; + +var g_logger = new Logger(); +$(function() { + if(g_enableLogging) + g_logger.open(); +}); + +// Test Tool. Please comment this out or remove this when going production. +// This is intended to provide a simple test tool to create user accounts and +// domains. +function initializeTestTool() { + $("#launch_test").click(function(event) { + testWindow = window.open('/client/test'); testWindow.g_sessionKey=g_sessionKey; - return false; - }); -} - -// Role Functions -function isAdmin() { - return (g_role == 1); -} - -function isUser() { - return (g_role == 0); -} - -function isDomainAdmin() { - return (g_role == 2); -} - + return false; + }); +} + +// Role Functions +function isAdmin() { + return (g_role == 1); +} + +function isUser() { + return (g_role == 0); +} + +function isDomainAdmin() { + return (g_role == 2); +} + function createURL(url) { return url + "&sessionkey=" + g_sessionKey; } -function setDateField(dateValue, dateField, htmlMarkup) { - if (dateValue != null && dateValue.length > 0) { - var disconnected = new Date(); - disconnected.setISO8601(dateValue); - var showDate; - if(g_timezoneoffset != null) - showDate = disconnected.getTimePlusTimezoneOffset(g_timezoneoffset); - else - showDate = disconnected.format("m/d/Y H:i:s"); - if(htmlMarkup == null) - dateField.text(showDate); - else - dateField.html(htmlMarkup + showDate); - } -} - -function initResizable(resizeElement, alsoResizeElement) { - var alsoResizeUi_originalHeight; - $("#"+resizeElement).resizable({ - handles: 'e, w', - autoHide: true, - //containment: ".grid_header" , - alsoResize: "."+alsoResizeElement - }); -} - -var sortBy = ""; -var parseFunction = function() {} -var sortingOrder = "asc"; - -function sortArrayAlphabetically(a, b) { - if(a[sortBy] == null || b[sortBy] == null) - return 0; - - var A = a[sortBy].toLowerCase(); - var B = b[sortBy].toLowerCase(); - - if(sortingOrder == "asc") { - if (A < B) - return -1; - if (A > B) - return 1; - } else { - if (A < B) - return 1; - if (A > B) - return -1; - } - return 0; -} - -function sortArrayAlphabeticallyParse(a, b) { - if(a[sortBy] == null || b[sortBy] == null) - return 0; - - var A = parseFunction(a[sortBy]).toLowerCase(); - var B = parseFunction(b[sortBy]).toLowerCase(); - - if(sortingOrder == "asc") { - if (A < B) - return -1; - if (A > B) - return 1; - } else { - if (A < B) - return 1; - if (A > B) - return -1; - } - return 0; -} - -function sortArrayNumerically(a, b) { - if(a[sortBy] == null || b[sortBy] == null) - return 0; - - var A = parseInt(a[sortBy]); - var B = parseInt(b[sortBy]); - - if(sortingOrder == "asc") { - if (A < B) - return -1; - if (A > B) - return 1; - } else { - if (A < B) - return 1; - if (A > B) - return -1; - } - return 0; -} - -function sortArrayNumericallyParse(a, b) { - if(a[sortBy] == null || b[sortBy] == null) - return 0; - - var A = parseFunction(parseInt(a[sortBy])); - var B = parseFunction(parseInt(b[sortBy])); - - if(sortingOrder == "asc") { - if (A < B) - return -1; - if (A > B) - return 1; - } else { - if (A < B) - return 1; - if (A > B) - return -1; - } - return 0; -} - -function sortArrayByDate(a, b) { - if(a[sortBy] == null || b[sortBy] == null) - return 0; - - var A = convertMilliseconds(a[sortBy]); - var B = convertMilliseconds(b[sortBy]); - - if(sortingOrder == "asc") { - if (A < B) - return -1; - if (A > B) - return 1; - } else { - if (A < B) - return 1; - if (A > B) - return -1; - } - return 0; -} - -function convertMilliseconds(string) { - if (string != null && string.length > 0) { - var date1 = new Date(); - date1.setISO8601(string); - return date1.getTime(); - } else { - return null; - } -} - -function drawGrid(items, submenuContent, template, fnJSONToTemplate) { - var grid = submenuContent.find("#grid_content").empty(); - if (items != null && items.length > 0) { - for (var i = 0; i < items.length; i++) { - var newTemplate = template.clone(true); - fnJSONToTemplate(items[i], newTemplate); - grid.append(newTemplate.show()); - } - setGridRowsTotal(submenuContent.find("#grid_rows_total"), items.length); - if(items.length < pageSize) - submenuContent.find("#nextPage_div").hide(); - else - submenuContent.find("#nextPage_div").show(); - } else { - setGridRowsTotal(submenuContent.find("#grid_rows_total"), null); - submenuContent.find("#nextPage_div").hide(); - } -} - -//listItems() function takes care of loading image, pagination -var items = []; +function setDateField(dateValue, dateField, htmlMarkup) { + if (dateValue != null && dateValue.length > 0) { + var disconnected = new Date(); + disconnected.setISO8601(dateValue); + var showDate; + if(g_timezoneoffset != null) + showDate = disconnected.getTimePlusTimezoneOffset(g_timezoneoffset); + else + showDate = disconnected.format("m/d/Y H:i:s"); + if(htmlMarkup == null) + dateField.text(showDate); + else + dateField.html(htmlMarkup + showDate); + } +} + +function initResizable(resizeElement, alsoResizeElement) { + var alsoResizeUi_originalHeight; + $("#"+resizeElement).resizable({ + handles: 'e, w', + autoHide: true, + //containment: ".grid_header" , + alsoResize: "."+alsoResizeElement + }); +} + +var sortBy = ""; +var parseFunction = function() {} +var sortingOrder = "asc"; + +function sortArrayAlphabetically(a, b) { + if(a[sortBy] == null || b[sortBy] == null) + return 0; + + var A = a[sortBy].toLowerCase(); + var B = b[sortBy].toLowerCase(); + + if(sortingOrder == "asc") { + if (A < B) + return -1; + if (A > B) + return 1; + } else { + if (A < B) + return 1; + if (A > B) + return -1; + } + return 0; +} + +function sortArrayAlphabeticallyParse(a, b) { + if(a[sortBy] == null || b[sortBy] == null) + return 0; + + var A = parseFunction(a[sortBy]).toLowerCase(); + var B = parseFunction(b[sortBy]).toLowerCase(); + + if(sortingOrder == "asc") { + if (A < B) + return -1; + if (A > B) + return 1; + } else { + if (A < B) + return 1; + if (A > B) + return -1; + } + return 0; +} + +function sortArrayNumerically(a, b) { + if(a[sortBy] == null || b[sortBy] == null) + return 0; + + var A = parseInt(a[sortBy]); + var B = parseInt(b[sortBy]); + + if(sortingOrder == "asc") { + if (A < B) + return -1; + if (A > B) + return 1; + } else { + if (A < B) + return 1; + if (A > B) + return -1; + } + return 0; +} + +function sortArrayNumericallyParse(a, b) { + if(a[sortBy] == null || b[sortBy] == null) + return 0; + + var A = parseFunction(parseInt(a[sortBy])); + var B = parseFunction(parseInt(b[sortBy])); + + if(sortingOrder == "asc") { + if (A < B) + return -1; + if (A > B) + return 1; + } else { + if (A < B) + return 1; + if (A > B) + return -1; + } + return 0; +} + +function sortArrayByDate(a, b) { + if(a[sortBy] == null || b[sortBy] == null) + return 0; + + var A = convertMilliseconds(a[sortBy]); + var B = convertMilliseconds(b[sortBy]); + + if(sortingOrder == "asc") { + if (A < B) + return -1; + if (A > B) + return 1; + } else { + if (A < B) + return 1; + if (A > B) + return -1; + } + return 0; +} + +function convertMilliseconds(string) { + if (string != null && string.length > 0) { + var date1 = new Date(); + date1.setISO8601(string); + return date1.getTime(); + } else { + return null; + } +} + +function drawGrid(items, submenuContent, template, fnJSONToTemplate) { + var grid = submenuContent.find("#grid_content").empty(); + if (items != null && items.length > 0) { + for (var i = 0; i < items.length; i++) { + var newTemplate = template.clone(true); + fnJSONToTemplate(items[i], newTemplate); + grid.append(newTemplate.show()); + } + setGridRowsTotal(submenuContent.find("#grid_rows_total"), items.length); + if(items.length < pageSize) + submenuContent.find("#nextPage_div").hide(); + else + submenuContent.find("#nextPage_div").show(); + } else { + setGridRowsTotal(submenuContent.find("#grid_rows_total"), null); + submenuContent.find("#nextPage_div").hide(); + } +} + +//listItems() function takes care of loading image, pagination +var items = []; function listItems(submenuContent, commandString, jsonResponse1, jsonResponse2, template, fnJSONToTemplate ) { - if(currentPage==1) - submenuContent.find("#prevPage_div").hide(); - else + if(currentPage==1) + submenuContent.find("#prevPage_div").hide(); + else submenuContent.find("#prevPage_div").show(); submenuContent.find("#loading_gridtable").show(); - submenuContent.find("#pagination_panel").hide(); + submenuContent.find("#pagination_panel").hide(); index = 0; - $.ajax({ - data: createURL(commandString), - dataType: "json", - async: false, + $.ajax({ + data: createURL(commandString), + dataType: "json", + async: false, success: function(json) { - //IF jsonResponse1=="listaccountsresponse", jsonResponse2=="account", THEN json[jsonResponse1][jsonResponse2] == json.listaccountsresponse.account - items = json[jsonResponse1][jsonResponse2]; - drawGrid(items, submenuContent, template, fnJSONToTemplate); - submenuContent.find("#loading_gridtable").hide(); - submenuContent.find("#pagination_panel").show(); - }, - error: function(XMLHttpResponse) { - submenuContent.find("#loading_gridtable").hide(); - handleError(XMLHttpResponse, function() { - if(XMLHttpResponse.status == ERROR_VMOPS_ACCOUNT_ERROR) { - submenuContent.find("#grid_content").empty(); - setGridRowsTotal(submenuContent.find("#grid_rows_total"), null); - submenuContent.find("#nextPage_div").hide(); - } - submenuContent.find("#loading_gridtable").hide(); - submenuContent.find("#pagination_panel").show(); - }); - } - }); -} - - -//event binder -var currentPage = 1; -var pageSize = 50; //consistent with server-side -function submenuContentEventBinder(submenuContent, listFunction) { - submenuContent.find("#nextPage").bind("click", function(event){ - event.preventDefault(); - currentPage++; - listFunction(); - }); - - submenuContent.find("#prevPage").bind("click", function(event){ - event.preventDefault(); - currentPage--; - listFunction(); - }); - - submenuContent.find("#refresh").bind("click", function(event){ - event.preventDefault(); - currentPage=1; - listFunction(); - }); - - submenuContent.find("#search_button").bind("click", function(event) { - event.preventDefault(); - currentPage = 1; - listFunction(); - }); - - submenuContent.find("#adv_search_button").bind("click", function(event) { - event.preventDefault(); - currentPage = 1; - listFunction(); - submenuContent.find("#search_button").data("advanced", false); - submenuContent.find("#advanced_search").hide(); - }); - - submenuContent.find("#search_input").bind("keypress", function(event) { - if(event.keyCode == keycode_Enter) { - event.preventDefault(); - submenuContent.find("#search_button").click(); - } - }); - - submenuContent.find("#advanced_search").bind("keypress", function(event) { - if(event.keyCode == keycode_Enter) { - event.preventDefault(); - submenuContent.find("#adv_search_button").click(); - } - }); - - submenuContent.find("#advanced_search_close").bind("click", function(event) { - event.preventDefault(); - submenuContent.find("#search_button").data("advanced", false); - submenuContent.find("#advanced_search").hide(); - }); - - submenuContent.find("#advanced_search_link").bind("click", function(event) { - event.preventDefault(); - submenuContent.find("#search_button").data("advanced", true); - submenuContent.find("#advanced_search").show(); - }); - - var zoneSelect = submenuContent.find("#advanced_search #adv_search_zone"); - if(zoneSelect.length>0) { //if zone dropdown is found on Advanced Search dialog - $.ajax({ + //IF jsonResponse1=="listaccountsresponse", jsonResponse2=="account", THEN json[jsonResponse1][jsonResponse2] == json.listaccountsresponse.account + items = json[jsonResponse1][jsonResponse2]; + drawGrid(items, submenuContent, template, fnJSONToTemplate); + submenuContent.find("#loading_gridtable").hide(); + submenuContent.find("#pagination_panel").show(); + }, + error: function(XMLHttpResponse) { + submenuContent.find("#loading_gridtable").hide(); + handleError(XMLHttpResponse, function() { + if(XMLHttpResponse.status == ERROR_VMOPS_ACCOUNT_ERROR) { + submenuContent.find("#grid_content").empty(); + setGridRowsTotal(submenuContent.find("#grid_rows_total"), null); + submenuContent.find("#nextPage_div").hide(); + } + submenuContent.find("#loading_gridtable").hide(); + submenuContent.find("#pagination_panel").show(); + }); + } + }); +} + + +//event binder +var currentPage = 1; +var pageSize = 50; //consistent with server-side +function submenuContentEventBinder(submenuContent, listFunction) { + submenuContent.find("#nextPage").bind("click", function(event){ + event.preventDefault(); + currentPage++; + listFunction(); + }); + + submenuContent.find("#prevPage").bind("click", function(event){ + event.preventDefault(); + currentPage--; + listFunction(); + }); + + submenuContent.find("#refresh").bind("click", function(event){ + event.preventDefault(); + currentPage=1; + listFunction(); + }); + + submenuContent.find("#search_button").bind("click", function(event) { + event.preventDefault(); + currentPage = 1; + listFunction(); + }); + + submenuContent.find("#adv_search_button").bind("click", function(event) { + event.preventDefault(); + currentPage = 1; + listFunction(); + submenuContent.find("#search_button").data("advanced", false); + submenuContent.find("#advanced_search").hide(); + }); + + submenuContent.find("#search_input").bind("keypress", function(event) { + if(event.keyCode == keycode_Enter) { + event.preventDefault(); + submenuContent.find("#search_button").click(); + } + }); + + submenuContent.find("#advanced_search").bind("keypress", function(event) { + if(event.keyCode == keycode_Enter) { + event.preventDefault(); + submenuContent.find("#adv_search_button").click(); + } + }); + + submenuContent.find("#advanced_search_close").bind("click", function(event) { + event.preventDefault(); + submenuContent.find("#search_button").data("advanced", false); + submenuContent.find("#advanced_search").hide(); + }); + + submenuContent.find("#advanced_search_link").bind("click", function(event) { + event.preventDefault(); + submenuContent.find("#search_button").data("advanced", true); + submenuContent.find("#advanced_search").show(); + }); + + var zoneSelect = submenuContent.find("#advanced_search #adv_search_zone"); + if(zoneSelect.length>0) { //if zone dropdown is found on Advanced Search dialog + $.ajax({ data: createURL("command=listZones&available=true&response=json"+maxPageSize), - dataType: "json", - success: function(json) { - var zones = json.listzonesresponse.zone; - zoneSelect.empty(); - zoneSelect.append(""); - if (zones != null && zones.length > 0) { - for (var i = 0; i < zones.length; i++) { - zoneSelect.append(""); - } - } - } - }); - - var podSelect = submenuContent.find("#advanced_search #adv_search_pod").empty(); - var podLabel = submenuContent.find("#advanced_search #adv_search_pod_label"); - if(podSelect.length>0 && isAdmin()) { //if pod dropdown is found on Advanced Search dialog and if its role is admin - zoneSelect.bind("change", function(event) { - var zoneId = $(this).val(); - if (zoneId == null || zoneId.length == 0) { - podLabel.css("color", "gray"); - podSelect.attr("disabled", "disabled"); - podSelect.empty(); - } else { - podLabel.css("color", "black"); - podSelect.removeAttr("disabled"); - $.ajax({ + dataType: "json", + success: function(json) { + var zones = json.listzonesresponse.zone; + zoneSelect.empty(); + zoneSelect.append(""); + if (zones != null && zones.length > 0) { + for (var i = 0; i < zones.length; i++) { + zoneSelect.append(""); + } + } + } + }); + + var podSelect = submenuContent.find("#advanced_search #adv_search_pod").empty(); + var podLabel = submenuContent.find("#advanced_search #adv_search_pod_label"); + if(podSelect.length>0 && isAdmin()) { //if pod dropdown is found on Advanced Search dialog and if its role is admin + zoneSelect.bind("change", function(event) { + var zoneId = $(this).val(); + if (zoneId == null || zoneId.length == 0) { + podLabel.css("color", "gray"); + podSelect.attr("disabled", "disabled"); + podSelect.empty(); + } else { + podLabel.css("color", "black"); + podSelect.removeAttr("disabled"); + $.ajax({ data: createURL("command=listPods&zoneId="+zoneId+"&response=json"+maxPageSize), - dataType: "json", - async: false, - success: function(json) { - var pods = json.listpodsresponse.pod; - podSelect.empty(); - if (pods != null && pods.length > 0) { - for (var i = 0; i < pods.length; i++) { - podSelect.append(""); - } - } - } - }); - } - return false; - }); - - zoneSelect.change(); - } - } - - var domainSelect = submenuContent.find("#advanced_search #adv_search_domain"); - if(domainSelect.length>0 && isAdmin()) { - var domainSelect = domainSelect.empty(); - $.ajax({ + dataType: "json", + async: false, + success: function(json) { + var pods = json.listpodsresponse.pod; + podSelect.empty(); + if (pods != null && pods.length > 0) { + for (var i = 0; i < pods.length; i++) { + podSelect.append(""); + } + } + } + }); + } + return false; + }); + + zoneSelect.change(); + } + } + + var domainSelect = submenuContent.find("#advanced_search #adv_search_domain"); + if(domainSelect.length>0 && isAdmin()) { + var domainSelect = domainSelect.empty(); + $.ajax({ data: createURL("command=listDomains&available=true&response=json"+maxPageSize), - dataType: "json", - success: function(json) { - var domains = json.listdomainsresponse.domain; - if (domains != null && domains.length > 0) { - for (var i = 0; i < domains.length; i++) { - domainSelect.append(""); - } - } - } - }); - } - - var vmSelect = submenuContent.find("#advanced_search").find("#adv_search_vm"); - if(vmSelect.length>0) { - vmSelect.empty(); - vmSelect.append(""); - $.ajax({ + dataType: "json", + success: function(json) { + var domains = json.listdomainsresponse.domain; + if (domains != null && domains.length > 0) { + for (var i = 0; i < domains.length; i++) { + domainSelect.append(""); + } + } + } + }); + } + + var vmSelect = submenuContent.find("#advanced_search").find("#adv_search_vm"); + if(vmSelect.length>0) { + vmSelect.empty(); + vmSelect.append(""); + $.ajax({ data: createURL("command=listVirtualMachines&response=json"+maxPageSize), - dataType: "json", - success: function(json) { - var items = json.listvirtualmachinesresponse.virtualmachine; - if (items != null && items.length > 0) { - for (var i = 0; i < items.length; i++) { - vmSelect.append(""); - } - } - } - }); - } -} - -// Validation functions -function showError(isValid, field, errMsgField, errMsg) { - if(isValid) { - errMsgField.text("").hide(); - field.addClass("text").removeClass("error_text"); - } - else { - errMsgField.text(errMsg).show(); - field.removeClass("text").addClass("error_text"); - } -} - -function showError2(isValid, field, errMsgField, errMsg, appendErrMsg) { - if(isValid) { - errMsgField.text("").hide(); - field.addClass("text2").removeClass("error_text2"); - } - else { - if(appendErrMsg) //append text - errMsgField.text(errMsgField.text()+errMsg).show(); - else //reset text - errMsgField.text(errMsg).show(); - field.removeClass("text2").addClass("error_text2"); - } -} - -function validateDropDownBox(label, field, errMsgField, appendErrMsg) { - var isValid = true; - var errMsg = ""; - var value = field.val(); - if (value == null || value.length == 0) { - errMsg = label + " is a required value. "; - isValid = false; - } - showError2(isValid, field, errMsgField, errMsg, appendErrMsg); - return isValid; -} - -function validateNumber(label, field, errMsgField, min, max, isOptional) { - var isValid = true; - var errMsg = ""; - var value = field.val(); - if (value != null && value.length != 0) { - if(isNaN(value)) { - errMsg = label + " must be a number"; - isValid = false; - } else { - if (min != null && value < min) { - errMsg = label + " must be a value greater than or equal to " + min; - isValid = false; - } - if (max != null && value > max) { - errMsg = label + " must be a value less than or equal to " + max; - isValid = false; - } - } - } else if(isOptional!=true){ //required field - errMsg = label + " is a required value. "; - isValid = false; - } - showError(isValid, field, errMsgField, errMsg); - return isValid; -} - -function validateString(label, field, errMsgField, isOptional) { - var isValid = true; - var errMsg = ""; - var value = field.val(); - if (isOptional!=true && (value == null || value.length == 0)) { //required field - errMsg = label + " is a required value. "; - isValid = false; - } - else if (value!=null && value.length >= 255) { - errMsg = label + " must be less than 255 characters"; - isValid = false; - } - else if(value!=null && value.indexOf('"')!=-1) { - errMsg = "Double quotes are not allowed."; - isValid = false; - } - showError(isValid, field, errMsgField, errMsg); - return isValid; -} - -function validateIp(label, field, errMsgField, isOptional) { - if(validateString(label, field, errMsgField, isOptional) == false) - return; - var isValid = true; - var errMsg = ""; - var value = field.val(); - if(value!=null && value.length>0) { - myregexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; - var isMatch = myregexp.test(value); - if(!isMatch) { - errMsg = label + " should be like 75.52.126.11"; - isValid = false; - } - } - showError(isValid, field, errMsgField, errMsg); - return isValid; -} - -function validateCIDR(label, field, errMsgField, isOptional) { - if(validateString(label, field, errMsgField, isOptional) == false) - return; - var isValid = true; - var errMsg = ""; - var value = field.val(); - if(value!=null && value.length>0) { - myregexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/; - var isMatch = myregexp.test(value); - if(!isMatch) { - errMsg = label + " should be like 10.1.1.0/24"; - isValid = false; - } - } - showError(isValid, field, errMsgField, errMsg); - return isValid; -} - -function validatePath(label, field, errMsgField, isOptional) { - if(validateString(label, field, errMsgField, isOptional) == false) - return; - var isValid = true; - var errMsg = ""; - var value = field.val(); - if(value!=null && value.length>0) { - myregexp = /^\//; - var isMatch = myregexp.test(value); - if(!isMatch) { - errMsg = label + " should be like /aaa/bbb/ccc"; - isValid = false; - } - } - showError(isValid, field, errMsgField, errMsg); - return isValid; -} - -function cleanErrMsg(field, errMsgField) { - showError(true, field, errMsgField); -} - -// setter -function setGridRowsTotal(field, gridRowsTotal) { - if(gridRowsTotal==null) { - field.text(""); - return; - } - - if(gridRowsTotal==1) - field.text(gridRowsTotal + " item"); - else - field.text(gridRowsTotal + " items"); -} - -function changeGridRowsTotal(field, difference) { - var t = field.text(); - var oldTotal = 0; - if(t.length>0 && t.indexOf(" item")!=-1) { - var s = t.substring(0, t.indexOf(" item")); - if(!isNaN(s)) - oldTotal = parseInt(s); - } - var newTotal = oldTotal + difference; - setGridRowsTotal(field, newTotal); -} - - -// others -function trim(val) { - if(val == null) - return null; - return val.replace(/^\s*/, "").replace(/\s*$/, ""); -} - -function noNull(val) { - if(val == null) - return ""; - else - return val; -} - -// Prevent cross-site-script(XSS) attack. -// used right before adding user input to the DOM tree. e.g. DOM_element.html(sanitizeXSS(user_input)); -function sanitizeXSS(val) { - if(val == null) - return val; - val = val.replace(//g, ">"); //replace > whose unicode is \u003e - return val; -} - -function getVmName(p_vmName, p_vmDisplayname) { - if(p_vmDisplayname == null) - return sanitizeXSS(p_vmName); - var vmName = null; - if (isAdmin()) { - if (p_vmDisplayname != p_vmName) { - vmName = p_vmName + "(" + sanitizeXSS(p_vmDisplayname) + ")"; - } else { - vmName = p_vmName; - } - } else { - vmName = sanitizeXSS(p_vmDisplayname); - } - return vmName; -} - -// FUNCTION: Handles AJAX error callbacks. You can pass in an optional function to -// handle errors that are not already handled by this method. -function handleError(xmlHttp, handleErrorCallback) { - // User Not authenticated - if (xmlHttp.status == ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED) { - $("#dialog_session_expired").dialog("open"); - } - else if (xmlHttp.status == ERROR_INTERNET_NAME_NOT_RESOLVED) { - $("#dialog_error").text("Internet name can not be resolved").dialog("open"); - } - else if (xmlHttp.status == ERROR_INTERNET_CANNOT_CONNECT) { - $("#dialog_error").text("Management server is not accessible").dialog("open"); - } - else if (xmlHttp.status == ERROR_VMOPS_ACCOUNT_ERROR && handleErrorCallback != undefined) { - handleErrorCallback(); + dataType: "json", + success: function(json) { + var items = json.listvirtualmachinesresponse.virtualmachine; + if (items != null && items.length > 0) { + for (var i = 0; i < items.length; i++) { + vmSelect.append(""); + } + } + } + }); + } +} + +// Validation functions +function showError(isValid, field, errMsgField, errMsg) { + if(isValid) { + errMsgField.text("").hide(); + field.addClass("text").removeClass("error_text"); + } + else { + errMsgField.text(errMsg).show(); + field.removeClass("text").addClass("error_text"); + } +} + +function showError2(isValid, field, errMsgField, errMsg, appendErrMsg) { + if(isValid) { + errMsgField.text("").hide(); + field.addClass("text2").removeClass("error_text2"); + } + else { + if(appendErrMsg) //append text + errMsgField.text(errMsgField.text()+errMsg).show(); + else //reset text + errMsgField.text(errMsg).show(); + field.removeClass("text2").addClass("error_text2"); + } +} + +function validateDropDownBox(label, field, errMsgField, appendErrMsg) { + var isValid = true; + var errMsg = ""; + var value = field.val(); + if (value == null || value.length == 0) { + errMsg = label + " is a required value. "; + isValid = false; + } + showError2(isValid, field, errMsgField, errMsg, appendErrMsg); + return isValid; +} + +function validateNumber(label, field, errMsgField, min, max, isOptional) { + var isValid = true; + var errMsg = ""; + var value = field.val(); + if (value != null && value.length != 0) { + if(isNaN(value)) { + errMsg = label + " must be a number"; + isValid = false; + } else { + if (min != null && value < min) { + errMsg = label + " must be a value greater than or equal to " + min; + isValid = false; + } + if (max != null && value > max) { + errMsg = label + " must be a value less than or equal to " + max; + isValid = false; + } + } + } else if(isOptional!=true){ //required field + errMsg = label + " is a required value. "; + isValid = false; + } + showError(isValid, field, errMsgField, errMsg); + return isValid; +} + +function validateString(label, field, errMsgField, isOptional) { + var isValid = true; + var errMsg = ""; + var value = field.val(); + if (isOptional!=true && (value == null || value.length == 0)) { //required field + errMsg = label + " is a required value. "; + isValid = false; + } + else if (value!=null && value.length >= 255) { + errMsg = label + " must be less than 255 characters"; + isValid = false; + } + else if(value!=null && value.indexOf('"')!=-1) { + errMsg = "Double quotes are not allowed."; + isValid = false; + } + showError(isValid, field, errMsgField, errMsg); + return isValid; +} + +function validateIp(label, field, errMsgField, isOptional) { + if(validateString(label, field, errMsgField, isOptional) == false) + return; + var isValid = true; + var errMsg = ""; + var value = field.val(); + if(value!=null && value.length>0) { + myregexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/; + var isMatch = myregexp.test(value); + if(!isMatch) { + errMsg = label + " should be like 75.52.126.11"; + isValid = false; + } + } + showError(isValid, field, errMsgField, errMsg); + return isValid; +} + +function validateCIDR(label, field, errMsgField, isOptional) { + if(validateString(label, field, errMsgField, isOptional) == false) + return; + var isValid = true; + var errMsg = ""; + var value = field.val(); + if(value!=null && value.length>0) { + myregexp = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/\d{1,2}$/; + var isMatch = myregexp.test(value); + if(!isMatch) { + errMsg = label + " should be like 10.1.1.0/24"; + isValid = false; + } + } + showError(isValid, field, errMsgField, errMsg); + return isValid; +} + +function validatePath(label, field, errMsgField, isOptional) { + if(validateString(label, field, errMsgField, isOptional) == false) + return; + var isValid = true; + var errMsg = ""; + var value = field.val(); + if(value!=null && value.length>0) { + myregexp = /^\//; + var isMatch = myregexp.test(value); + if(!isMatch) { + errMsg = label + " should be like /aaa/bbb/ccc"; + isValid = false; + } + } + showError(isValid, field, errMsgField, errMsg); + return isValid; +} + +function cleanErrMsg(field, errMsgField) { + showError(true, field, errMsgField); +} + +// setter +function setGridRowsTotal(field, gridRowsTotal) { + if(gridRowsTotal==null) { + field.text(""); + return; + } + + if(gridRowsTotal==1) + field.text(gridRowsTotal + " item"); + else + field.text(gridRowsTotal + " items"); +} + +function changeGridRowsTotal(field, difference) { + var t = field.text(); + var oldTotal = 0; + if(t.length>0 && t.indexOf(" item")!=-1) { + var s = t.substring(0, t.indexOf(" item")); + if(!isNaN(s)) + oldTotal = parseInt(s); + } + var newTotal = oldTotal + difference; + setGridRowsTotal(field, newTotal); +} + + +// others +function trim(val) { + if(val == null) + return null; + return val.replace(/^\s*/, "").replace(/\s*$/, ""); +} + +function noNull(val) { + if(val == null) + return ""; + else + return val; +} + +// Prevent cross-site-script(XSS) attack. +// used right before adding user input to the DOM tree. e.g. DOM_element.html(sanitizeXSS(user_input)); +function sanitizeXSS(val) { + if(val == null) + return val; + val = val.replace(//g, ">"); //replace > whose unicode is \u003e + return val; +} + +function getVmName(p_vmName, p_vmDisplayname) { + if(p_vmDisplayname == null) + return sanitizeXSS(p_vmName); + var vmName = null; + if (isAdmin()) { + if (p_vmDisplayname != p_vmName) { + vmName = p_vmName + "(" + sanitizeXSS(p_vmDisplayname) + ")"; + } else { + vmName = p_vmName; + } + } else { + vmName = sanitizeXSS(p_vmDisplayname); + } + return vmName; +} + +// FUNCTION: Handles AJAX error callbacks. You can pass in an optional function to +// handle errors that are not already handled by this method. +function handleError(xmlHttp, handleErrorCallback) { + // User Not authenticated + if (xmlHttp.status == ERROR_ACCESS_DENIED_DUE_TO_UNAUTHORIZED) { + $("#dialog_session_expired").dialog("open"); + } + else if (xmlHttp.status == ERROR_INTERNET_NAME_NOT_RESOLVED) { + $("#dialog_error").text("Internet name can not be resolved").dialog("open"); + } + else if (xmlHttp.status == ERROR_INTERNET_CANNOT_CONNECT) { + $("#dialog_error").text("Management server is not accessible").dialog("open"); + } + else if (xmlHttp.status == ERROR_VMOPS_ACCOUNT_ERROR && handleErrorCallback != undefined) { + handleErrorCallback(); } else if (handleErrorCallback != undefined) { handleErrorCallback(); - } - else { - var start = xmlHttp.responseText.indexOf("h1") + 3; - var end = xmlHttp.responseText.indexOf("Encountered an error:


    "+sanitizeXSS(errorMsg)+"

    ").dialog("open"); - } -} - -// FUNCTION: Adds a Dialog to the list of active Dialogs so that -// when you shift from one tab to another, we clean out the dialogs -var activeDialogs = new Array(); -function activateDialog(dialog) { - activeDialogs[activeDialogs.length] = dialog; - - //bind Enter-Key-pressing event handler to the dialog - dialog.keypress(function(event) { - if(event.keyCode == keycode_Enter) { - $('[aria-labelledby$='+dialog.attr("id")+']').find(":button:first").click(); - return false; //event.preventDefault() + event.stopPropagation() - } - }); -} -function removeDialogs() { - for (var i = 0; i < activeDialogs.length; i++) { - activeDialogs[i].remove(); - } - activeDialogs = new Array(); -} - -function convertBytes(bytes) { - if (bytes < 1024 * 1024) { - return (bytes / 1024).toFixed(2) + " KB"; - } else if (bytes < 1024 * 1024 * 1024) { - return (bytes / 1024 / 1024).toFixed(2) + " MB"; - } else if (bytes < 1024 * 1024 * 1024 * 1024) { - return (bytes / 1024 / 1024 / 1024).toFixed(2) + " GB"; - } else { - return (bytes / 1024 / 1024 / 1024 / 1024).toFixed(2) + " TB"; - } -} - -function convertHz(hz) { - if (hz < 1000) { - return hz + " MHZ"; - } else { - return (hz / 1000).toFixed(2) + " GHZ"; - } -} - -function toDayOfMonthDesp(dayOfMonth) { - return "Day "+dayOfMonth +" of Month"; -} - -function toDayOfWeekDesp(dayOfWeek) { - if (dayOfWeek == "1") - return "Sunday"; - else if (dayOfWeek == "2") - return "Monday"; - else if (dayOfWeek == "3") - return "Tuesday"; - else if (dayOfWeek == "4") - return "Wednesday"; - else if (dayOfWeek == "5") - return "Thursday" - else if (dayOfWeek == "6") - return "Friday"; - else if (dayOfWeek == "7") - return "Saturday"; -} - -function toBooleanText(booleanValue) { - if(booleanValue == "true") - return "Yes"; - else if(booleanValue == "false") - return "No"; -} - -function toBooleanValue(booleanText) { - if(booleanText == "Yes") - return "true"; - else if(booleanText == "No") - return "false"; -} - -function toNetworkType(usevirtualnetwork) { - if(usevirtualnetwork == "true") - return "Public"; - else - return "Direct"; -} - -var roleTypeUser = "0"; -var roleTypeAdmin = "1"; -var roleTypeDomainAdmin = "2"; -function toRole(type) { - if (type == roleTypeUser) { - return "User"; - } else if (type == roleTypeAdmin) { - return "Admin"; - } else if (type == roleTypeDomainAdmin) { - return "Domain-Admin"; - } -} - -function toAlertType(alertCode) { - switch (alertCode) { - case "0" : return "Capacity Threshold - Memory"; - case "1" : return "Capacity Threshold - CPU"; - case "2" : return "Capacity Threshold - Storage Used"; - case "3" : return "Capacity Threshold - Storage Allocated"; - case "4" : return "Capacity Threshold - Public IP"; - case "5" : return "Capacity Threshold - Private IP"; - case "6" : return "Monitoring - Host"; - case "7" : return "Monitoring - VM"; - case "8" : return "Monitoring - Domain Router"; - case "9" : return "Monitoring - Console Proxy"; - case "10" : return "Monitoring - Routing Host"; - case "11" : return "Monitoring - Storage"; - case "12" : return "Monitoring - Usage Server"; - case "13" : return "Monitoring - Management Server"; - case "14" : return "Migration - Domain Router"; - case "15" : return "Migration - Console Proxy"; - case "16" : return "Migration - User VM"; - case "17" : return "VLAN"; - case "18" : return "Monitoring - Secondary Storage VM"; - } + } + else { + var start = xmlHttp.responseText.indexOf("h1") + 3; + var end = xmlHttp.responseText.indexOf("Encountered an error:


    "+sanitizeXSS(errorMsg)+"

    ").dialog("open"); + } +} + +// FUNCTION: Adds a Dialog to the list of active Dialogs so that +// when you shift from one tab to another, we clean out the dialogs +var activeDialogs = new Array(); +function activateDialog(dialog) { + activeDialogs[activeDialogs.length] = dialog; + + //bind Enter-Key-pressing event handler to the dialog + dialog.keypress(function(event) { + if(event.keyCode == keycode_Enter) { + $('[aria-labelledby$='+dialog.attr("id")+']').find(":button:first").click(); + return false; //event.preventDefault() + event.stopPropagation() + } + }); +} +function removeDialogs() { + for (var i = 0; i < activeDialogs.length; i++) { + activeDialogs[i].remove(); + } + activeDialogs = new Array(); +} + +function convertBytes(bytes) { + if (bytes < 1024 * 1024) { + return (bytes / 1024).toFixed(2) + " KB"; + } else if (bytes < 1024 * 1024 * 1024) { + return (bytes / 1024 / 1024).toFixed(2) + " MB"; + } else if (bytes < 1024 * 1024 * 1024 * 1024) { + return (bytes / 1024 / 1024 / 1024).toFixed(2) + " GB"; + } else { + return (bytes / 1024 / 1024 / 1024 / 1024).toFixed(2) + " TB"; + } +} + +function convertHz(hz) { + if (hz < 1000) { + return hz + " MHZ"; + } else { + return (hz / 1000).toFixed(2) + " GHZ"; + } +} + +function toDayOfMonthDesp(dayOfMonth) { + return "Day "+dayOfMonth +" of Month"; +} + +function toDayOfWeekDesp(dayOfWeek) { + if (dayOfWeek == "1") + return "Sunday"; + else if (dayOfWeek == "2") + return "Monday"; + else if (dayOfWeek == "3") + return "Tuesday"; + else if (dayOfWeek == "4") + return "Wednesday"; + else if (dayOfWeek == "5") + return "Thursday" + else if (dayOfWeek == "6") + return "Friday"; + else if (dayOfWeek == "7") + return "Saturday"; +} + +function toBooleanText(booleanValue) { + if(booleanValue == "true") + return "Yes"; + else if(booleanValue == "false") + return "No"; +} + +function toBooleanValue(booleanText) { + if(booleanText == "Yes") + return "true"; + else if(booleanText == "No") + return "false"; +} + +function toNetworkType(usevirtualnetwork) { + if(usevirtualnetwork == "true") + return "Public"; + else + return "Direct"; +} + +var roleTypeUser = "0"; +var roleTypeAdmin = "1"; +var roleTypeDomainAdmin = "2"; +function toRole(type) { + if (type == roleTypeUser) { + return "User"; + } else if (type == roleTypeAdmin) { + return "Admin"; + } else if (type == roleTypeDomainAdmin) { + return "Domain-Admin"; + } +} + +function toAlertType(alertCode) { + switch (alertCode) { + case "0" : return "Capacity Threshold - Memory"; + case "1" : return "Capacity Threshold - CPU"; + case "2" : return "Capacity Threshold - Storage Used"; + case "3" : return "Capacity Threshold - Storage Allocated"; + case "4" : return "Capacity Threshold - Public IP"; + case "5" : return "Capacity Threshold - Private IP"; + case "6" : return "Monitoring - Host"; + case "7" : return "Monitoring - VM"; + case "8" : return "Monitoring - Domain Router"; + case "9" : return "Monitoring - Console Proxy"; + case "10" : return "Monitoring - Routing Host"; + case "11" : return "Monitoring - Storage"; + case "12" : return "Monitoring - Usage Server"; + case "13" : return "Monitoring - Management Server"; + case "14" : return "Migration - Domain Router"; + case "15" : return "Migration - Console Proxy"; + case "16" : return "Migration - User VM"; + case "17" : return "VLAN"; + case "18" : return "Monitoring - Secondary Storage VM"; + } } // Timezones From b7550c04e4723ff624a6d1b8bfa2d7017d7fdec9 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 10:06:10 -0700 Subject: [PATCH 077/235] resolve merge conflict. delete obsolete files. --- ui/new/content/tab_instance.htm | 586 ------------------------------ ui/new/index.html | 8 +- ui/new/jsp/tab_instance.jsp | 2 +- ui/new/scripts/cloud.core.init.js | 2 + ui/new/scripts/cloud.core.js | 15 +- 5 files changed, 14 insertions(+), 599 deletions(-) delete mode 100755 ui/new/content/tab_instance.htm diff --git a/ui/new/content/tab_instance.htm b/ui/new/content/tab_instance.htm deleted file mode 100755 index 21640742a50..00000000000 --- a/ui/new/content/tab_instance.htm +++ /dev/null @@ -1,586 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/ui/new/index.html b/ui/new/index.html index 244d8e85441..3b085f9c385 100755 --- a/ui/new/index.html +++ b/ui/new/index.html @@ -4,12 +4,8 @@ - -<<<<<<< HEAD - -======= - ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance + + diff --git a/ui/new/jsp/tab_instance.jsp b/ui/new/jsp/tab_instance.jsp index 10e63a491b8..599222ccad1 100755 --- a/ui/new/jsp/tab_instance.jsp +++ b/ui/new/jsp/tab_instance.jsp @@ -24,7 +24,7 @@
    - <%=t.getString("computer")%> Details
    + Details <%=t.t("computer")%>
    Volume
    diff --git a/ui/new/scripts/cloud.core.init.js b/ui/new/scripts/cloud.core.init.js index 79d4488c6f0..99814507f88 100755 --- a/ui/new/scripts/cloud.core.init.js +++ b/ui/new/scripts/cloud.core.init.js @@ -98,7 +98,9 @@ $(document).ready(function() { return; } + /* initializeTestTool(); + */ // We will be dropping all the main tab content into this container mainContainer = $("#maincontentarea"); diff --git a/ui/new/scripts/cloud.core.js b/ui/new/scripts/cloud.core.js index 2ff90c72b3e..a45db5820be 100755 --- a/ui/new/scripts/cloud.core.js +++ b/ui/new/scripts/cloud.core.js @@ -17,12 +17,15 @@ */ -var g_mySession = null; -var g_sessionKey = null; -var g_role = null; // roles - root, domain-admin, ro-admin, user -var g_username = null; -var g_account = null; -var g_domainid = null; + +// Version: @VERSION@ + +var g_mySession = null; +var g_sessionKey = null; +var g_role = null; // roles - root, domain-admin, ro-admin, user +var g_username = null; +var g_account = null; +var g_domainid = null; var g_enableLogging = false; var g_timezoneoffset = null; var g_timezone = null; From f04e1351bc7c11c243970c08a361ebab57c77d68 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 10:56:42 -0700 Subject: [PATCH 078/235] add CloudResourceBundle.java to com.cloud.utils --- .../com/cloud/utils/CloudResourceBundle.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 utils/src/com/cloud/utils/CloudResourceBundle.java diff --git a/utils/src/com/cloud/utils/CloudResourceBundle.java b/utils/src/com/cloud/utils/CloudResourceBundle.java new file mode 100755 index 00000000000..146c54e50bb --- /dev/null +++ b/utils/src/com/cloud/utils/CloudResourceBundle.java @@ -0,0 +1,29 @@ +package com.cloud.utils; + +import java.util.Locale; +import java.util.ResourceBundle; + +public class CloudResourceBundle { + + private ResourceBundle _bundle; + + public CloudResourceBundle(ResourceBundle bundle) { + _bundle = bundle; + } + + public static CloudResourceBundle getBundle(String baseName, Locale locale) { + return new CloudResourceBundle(ResourceBundle.getBundle(baseName, locale)); + } + + private String getString(String key) { + try { + return _bundle.getString(key); + } catch(Exception e) { + return "##" + key + "##"; + } + } + + public String t(String key) { + return getString(key); + } +} From 25a200c20139ee9727715a7c08f8e644dfa85dea Mon Sep 17 00:00:00 2001 From: NIKITA Date: Wed, 25 Aug 2010 11:11:29 -0700 Subject: [PATCH 079/235] removed merged issues --- ui/new/css/main.css | 70 +++++++++++++++++++-------------------------- 1 file changed, 30 insertions(+), 40 deletions(-) diff --git a/ui/new/css/main.css b/ui/new/css/main.css index 0bcf04c026b..241b94e38b6 100644 --- a/ui/new/css/main.css +++ b/ui/new/css/main.css @@ -292,7 +292,7 @@ a:visited { padding:0; } -<<<<<<< HEAD + .vmpopup_container_closebutton { width:13px; height:13px; @@ -308,8 +308,7 @@ a:visited { background:url(../images/vm_closebutton_hover.gif) no-repeat top left; } -======= ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance + .vmpopup_container_top { width:737px; height:30px; @@ -1608,11 +1607,7 @@ a:visited { } .midmenu_textbox { -<<<<<<< HEAD - width:165px; -======= - width:150px; ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance + width:165px; height:auto; float:left; margin:0 0 0 10px; @@ -1621,11 +1616,7 @@ a:visited { } .midmenu_textbox p { -<<<<<<< HEAD width:165px; -======= - width:150px; ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance height:auto; float:left; text-align:left; @@ -1939,7 +1930,6 @@ a:visited { background:url(../images/infoerror_icon.gif) no-repeat top left; } -<<<<<<< HEAD .info_detailbox { width:99%; height:auto; @@ -1965,30 +1955,30 @@ a:visited { background:#ffe5e5 repeat top left; color:#a90000; } -======= -.info_detailbox { - width:99%; - height:auto; - float:left; - background:#fffbe6 repeat top left; - border:1px dashed #CCC; - color:#333; - margin:0 0 0 0; - padding:0; -} - -.info_detailbox p{ - width:auto; - height:auto; - float:left; - text-align:left; - font-size:11px; - margin:10px; - padding:0; -} - -.info_detailbox.errorbox { - background:#ffe5e5 repeat top left; - color:#a90000; -} ->>>>>>> 10bc0b5... new UI - left menu, middle menu, instance + +.info_detailbox { + width:99%; + height:auto; + float:left; + background:#fffbe6 repeat top left; + border:1px dashed #CCC; + color:#333; + margin:0 0 0 0; + padding:0; +} + +.info_detailbox p{ + width:auto; + height:auto; + float:left; + text-align:left; + font-size:11px; + margin:10px; + padding:0; +} + +.info_detailbox.errorbox { + background:#ffe5e5 repeat top left; + color:#a90000; +} + From 6ec54555796505e22855c4145b84618d001cac92 Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 11:37:55 -0700 Subject: [PATCH 080/235] If no translation is found, return original word (i.e. English word) --- .../classes/resources/resource.properties | 6 +---- .../classes/resources/resource_zh.properties | 19 +++++++++++---- ui/new/jsp/tab_instance.jsp | 24 +++++++++---------- .../com/cloud/utils/CloudResourceBundle.java | 2 +- 4 files changed, 28 insertions(+), 23 deletions(-) diff --git a/client/WEB-INF/classes/resources/resource.properties b/client/WEB-INF/classes/resources/resource.properties index b7a3baead51..0310e1c3f06 100644 --- a/client/WEB-INF/classes/resources/resource.properties +++ b/client/WEB-INF/classes/resources/resource.properties @@ -1,5 +1 @@ -computer = computer -disk = disk -computer_disk_hahaha = computer disk hahaha -monitor = monitor -keyboard = keyboard +Details = Details diff --git a/client/WEB-INF/classes/resources/resource_zh.properties b/client/WEB-INF/classes/resources/resource_zh.properties index 948c8e13203..307334f028f 100644 --- a/client/WEB-INF/classes/resources/resource_zh.properties +++ b/client/WEB-INF/classes/resources/resource_zh.properties @@ -1,5 +1,14 @@ -computer = 電腦 -disk = 硬碟 -computer_disk_hahaha = 電腦 硬碟 哈哈哈 !!! -monitor = 瑩幕 -keyboard = 鍵盤 +Details = 詳述 +Volume = 容積 +Statistics = 統計 +Zone = 區域 +Template = 模板 +Service = 服務 +HA = 高的可用性 +Created = 產生日期 +Account = 帳戶 +Domain = 領土 +Host = 主機 +ISO = 空白模板 + + diff --git a/ui/new/jsp/tab_instance.jsp b/ui/new/jsp/tab_instance.jsp index 599222ccad1..d3d2b6aeeb3 100755 --- a/ui/new/jsp/tab_instance.jsp +++ b/ui/new/jsp/tab_instance.jsp @@ -24,11 +24,11 @@
    - Details <%=t.t("computer")%>
    + <%=t.t("Details")%>
    - Volume
    + <%=t.t("Volume")%>
    - Statistics
    + <%=t.t("Statistics")%>
    @@ -47,7 +47,7 @@
    - Zone:
    + <%=t.t("Zone")%>:
    @@ -57,7 +57,7 @@
    - Template:
    + <%=t.t("Template")%>:
    @@ -67,7 +67,7 @@
    - Service:
    + <%=t.t("Service")%>:
    @@ -77,7 +77,7 @@
    - HA:
    + <%=t.t("HA")%>:
    @@ -89,7 +89,7 @@
    - Created:
    + <%=t.t("Created")%>:
    @@ -99,7 +99,7 @@
    - Account:
    + <%=t.t("Account")%>:
    @@ -109,7 +109,7 @@
    - Domain:
    + <%=t.t("Domain")%>:
    @@ -119,7 +119,7 @@
    - Host:
    + <%=t.t("Host")%>:
    @@ -129,7 +129,7 @@
    - ISO:
    + <%=t.t("ISO")%>:
    diff --git a/utils/src/com/cloud/utils/CloudResourceBundle.java b/utils/src/com/cloud/utils/CloudResourceBundle.java index 146c54e50bb..69e77275928 100755 --- a/utils/src/com/cloud/utils/CloudResourceBundle.java +++ b/utils/src/com/cloud/utils/CloudResourceBundle.java @@ -19,7 +19,7 @@ public class CloudResourceBundle { try { return _bundle.getString(key); } catch(Exception e) { - return "##" + key + "##"; + return key; //if translation is not found, just return original word (i.e. English). } } From bd46014574e65ccf375ad4e4822b021aea94264b Mon Sep 17 00:00:00 2001 From: jessica Date: Wed, 25 Aug 2010 20:46:01 -0700 Subject: [PATCH 081/235] Create shared function vmJsonToRightPanel() --- ui/new/index.html | 2 +- ui/new/scripts/cloud.core.instance.js | 135 +++++++++++++------------- 2 files changed, 70 insertions(+), 67 deletions(-) diff --git a/ui/new/index.html b/ui/new/index.html index 3b085f9c385..4fe8a610925 100755 --- a/ui/new/index.html +++ b/ui/new/index.html @@ -585,7 +585,7 @@

    - IP Address: + IP Address: