cloudstack: add JDK11 support (#3601)

This adds support for JDK11 in CloudStack 4.14+:

- Fixes code to build against JDK11
- Bump to Debian 9 systemvmtemplate with openjdk-11
- Fix Travis to run smoketests against openjdk-11
- Use maven provided jdk11 compatible mysql-connector-java
- Remove old agent init.d scripts

Signed-off-by: Rohit Yadav <rohit.yadav@shapeblue.com>
This commit is contained in:
Rohit Yadav 2020-02-12 12:58:25 +05:30 committed by GitHub
parent ccda5fb776
commit d90341ebf1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
185 changed files with 1988 additions and 3247 deletions

View File

@ -1 +1 @@
1.8 11.0

View File

@ -14,13 +14,16 @@
# KIND, either express or implied. See the License for the # KIND, either express or implied. See the License for the
# specific language governing permissions and limitations # specific language governing permissions and limitations
# under the License. # under the License.
sudo: required sudo: required
dist: xenial dist: bionic
group: edge group: stable
language: java language: java
jdk: jdk:
- openjdk8 - openjdk11
python: python:
- "2.7" - "2.7"
@ -46,6 +49,7 @@ env:
smoke/test_create_list_domain_account_project smoke/test_create_list_domain_account_project
smoke/test_create_network smoke/test_create_network
smoke/test_deploy_vgpu_enabled_vm smoke/test_deploy_vgpu_enabled_vm
smoke/test_deploy_vm_extra_config_data
smoke/test_deploy_vm_iso smoke/test_deploy_vm_iso
smoke/test_deploy_vm_root_resize smoke/test_deploy_vm_root_resize
smoke/test_deploy_vm_with_userdata smoke/test_deploy_vm_with_userdata
@ -153,6 +157,7 @@ env:
component/test_project_resources" component/test_project_resources"
- TESTS="component/test_project_usage - TESTS="component/test_project_usage
component/test_protocol_number_security_group
component/test_resource_limits" component/test_resource_limits"
- TESTS="component/test_regions_accounts - TESTS="component/test_regions_accounts

View File

@ -15,15 +15,8 @@ was tested against a CentOS 7 x86_64 setup.
Install tools and dependencies used for development: Install tools and dependencies used for development:
$ yum install git java-1.8.0-openjdk java-1.8.0-openjdk-devel \ # yum -y install git java-11-openjdk java-11-openjdk-devel \
mysql mysql-server mkisofs gcc python MySQL-python openssh-clients wget mysql mysql-server mkisofs git gcc python MySQL-python openssh-clients wget
# yum -y update
# yum -y install java-1.8.0-openjdk
# yum -y install java-1.8.0-openjdk-devel
# yum -y install mysql-server
# yum -y install git
# yum -y install genisoimage
Set up Maven (3.6.0): Set up Maven (3.6.0):

View File

@ -1,119 +0,0 @@
#!/bin/bash
# chkconfig: 35 99 10
# description: Cloud Agent
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well
. /etc/rc.d/init.d/functions
# set environment variables
SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"
JSVC=`which jsvc 2>/dev/null`;
# exit if we don't find jsvc
if [ -z "$JSVC" ]; then
echo no jsvc found in path;
exit 1;
fi
unset OPTIONS
[ -r @SYSCONFDIR@/sysconfig/"$SHORTNAME" ] && source @SYSCONFDIR@/sysconfig/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
JAVA_HOME="$jdir"
fi
done
export JAVA_HOME
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@:@AGENTLIBDIR@"
start() {
echo -n $"Starting $PROGNAME: "
if hostname --fqdn >/dev/null 2>&1 ; then
$JSVC -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
echo
else
failure
echo
echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr
RETVAL=9
fi
[ $RETVAL = 0 ] && touch ${LOCKFILE}
return $RETVAL
}
stop() {
echo -n $"Stopping $PROGNAME: "
$JSVC -pidfile "$PIDFILE" -stop $CLASS
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE}
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status -p ${PIDFILE} $SHORTNAME
RETVAL=$?
;;
restart)
stop
sleep 3
start
;;
condrestart)
if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then
stop
sleep 3
start
fi
;;
*)
echo $"Usage: $SHORTNAME {start|stop|restart|condrestart|status|help}"
RETVAL=3
esac
exit $RETVAL

View File

@ -1,119 +0,0 @@
#!/bin/bash
# chkconfig: 35 99 10
# description: Cloud Agent
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well
. /etc/rc.d/init.d/functions
# set environment variables
SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"
JSVC=`which jsvc 2>/dev/null`;
# exit if we don't find jsvc
if [ -z "$JSVC" ]; then
echo no jsvc found in path;
exit 1;
fi
unset OPTIONS
[ -r @SYSCONFDIR@/sysconfig/"$SHORTNAME" ] && source @SYSCONFDIR@/sysconfig/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
JAVA_HOME="$jdir"
fi
done
export JAVA_HOME
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@:@AGENTLIBDIR@"
start() {
echo -n $"Starting $PROGNAME: "
if hostname --fqdn >/dev/null 2>&1 ; then
$JSVC -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
echo
else
failure
echo
echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr
RETVAL=9
fi
[ $RETVAL = 0 ] && touch ${LOCKFILE}
return $RETVAL
}
stop() {
echo -n $"Stopping $PROGNAME: "
$JSVC -pidfile "$PIDFILE" -stop $CLASS
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE}
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status -p ${PIDFILE} $SHORTNAME
RETVAL=$?
;;
restart)
stop
sleep 3
start
;;
condrestart)
if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then
stop
sleep 3
start
fi
;;
*)
echo $"Usage: $SHORTNAME {start|stop|restart|condrestart|status|help}"
RETVAL=3
esac
exit $RETVAL

View File

@ -1,172 +0,0 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: cloudstack-agent
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# X-Interactive: true
# Short-Description: Start/stop apache2 web server
### END INIT INFO
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well
. /lib/lsb/init-functions
. /etc/rc.status
# set environment variables
SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"
unset OPTIONS
[ -r @SYSCONFDIR@/default/"$SHORTNAME" ] && source @SYSCONFDIR@/default/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
JAVA_HOME="$jdir"
fi
done
export JAVA_HOME
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@"
wait_for_network() {
i=1
while [ $i -lt 10 ]
do
# Under Ubuntu and Debian libvirt by default creates a bridge called virbr0.
# That's why we want more then 3 lines back from brctl, so that there is a manually created bridge
if [ "$(brctl show|wc -l)" -gt 2 ]; then
break
else
sleep 1
let i=$i+1
continue
fi
done
}
start() {
log_daemon_msg $"Starting $PROGNAME" "$SHORTNAME"
if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_progress_msg "apparently already running"
log_end_msg 0
exit 0
fi
if hostname --fqdn >/dev/null 2>&1 ; then
true
else
log_failure_msg "The host name does not resolve properly to an IP address. Cannot start $PROGNAME"
log_end_msg 1
exit 1
fi
wait_for_network
if jsvc -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
then
rc=0
sleep 1
if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_failure_msg "$PROG failed to start"
rc=1
fi
else
rc=1
fi
if [ $rc -eq 0 ]; then
log_end_msg 0
else
log_end_msg 1
rm -f "$PIDFILE"
fi
}
stop() {
SHUTDOWN_WAIT="30"
count="0"
echo -n $"Stopping $PROGNAME" "$SHORTNAME"
jsvc -pidfile "$PIDFILE" -stop $CLASS
until [ "$count" -gt "$SHUTDOWN_WAIT" ]
do
agentPid=`ps aux|grep [j]svc|grep cloud-agent`
if [ "$?" -gt "0" ];then
break
fi
sleep 1
let count="${count}+1"
done
agentPid=`ps aux|grep [j]svc|grep cloud-agent`
if [ "$?" -eq "0" ]; then
agentPid=`ps aux|grep [j]svc|awk '{print $2}'`
if [ "$agentPid" != "" ]; then
kill -9 $agentPid
fi
fi
log_end_msg $?
rm -f "$PIDFILE"
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status_of_proc -p "$PIDFILE" "$PROG" "$SHORTNAME"
RETVAL=$?
;;
restart)
stop
sleep 3
start
;;
*)
echo $"Usage: $SHORTNAME {start|stop|restart|status|help}"
RETVAL=3
esac
exit $RETVAL

View File

@ -1,122 +0,0 @@
#!/bin/bash
# chkconfig: 35 99 10
# description: Cloud Agent
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well
. /etc/rc.d/init.d/functions
# set environment variables
SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"
JSVC=`which jsvc 2>/dev/null`;
# exit if we don't find jsvc
if [ -z "$JSVC" ]; then
echo no jsvc found in path;
exit 1;
fi
unset OPTIONS
[ -r @SYSCONFDIR@/sysconfig/"$SHORTNAME" ] && source @SYSCONFDIR@/sysconfig/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/jre /usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm /usr/lib/jvm/jre-1.7.0"
jhome=""
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
jhome="$jdir"
fi
done
if [ ! -z $jhome ];then
export JAVA_HOME="$jhome"
fi
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@:@AGENTLIBDIR@"
start() {
echo -n $"Starting $PROGNAME: "
if hostname --fqdn >/dev/null 2>&1 ; then
$JSVC -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
echo
else
failure
echo
echo The host name does not resolve properly to an IP address. Cannot start "$PROGNAME". > /dev/stderr
RETVAL=9
fi
[ $RETVAL = 0 ] && touch ${LOCKFILE}
return $RETVAL
}
stop() {
echo -n $"Stopping $PROGNAME: "
$JSVC -pidfile "$PIDFILE" -stop $CLASS
RETVAL=$?
echo
[ $RETVAL = 0 ] && rm -f ${LOCKFILE} ${PIDFILE}
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status -p ${PIDFILE} $SHORTNAME
RETVAL=$?
;;
restart)
stop
sleep 3
start
;;
condrestart)
if status -p ${PIDFILE} $SHORTNAME >&/dev/null; then
stop
sleep 3
start
fi
;;
*)
echo $"Usage: $SHORTNAME {start|stop|restart|condrestart|status|help}"
RETVAL=3
esac
exit $RETVAL

View File

@ -1,172 +0,0 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: cloudstack-agent
# Required-Start: $network
# Required-Stop: $network
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# X-Interactive: true
# Short-Description: Start/stop apache2 web server
### END INIT INFO
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# WARNING: if this script is changed, then all other initscripts MUST BE changed to match it as well
. /lib/lsb/init-functions
. /etc/rc.status
# set environment variables
SHORTNAME=`basename $0`
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="Cloud Agent"
CLASS="com.cloud.agent.AgentShell"
unset OPTIONS
[ -r @SYSCONFDIR@/default/"$SHORTNAME" ] && source @SYSCONFDIR@/default/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
JAVA_HOME="$jdir"
fi
done
export JAVA_HOME
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@"
wait_for_network() {
i=1
while [ $i -lt 10 ]
do
# Under Ubuntu and Debian libvirt by default creates a bridge called virbr0.
# That's why we want more then 3 lines back from brctl, so that there is a manually created bridge
if [ "$(brctl show|wc -l)" -gt 2 ]; then
break
else
sleep 1
let i=$i+1
continue
fi
done
}
start() {
log_daemon_msg $"Starting $PROGNAME" "$SHORTNAME"
if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_progress_msg "apparently already running"
log_end_msg 0
exit 0
fi
if hostname --fqdn >/dev/null 2>&1 ; then
true
else
log_failure_msg "The host name does not resolve properly to an IP address. Cannot start $PROGNAME"
log_end_msg 1
exit 1
fi
wait_for_network
if jsvc -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
then
rc=0
sleep 1
if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_failure_msg "$PROG failed to start"
rc=1
fi
else
rc=1
fi
if [ $rc -eq 0 ]; then
log_end_msg 0
else
log_end_msg 1
rm -f "$PIDFILE"
fi
}
stop() {
SHUTDOWN_WAIT="30"
count="0"
echo -n $"Stopping $PROGNAME" "$SHORTNAME"
jsvc -pidfile "$PIDFILE" -stop $CLASS
until [ "$count" -gt "$SHUTDOWN_WAIT" ]
do
agentPid=`ps aux|grep [j]svc|grep cloud-agent`
if [ "$?" -gt "0" ];then
break
fi
sleep 1
let count="${count}+1"
done
agentPid=`ps aux|grep [j]svc|grep cloud-agent`
if [ "$?" -eq "0" ]; then
agentPid=`ps aux|grep [j]svc|awk '{print $2}'`
if [ "$agentPid" != "" ]; then
kill -9 $agentPid
fi
fi
log_end_msg $?
rm -f "$PIDFILE"
}
# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status_of_proc -p "$PIDFILE" "$PROG" "$SHORTNAME"
RETVAL=$?
;;
restart)
stop
sleep 3
start
;;
*)
echo $"Usage: $SHORTNAME {start|stop|restart|status|help}"
RETVAL=3
esac
exit $RETVAL

View File

@ -1,173 +0,0 @@
#!/bin/bash
### BEGIN INIT INFO
# Provides: cloudstack-agent
# Required-Start: $network $local_fs
# Required-Stop: $network $local_fs
# Default-Start: 3 4 5
# Default-Stop: 0 1 2 6
# Short-Description: Start/stop Apache CloudStack Agent
# Description: This scripts Starts/Stops the Apache CloudStack agent
## The CloudStack Agent is a part of the Apache CloudStack project and is used
## for managing KVM-based Hypervisors and performing secondary storage tasks inside
## the Secondary Storage System Virtual Machine.
## JSVC (Java daemonizing) is used for starting and stopping the agent
### END INIT INFO
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
. /lib/lsb/init-functions
SHORTNAME="cloud-agent"
PIDFILE=@PIDDIR@/"$SHORTNAME".pid
LOCKFILE=@LOCKDIR@/"$SHORTNAME"
LOGFILE=@AGENTLOG@
PROGNAME="CloudStack Agent"
CLASS="com.cloud.agent.AgentShell"
PROG="jsvc"
DAEMON="/usr/bin/jsvc"
SHUTDOWN_WAIT="30"
unset OPTIONS
[ -r @SYSCONFDIR@/default/"$SHORTNAME" ] && source @SYSCONFDIR@/default/"$SHORTNAME"
# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-6-openjdk-i386 /usr/lib/jvm/java-6-openjdk-amd64 /usr/lib/jvm/java-6-sun /usr/lib/jvm/java-1.5.0-sun /usr/lib/j2sdk1.5-sun /usr/lib/j2sdk1.5-ibm"
for jdir in $JDK_DIRS; do
if [ -r "$jdir/bin/java" -a -z "${JAVA_HOME}" ]; then
JAVA_HOME="$jdir"
fi
done
export JAVA_HOME
SCP="@SYSTEMCLASSPATH@"
DCP="@DEPSCLASSPATH@"
ACP="@AGENTCLASSPATH@"
JCP="/usr/share/java/commons-daemon.jar"
# We need to append the JSVC daemon JAR to the classpath
# AgentShell implements the JSVC daemon methods
export CLASSPATH="$SCP:$DCP:$ACP:$JCP:@AGENTSYSCONFDIR@"
wait_for_network() {
i=1
while [ $i -lt 10 ]
do
# Under Ubuntu and Debian libvirt by default creates a bridge called virbr0.
# That's why we want more then 3 lines back from brctl, so that there is a manually created bridge
if [ "$(brctl show|wc -l)" -gt 2 ]; then
break
else
sleep 1
let i=$i+1
continue
fi
done
}
start() {
if [ -s "$PIDFILE" ] && kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_daemon_msg "$PROGNAME apparently already running"
log_end_msg 0
exit 0
fi
log_daemon_msg "Starting $PROGNAME" "$SHORTNAME"
if hostname --fqdn >/dev/null 2>&1 ; then
true
else
log_failure_msg "The host name does not resolve properly to an IP address. Cannot start $PROGNAME"
log_end_msg 1
exit 1
fi
wait_for_network
if start_daemon -p $PIDFILE $DAEMON -cp "$CLASSPATH" -pidfile "$PIDFILE" -errfile SYSLOG $CLASS
RETVAL=$?
then
rc=0
sleep 1
if ! kill -0 $(cat "$PIDFILE") >/dev/null 2>&1; then
log_failure_msg "$PROG failed to start"
rc=1
fi
else
rc=1
fi
if [ $rc -eq 0 ]; then
log_end_msg 0
else
log_end_msg 1
rm -f "$PIDFILE"
fi
}
stop() {
count="0"
log_daemon_msg "Stopping $PROGNAME" "$SHORTNAME"
killproc -p $PIDFILE $DAEMON
until [ "$count" -gt "$SHUTDOWN_WAIT" ]
do
agentPid=$(ps aux|grep [j]svc|grep $SHORTNAME)
if [ "$?" -gt "0" ];then
break
fi
sleep 1
let count="${count}+1"
done
agentPid=$(ps aux|grep [j]svc|grep $SHORTNAME)
if [ "$?" -eq "0" ]; then
agentPid=$(ps aux|grep [j]svc|awk '{print $2}')
if [ "$agentPid" != "" ]; then
log_warning_msg "$PROG still running, forcing kill"
kill -9 $agentPid
fi
fi
log_end_msg $?
rm -f "$PIDFILE"
}
case "$1" in
start)
start
;;
stop)
stop
;;
status)
status_of_proc -p "$PIDFILE" "$PROG" "$SHORTNAME"
RETVAL=$?
;;
restart | force-reload)
stop
sleep 3
start
;;
*)
echo "Usage: $0 {start|stop|restart|force-reload|status}"
RETVAL=3
esac
exit $RETVAL

View File

@ -292,8 +292,13 @@ public class Agent implements HandlerFactory, IAgentControl {
try { try {
_connection.start(); _connection.start();
} catch (final NioConnectionException e) { } catch (final NioConnectionException e) {
s_logger.warn("NIO Connection Exception " + e); _connection.stop();
s_logger.info("Attempted to connect to the server, but received an unexpected exception, trying again..."); try {
_connection.cleanUp();
} catch (final IOException ex) {
s_logger.warn("Fail to clean up old connection. " + ex);
}
s_logger.info("Attempted to connect to the server, but received an unexpected exception, trying again...", e);
} }
} }
_shell.updateConnectedHost(); _shell.updateConnectedHost();
@ -516,8 +521,7 @@ public class Agent implements HandlerFactory, IAgentControl {
try { try {
_connection.start(); _connection.start();
} catch (final NioConnectionException e) { } catch (final NioConnectionException e) {
s_logger.warn("NIO Connection Exception " + e); s_logger.info("Attempted to re-connect to the server, but received an unexpected exception, trying again...", e);
s_logger.info("Attempted to connect to the server, but received an unexpected exception, trying again...");
_connection.stop(); _connection.stop();
try { try {
_connection.cleanUp(); _connection.cleanUp();

View File

@ -59,7 +59,6 @@ import com.cloud.host.Host.Type;
import com.cloud.resource.ServerResource; import com.cloud.resource.ServerResource;
import com.cloud.resource.ServerResourceBase; import com.cloud.resource.ServerResourceBase;
import com.cloud.utils.NumbersUtil; import com.cloud.utils.NumbersUtil;
import com.cloud.utils.ReflectUtil;
import com.cloud.utils.net.NetUtils; import com.cloud.utils.net.NetUtils;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import com.google.gson.Gson; import com.google.gson.Gson;
@ -317,14 +316,13 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe
private void launchConsoleProxy(final byte[] ksBits, final String ksPassword, final String encryptorPassword) { private void launchConsoleProxy(final byte[] ksBits, final String ksPassword, final String encryptorPassword) {
final Object resource = this; final Object resource = this;
s_logger.info("Building class loader for com.cloud.consoleproxy.ConsoleProxy"); s_logger.info("Building class loader for com.cloud.consoleproxy.ConsoleProxy");
final ClassLoader loader = ReflectUtil.getClassLoaderForName("console-proxy");
if (_consoleProxyMain == null) { if (_consoleProxyMain == null) {
s_logger.info("Running com.cloud.consoleproxy.ConsoleProxy with encryptor password=" + encryptorPassword); s_logger.info("Running com.cloud.consoleproxy.ConsoleProxy with encryptor password=" + encryptorPassword);
_consoleProxyMain = new Thread(new ManagedContextRunnable() { _consoleProxyMain = new Thread(new ManagedContextRunnable() {
@Override @Override
protected void runInContext() { protected void runInContext() {
try { try {
Class<?> consoleProxyClazz = loader.loadClass("com.cloud.consoleproxy.ConsoleProxy"); Class<?> consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy");
try { try {
s_logger.info("Invoke startWithContext()"); s_logger.info("Invoke startWithContext()");
Method method = consoleProxyClazz.getMethod("startWithContext", Properties.class, Object.class, byte[].class, String.class, String.class); Method method = consoleProxyClazz.getMethod("startWithContext", Properties.class, Object.class, byte[].class, String.class, String.class);
@ -357,7 +355,7 @@ public class ConsoleProxyResource extends ServerResourceBase implements ServerRe
s_logger.info("com.cloud.consoleproxy.ConsoleProxy is already running"); s_logger.info("com.cloud.consoleproxy.ConsoleProxy is already running");
try { try {
Class<?> consoleProxyClazz = loader.loadClass("com.cloud.consoleproxy.ConsoleProxy"); Class<?> consoleProxyClazz = Class.forName("com.cloud.consoleproxy.ConsoleProxy");
Method methodSetup = consoleProxyClazz.getMethod("setEncryptorPassword", String.class); Method methodSetup = consoleProxyClazz.getMethod("setEncryptorPassword", String.class);
methodSetup.invoke(null, encryptorPassword); methodSetup.invoke(null, encryptorPassword);
} catch (SecurityException e) { } catch (SecurityException e) {

View File

@ -16,29 +16,29 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command.test; package org.apache.cloudstack.api.command.test;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject; import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Matchers.anyString; import static org.mockito.ArgumentMatchers.anyObject;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isNull;
import java.util.Map; import java.util.Map;
import junit.framework.Assert; import org.apache.cloudstack.api.ResponseGenerator;
import junit.framework.TestCase; import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.apache.cloudstack.api.ResponseGenerator;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.admin.storage.AddImageStoreCmd;
import org.apache.cloudstack.api.response.ImageStoreResponse;
import com.cloud.storage.ImageStore; import com.cloud.storage.ImageStore;
import com.cloud.storage.StorageService; import com.cloud.storage.StorageService;
import junit.framework.TestCase;
public class AddSecondaryStorageCmdTest extends TestCase { public class AddSecondaryStorageCmdTest extends TestCase {
private AddImageStoreCmd addImageStoreCmd; private AddImageStoreCmd addImageStoreCmd;
@ -62,25 +62,22 @@ public class AddSecondaryStorageCmdTest extends TestCase {
ImageStore store = Mockito.mock(ImageStore.class); ImageStore store = Mockito.mock(ImageStore.class);
Mockito.when(resourceService.discoverImageStore(anyString(), anyString(), anyString(), anyLong(), (Map)anyObject())) Mockito.when(resourceService.discoverImageStore(isNull(), isNull(), isNull(), isNull(), isNull())).thenReturn(store);
.thenReturn(store);
ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class); ResponseGenerator responseGenerator = Mockito.mock(ResponseGenerator.class);
addImageStoreCmd._responseGenerator = responseGenerator; addImageStoreCmd._responseGenerator = responseGenerator;
ImageStoreResponse responseHost = new ImageStoreResponse(); ImageStoreResponse responseHost = new ImageStoreResponse();
responseHost.setName("Test"); responseHost.setName("Test");
Mockito.when(responseGenerator.createImageStoreResponse(store)).thenReturn(responseHost); Mockito.doReturn(responseHost).when(responseGenerator).createImageStoreResponse(store);
addImageStoreCmd.execute(); addImageStoreCmd.execute();
Mockito.verify(responseGenerator).createImageStoreResponse(store); Mockito.verify(responseGenerator).createImageStoreResponse(store);
ImageStoreResponse actualResponse = (ImageStoreResponse)addImageStoreCmd.getResponseObject(); ImageStoreResponse actualResponse = (ImageStoreResponse)addImageStoreCmd.getResponseObject();
assertEquals(responseHost, actualResponse);
Assert.assertEquals(responseHost, actualResponse); assertEquals("addimagestoreresponse", actualResponse.getResponseName());
Assert.assertEquals("addimagestoreresponse", actualResponse.getResponseName());
} }
@ -96,7 +93,7 @@ public class AddSecondaryStorageCmdTest extends TestCase {
try { try {
addImageStoreCmd.execute(); addImageStoreCmd.execute();
} catch (ServerApiException exception) { } catch (ServerApiException exception) {
Assert.assertEquals("Failed to add secondary storage", exception.getDescription()); assertEquals("Failed to add secondary storage", exception.getDescription());
} }
} }

View File

@ -16,24 +16,25 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command.test; package org.apache.cloudstack.api.command.test;
import junit.framework.Assert; import static org.mockito.ArgumentMatchers.anyLong;
import junit.framework.TestCase; import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.nullable;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.vpn.AddVpnUserCmd;
import org.junit.Before; import org.junit.Before;
import org.junit.Rule; import org.junit.Rule;
import org.junit.Test; import org.junit.Test;
import org.junit.rules.ExpectedException; import org.junit.rules.ExpectedException;
import org.mockito.Matchers;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.command.user.vpn.AddVpnUserCmd;
import com.cloud.network.VpnUser; import com.cloud.network.VpnUser;
import com.cloud.network.vpn.RemoteAccessVpnService; import com.cloud.network.vpn.RemoteAccessVpnService;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountService; import com.cloud.user.AccountService;
import junit.framework.Assert;
import junit.framework.TestCase;
public class AddVpnUserCmdTest extends TestCase { public class AddVpnUserCmdTest extends TestCase {
private AddVpnUserCmd addVpnUserCmd; private AddVpnUserCmd addVpnUserCmd;
@ -76,14 +77,15 @@ public class AddVpnUserCmdTest extends TestCase {
AccountService accountService = Mockito.mock(AccountService.class); AccountService accountService = Mockito.mock(AccountService.class);
Account account = Mockito.mock(Account.class); Account account = Mockito.mock(Account.class);
Mockito.when(accountService.getAccount(Matchers.anyLong())).thenReturn(account); Mockito.when(accountService.getAccount(nullable(Long.class))).thenReturn(account);
addVpnUserCmd._accountService = accountService; addVpnUserCmd._accountService = accountService;
RemoteAccessVpnService ravService = Mockito.mock(RemoteAccessVpnService.class); RemoteAccessVpnService ravService = Mockito.mock(RemoteAccessVpnService.class);
VpnUser vpnUser = Mockito.mock(VpnUser.class); VpnUser vpnUser = Mockito.mock(VpnUser.class);
Mockito.when(ravService.addVpnUser(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(vpnUser);
Mockito.when(ravService.addVpnUser(anyLong(), isNull(), isNull())).thenReturn(vpnUser);
addVpnUserCmd._ravService = ravService; addVpnUserCmd._ravService = ravService;
@ -96,12 +98,13 @@ public class AddVpnUserCmdTest extends TestCase {
AccountService accountService = Mockito.mock(AccountService.class); AccountService accountService = Mockito.mock(AccountService.class);
Account account = Mockito.mock(Account.class); Account account = Mockito.mock(Account.class);
Mockito.when(accountService.getAccount(Matchers.anyLong())).thenReturn(account); Mockito.when(accountService.getAccount(nullable(Long.class))).thenReturn(account);
addVpnUserCmd._accountService = accountService; addVpnUserCmd._accountService = accountService;
RemoteAccessVpnService ravService = Mockito.mock(RemoteAccessVpnService.class); RemoteAccessVpnService ravService = Mockito.mock(RemoteAccessVpnService.class);
Mockito.when(ravService.addVpnUser(Matchers.anyLong(), Matchers.anyString(), Matchers.anyString())).thenReturn(null);
Mockito.when(ravService.addVpnUser(anyLong(), isNull(), isNull())).thenReturn(null);
addVpnUserCmd._ravService = ravService; addVpnUserCmd._ravService = ravService;

View File

@ -16,8 +16,7 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command.test; package org.apache.cloudstack.api.command.test;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.anyString;
@ -92,8 +91,8 @@ public class CreateSnapshotCmdTest extends TestCase {
VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class); VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class);
Snapshot snapshot = Mockito.mock(Snapshot.class); Snapshot snapshot = Mockito.mock(Snapshot.class);
try { try {
Mockito.when(volumeApiService.takeSnapshot(anyLong(), anyLong(), anyLong(), Mockito.when(volumeApiService.takeSnapshot(nullable(Long.class), nullable(Long.class), isNull(),
any(Account.class), anyBoolean(), isNull(Snapshot.LocationType.class), anyBoolean(), anyObject())).thenReturn(snapshot); nullable(Account.class), nullable(Boolean.class), nullable(Snapshot.LocationType.class), nullable(Boolean.class), nullable(Map.class))).thenReturn(snapshot);
} catch (Exception e) { } catch (Exception e) {
Assert.fail("Received exception when success expected " + e.getMessage()); Assert.fail("Received exception when success expected " + e.getMessage());
@ -125,8 +124,8 @@ public class CreateSnapshotCmdTest extends TestCase {
VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class); VolumeApiService volumeApiService = Mockito.mock(VolumeApiService.class);
try { try {
Mockito.when(volumeApiService.takeSnapshot(anyLong(), anyLong(), anyLong(), Mockito.when(volumeApiService.takeSnapshot(nullable(Long.class), nullable(Long.class), nullable(Long.class),
any(Account.class), anyBoolean(), isNull(Snapshot.LocationType.class), anyBoolean(), anyObject())).thenReturn(null); nullable(Account.class), nullable(Boolean.class), nullable(Snapshot.LocationType.class), nullable(Boolean.class), anyObject())).thenReturn(null);
} catch (Exception e) { } catch (Exception e) {
Assert.fail("Received exception when success expected " + e.getMessage()); Assert.fail("Received exception when success expected " + e.getMessage());
} }

View File

@ -16,15 +16,9 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command.test; package org.apache.cloudstack.api.command.test;
import junit.framework.Assert; import static org.mockito.ArgumentMatchers.anyInt;
import junit.framework.TestCase; import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.isNull;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Matchers;
import org.mockito.Mockito;
import org.apache.cloudstack.api.ResponseGenerator; import org.apache.cloudstack.api.ResponseGenerator;
import org.apache.cloudstack.api.ServerApiException; import org.apache.cloudstack.api.ServerApiException;
@ -32,6 +26,13 @@ import org.apache.cloudstack.api.command.admin.region.AddRegionCmd;
import org.apache.cloudstack.api.response.RegionResponse; import org.apache.cloudstack.api.response.RegionResponse;
import org.apache.cloudstack.region.Region; import org.apache.cloudstack.region.Region;
import org.apache.cloudstack.region.RegionService; import org.apache.cloudstack.region.RegionService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import junit.framework.TestCase;
public class RegionCmdTest extends TestCase { public class RegionCmdTest extends TestCase {
@ -66,7 +67,8 @@ public class RegionCmdTest extends TestCase {
RegionService regionService = Mockito.mock(RegionService.class); RegionService regionService = Mockito.mock(RegionService.class);
Region region = Mockito.mock(Region.class); Region region = Mockito.mock(Region.class);
Mockito.when(regionService.addRegion(Matchers.anyInt(), Matchers.anyString(), Matchers.anyString())).thenReturn(region);
Mockito.when(regionService.addRegion(anyInt(), anyString(), isNull())).thenReturn(region);
addRegionCmd._regionService = regionService; addRegionCmd._regionService = regionService;
responseGenerator = Mockito.mock(ResponseGenerator.class); responseGenerator = Mockito.mock(ResponseGenerator.class);
@ -86,14 +88,15 @@ public class RegionCmdTest extends TestCase {
RegionService regionService = Mockito.mock(RegionService.class); RegionService regionService = Mockito.mock(RegionService.class);
Region region = Mockito.mock(Region.class); Region region = Mockito.mock(Region.class);
Mockito.when(regionService.addRegion(Matchers.anyInt(), Matchers.anyString(), Matchers.anyString())).thenReturn(null);
Mockito.when(regionService.addRegion(anyInt(), anyString(), isNull())).thenReturn(null);
addRegionCmd._regionService = regionService; addRegionCmd._regionService = regionService;
try { try {
addRegionCmd.execute(); addRegionCmd.execute();
} catch (ServerApiException exception) { } catch (ServerApiException exception) {
Assert.assertEquals("Failed to add Region", exception.getDescription()); assertEquals("Failed to add Region", exception.getDescription());
} }
} }

View File

@ -61,7 +61,6 @@
<dependency> <dependency>
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.cloudstack</groupId> <groupId>org.apache.cloudstack</groupId>
@ -537,9 +536,13 @@
</dependency> </dependency>
</dependencies> </dependencies>
<configuration> <configuration>
<supportedPackagings>
<supportedPackaging>jar</supportedPackaging>
</supportedPackagings>
<scanIntervalSeconds>0</scanIntervalSeconds> <scanIntervalSeconds>0</scanIntervalSeconds>
<stopPort>9966</stopPort> <stopPort>9966</stopPort>
<stopKey>stop-jetty</stopKey> <stopKey>stop-jetty</stopKey>
<stopWait>10</stopWait>
<connectors> <connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector"> <connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port> <port>8080</port>
@ -548,11 +551,11 @@
</connectors> </connectors>
<webXml>${project.build.directory}/classes/META-INF/webapp/WEB-INF/web.xml</webXml> <webXml>${project.build.directory}/classes/META-INF/webapp/WEB-INF/web.xml</webXml>
<webAppSourceDirectory>${project.build.directory}/classes/META-INF/webapp/</webAppSourceDirectory> <webAppSourceDirectory>${project.build.directory}/classes/META-INF/webapp/</webAppSourceDirectory>
<webAppConfig> <webApp>
<contextPath>/client</contextPath> <contextPath>/client</contextPath>
<extraClasspath>${project.build.directory}/conf/;${project.build.directory}/common;${project.build.directory}/utilities/scripts/db/;${project.build.directory}/utilities/scripts/db/db/</extraClasspath> <extraClasspath>${project.build.directory}/conf/;${project.build.directory}/common;${project.build.directory}/utilities/scripts/db/;${project.build.directory}/utilities/scripts/db/db/;${project.build.directory}/cloud-client-ui-${project.version}.jar</extraClasspath>
<webInfIncludeJarPattern>.*/cloud.*jar$|.*/classes/.*</webInfIncludeJarPattern> <webInfIncludeJarPattern>.*/cloud.*jar$|.*/classes/.*</webInfIncludeJarPattern>
</webAppConfig> </webApp>
<systemProperties> <systemProperties>
<systemProperty> <systemProperty>
<name>log4j.configuration</name> <name>log4j.configuration</name>
@ -697,6 +700,12 @@
<overWrite>false</overWrite> <overWrite>false</overWrite>
<outputDirectory>${project.build.directory}/pythonlibs</outputDirectory> <outputDirectory>${project.build.directory}/pythonlibs</outputDirectory>
</artifactItem> </artifactItem>
<artifactItem>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<overWrite>false</overWrite>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</artifactItem>
<artifactItem> <artifactItem>
<groupId>org.bouncycastle</groupId> <groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId> <artifactId>bcprov-jdk15on</artifactId>
@ -737,7 +746,7 @@
<exclude>org.mockito:mockito-all</exclude> <exclude>org.mockito:mockito-all</exclude>
<exclude>org.hamcrest:hamcrest-all</exclude> <exclude>org.hamcrest:hamcrest-all</exclude>
<exclude>org.powermock:powermock-module-junit4</exclude> <exclude>org.powermock:powermock-module-junit4</exclude>
<exclude>org.powermock:powermock-api-mockito</exclude> <exclude>org.powermock:powermock-api-mockito2</exclude>
<exclude>org.springframework:spring-test</exclude> <exclude>org.springframework:spring-test</exclude>
<exclude>org.apache.tomcat.embed:tomcat-embed-core</exclude> <exclude>org.apache.tomcat.embed:tomcat-embed-core</exclude>
<exclude>org.apache.geronimo.specs:geronimo-servlet_3.0_spec</exclude> <exclude>org.apache.geronimo.specs:geronimo-servlet_3.0_spec</exclude>

View File

@ -18,23 +18,26 @@
*/ */
package com.cloud.storage.template; package com.cloud.storage.template;
import com.cloud.exception.InternalErrorException; import java.io.File;
import com.cloud.storage.Storage; import java.io.IOException;
import com.cloud.storage.StorageLayer; import java.util.HashMap;
import java.util.Map;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File; import com.cloud.exception.InternalErrorException;
import java.io.IOException; import com.cloud.storage.Storage;
import java.util.HashMap; import com.cloud.storage.StorageLayer;
import java.util.Map;
@RunWith(MockitoJUnitRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(QCOW2Processor.class)
public class QCOW2ProcessorTest { public class QCOW2ProcessorTest {
QCOW2Processor processor; QCOW2Processor processor;

View File

@ -19,17 +19,6 @@
package com.cloud.storage.template; package com.cloud.storage.template;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage;
import com.cloud.storage.StorageLayer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
@ -37,7 +26,21 @@ import java.nio.charset.Charset;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@RunWith(MockitoJUnitRunner.class) import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.exception.InternalErrorException;
import com.cloud.storage.Storage;
import com.cloud.storage.StorageLayer;
@RunWith(PowerMockRunner.class)
@PrepareForTest(VhdProcessor.class)
public class VhdProcessorTest { public class VhdProcessorTest {
VhdProcessor processor; VhdProcessor processor;

8
debian/control vendored
View File

@ -2,7 +2,7 @@ Source: cloudstack
Section: libs Section: libs
Priority: extra Priority: extra
Maintainer: Wido den Hollander <wido@widodh.nl> Maintainer: Wido den Hollander <wido@widodh.nl>
Build-Depends: debhelper (>= 9), openjdk-8-jdk | java8-sdk | java8-jdk | openjdk-9-jdk, genisoimage, Build-Depends: debhelper (>= 9), openjdk-11-jdk | java11-sdk | java11-jdk, genisoimage,
python-mysql.connector, maven (>= 3) | maven3, python (>= 2.7), python3 (>= 3), lsb-release, dh-systemd, python-setuptools python-mysql.connector, maven (>= 3) | maven3, python (>= 2.7), python3 (>= 3), lsb-release, dh-systemd, python-setuptools
Standards-Version: 3.8.1 Standards-Version: 3.8.1
Homepage: http://www.cloudstack.org/ Homepage: http://www.cloudstack.org/
@ -15,14 +15,14 @@ Description: A common package which contains files which are shared by several C
Package: cloudstack-management Package: cloudstack-management
Architecture: all Architecture: all
Depends: ${python:Depends}, openjdk-8-jre-headless | java8-runtime-headless | java8-runtime | openjdk-9-jre-headless, cloudstack-common (= ${source:Version}), sudo, python-mysql.connector, libmysql-java, augeas-tools, mysql-client, adduser, bzip2, ipmitool, file, gawk, iproute2, lsb-release, init-system-helpers (>= 1.14~), qemu-utils, python-dnspython Depends: ${python:Depends}, openjdk-11-jre-headless | java11-runtime-headless | java11-runtime | openjdk-11-jre-headless, cloudstack-common (= ${source:Version}), sudo, python-mysql.connector, augeas-tools, mysql-client | mariadb-client, adduser, bzip2, ipmitool, file, gawk, iproute2, qemu-utils, python-dnspython, lsb-release, init-system-helpers (>= 1.14~)
Conflicts: cloud-server, cloud-client, cloud-client-ui Conflicts: cloud-server, cloud-client, cloud-client-ui
Description: CloudStack server library Description: CloudStack server library
The CloudStack management server The CloudStack management server
Package: cloudstack-agent Package: cloudstack-agent
Architecture: all Architecture: all
Depends: ${python:Depends}, openjdk-8-jre-headless | java8-runtime-headless | java8-runtime | openjdk-9-jre-headless, cloudstack-common (= ${source:Version}), lsb-base (>= 9), openssh-client, qemu-kvm (>= 2.5), libvirt-bin (>= 1.3) | libvirt-daemon-system (>= 3.0), uuid-runtime, iproute2, ebtables, vlan, ipset, python3-libvirt, ethtool, iptables, lsb-release, aria2 Depends: ${python:Depends}, openjdk-11-jre-headless | java11-runtime-headless | java11-runtime | openjdk-11-jre-headless, cloudstack-common (= ${source:Version}), lsb-base (>= 9), openssh-client, qemu-kvm (>= 2.5), libvirt-bin (>= 1.3) | libvirt-daemon-system (>= 3.0), uuid-runtime, iproute2, ebtables, vlan, ipset, python3-libvirt, ethtool, iptables, lsb-release, aria2
Recommends: init-system-helpers Recommends: init-system-helpers
Conflicts: cloud-agent, cloud-agent-libs, cloud-agent-deps, cloud-agent-scripts Conflicts: cloud-agent, cloud-agent-libs, cloud-agent-deps, cloud-agent-scripts
Description: CloudStack agent Description: CloudStack agent
@ -32,7 +32,7 @@ Description: CloudStack agent
Package: cloudstack-usage Package: cloudstack-usage
Architecture: all Architecture: all
Depends: openjdk-8-jre-headless | java8-runtime-headless | java8-runtime | openjdk-9-jre-headless, cloudstack-common (= ${source:Version}), libmysql-java, init-system-helpers Depends: openjdk-11-jre-headless | java11-runtime-headless | java11-runtime | openjdk-11-jre-headless, cloudstack-common (= ${source:Version}), init-system-helpers
Description: CloudStack usage monitor Description: CloudStack usage monitor
The CloudStack usage monitor provides usage accounting across the entire cloud for The CloudStack usage monitor provides usage accounting across the entire cloud for
cloud operators to charge based on usage parameters. cloud operators to charge based on usage parameters.

3
debian/rules vendored
View File

@ -110,7 +110,7 @@ override_dh_auto_install:
install -D client/target/utilities/bin/cloud-sysvmadm $(DESTDIR)/usr/bin/cloudstack-sysvmadm install -D client/target/utilities/bin/cloud-sysvmadm $(DESTDIR)/usr/bin/cloudstack-sysvmadm
install -D systemvm/dist/systemvm.iso $(DESTDIR)/usr/share/$(PACKAGE)-common/vms/systemvm.iso install -D systemvm/dist/systemvm.iso $(DESTDIR)/usr/share/$(PACKAGE)-common/vms/systemvm.iso
# We need jasypt for cloud-install-sys-tmplt, so this is a nasty hack to get it into the right place # We need jasypt for cloud-install-sys-tmplt, so this is a nasty hack to get it into the right place
install -D agent/target/dependencies/jasypt-1.9.2.jar $(DESTDIR)/usr/share/$(PACKAGE)-common/lib install -D agent/target/dependencies/jasypt-1.9.3.jar $(DESTDIR)/usr/share/$(PACKAGE)-common/lib
# cloudstack-python # cloudstack-python
mkdir -p $(DESTDIR)/usr/share/pyshared mkdir -p $(DESTDIR)/usr/share/pyshared
@ -122,6 +122,7 @@ override_dh_auto_install:
mkdir $(DESTDIR)/usr/share/$(PACKAGE)-usage/plugins mkdir $(DESTDIR)/usr/share/$(PACKAGE)-usage/plugins
install -D usage/target/cloud-usage-$(VERSION).jar $(DESTDIR)/usr/share/$(PACKAGE)-usage/lib/$(PACKAGE)-usage.jar install -D usage/target/cloud-usage-$(VERSION).jar $(DESTDIR)/usr/share/$(PACKAGE)-usage/lib/$(PACKAGE)-usage.jar
install -D usage/target/dependencies/* $(DESTDIR)/usr/share/$(PACKAGE)-usage/lib/ install -D usage/target/dependencies/* $(DESTDIR)/usr/share/$(PACKAGE)-usage/lib/
cp client/target/lib/mysql*jar $(DESTDIR)/usr/share/$(PACKAGE)-usage/lib/
cp usage/target/transformed/db.properties $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/usage/ cp usage/target/transformed/db.properties $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/usage/
cp usage/target/transformed/log4j-cloud_usage.xml $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/usage/log4j-cloud.xml cp usage/target/transformed/log4j-cloud_usage.xml $(DESTDIR)/$(SYSCONFDIR)/$(PACKAGE)/usage/log4j-cloud.xml

View File

@ -58,5 +58,20 @@
<artifactId>cloud-framework-config</artifactId> <artifactId>cloud-framework-config</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -24,12 +24,12 @@ import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
import org.apache.log4j.Logger;
import com.cloud.configuration.ManagementServiceConfiguration;
import org.apache.cloudstack.framework.messagebus.MessageBus; import org.apache.cloudstack.framework.messagebus.MessageBus;
import org.apache.cloudstack.framework.messagebus.PublishScope; import org.apache.cloudstack.framework.messagebus.PublishScope;
import org.apache.log4j.Logger;
import com.cloud.agent.api.HostVmStateReportEntry; import com.cloud.agent.api.HostVmStateReportEntry;
import com.cloud.configuration.ManagementServiceConfiguration;
import com.cloud.utils.DateUtil; import com.cloud.utils.DateUtil;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDao;

View File

@ -48,5 +48,9 @@
<artifactId>cloud-framework-db</artifactId> <artifactId>cloud-framework-db</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -189,6 +189,7 @@ public class DatabaseUpgradeChecker implements SystemIntegrityChecker {
.next("4.11.3.0", new Upgrade41120to41200()) .next("4.11.3.0", new Upgrade41120to41200())
.next("4.12.0.0", new Upgrade41200to41300()) .next("4.12.0.0", new Upgrade41200to41300())
.next("4.13.0.0", new Upgrade41300to41400()) .next("4.13.0.0", new Upgrade41300to41400())
.next("4.13.1.0", new Upgrade41300to41400())
.build(); .build();
} }

View File

@ -19,23 +19,11 @@ package com.cloud.upgrade.dao;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
public class Upgrade41200to41300 implements DbUpgrade { public class Upgrade41200to41300 implements DbUpgrade {
final static Logger LOG = Logger.getLogger(Upgrade41200to41300.class);
@Override @Override
public String[] getUpgradableVersionRange() { public String[] getUpgradableVersionRange() {
return new String[] {"4.12.0.0", "4.13.0.0"}; return new String[] {"4.12.0.0", "4.13.0.0"};
@ -64,175 +52,6 @@ public class Upgrade41200to41300 implements DbUpgrade {
@Override @Override
public void performDataMigration(Connection conn) { public void performDataMigration(Connection conn) {
updateSystemVmTemplates(conn);
}
@SuppressWarnings("serial")
private void updateSystemVmTemplates(final Connection conn) {
LOG.debug("Updating System Vm template IDs");
final Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
case XenServer:
hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
break;
case KVM:
hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
break;
case VMware:
hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
break;
case Hyperv:
hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
break;
case LXC:
hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
break;
case Ovm3:
hypervisorsListInUse.add(Hypervisor.HypervisorType.Ovm3);
break;
default:
break;
}
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e);
}
final Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.11.3");
put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.11.3");
put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.11.3");
put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.11.3");
put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.11.3");
put(Hypervisor.HypervisorType.Ovm3, "systemvm-ovm3-4.11.3");
}
};
final Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3");
}
};
final Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.VMware, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-vmware.ova");
put(Hypervisor.HypervisorType.XenServer, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-xen.vhd.bz2");
put(Hypervisor.HypervisorType.Hyperv, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-hyperv.vhd.zip");
put(Hypervisor.HypervisorType.LXC, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.Ovm3, "https://download.cloudstack.org/systemvm/4.11/systemvmtemplate-4.11.3-ovm.raw.bz2");
}
};
final Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "15ec268d0939a8fa0be1bc79f397a167");
put(Hypervisor.HypervisorType.XenServer, "ae96f35fb746524edc4ebc9856719d71");
put(Hypervisor.HypervisorType.VMware, "f50c82139430afce7e4e46d3a585abbd");
put(Hypervisor.HypervisorType.Hyperv, "abf411f6cdd9139716b5d8172ab903a6");
put(Hypervisor.HypervisorType.LXC, "15ec268d0939a8fa0be1bc79f397a167");
put(Hypervisor.HypervisorType.Ovm3, "c71f143a477f4c7a0d5e8c82ccb00220");
}
};
for (final Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
LOG.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1")) {
// Get 4.11 systemvm template id for corresponding hypervisor
long templateId = -1;
pstmt.setString(1, hypervisorAndTemplateName.getValue());
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
templateId = rs.getLong(1);
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates: Exception caught while getting ids of templates: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates: Exception caught while getting ids of templates", e);
}
// change template type to SYSTEM
if (templateId != -1) {
try (PreparedStatement templ_type_pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");) {
templ_type_pstmt.setLong(1, templateId);
templ_type_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e);
}
// update template ID of system Vms
try (PreparedStatement update_templ_id_pstmt = conn
.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ? and removed is NULL");) {
update_templ_id_pstmt.setLong(1, templateId);
update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
update_templ_id_pstmt.executeUpdate();
} catch (final Exception e) {
LOG.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId
+ ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to "
+ templateId, e);
}
// Change value of global configuration parameter
// router.template.* for the corresponding hypervisor
try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
update_pstmt.setString(1, hypervisorAndTemplateName.getValue());
update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
update_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to "
+ hypervisorAndTemplateName.getValue() + ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting "
+ routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e);
}
// Change value of global configuration parameter
// minreq.sysvmtemplate.version for the ACS version
try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
update_pstmt.setString(1, "4.11.3");
update_pstmt.setString(2, "minreq.sysvmtemplate.version");
update_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.11.3: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.11.3", e);
}
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) {
throw new CloudRuntimeException(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
LOG.warn(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey()
+ " hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding
// hypervisor
try (PreparedStatement update_templ_url_pstmt = conn
.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");) {
update_templ_url_pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
update_templ_url_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type "
+ hypervisorAndTemplateName.getKey().toString() + ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type "
+ hypervisorAndTemplateName.getKey().toString(), e);
}
}
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while getting ids of templates: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
}
}
LOG.debug("Updating System Vm Template IDs Complete");
} }
@Override @Override

View File

@ -19,9 +19,17 @@ package com.cloud.upgrade.dao;
import java.io.InputStream; import java.io.InputStream;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
public class Upgrade41300to41400 implements DbUpgrade { public class Upgrade41300to41400 implements DbUpgrade {
@ -56,6 +64,175 @@ public class Upgrade41300to41400 implements DbUpgrade {
@Override @Override
public void performDataMigration(Connection conn) { public void performDataMigration(Connection conn) {
updateSystemVmTemplates(conn);
}
@SuppressWarnings("serial")
private void updateSystemVmTemplates(final Connection conn) {
LOG.debug("Updating System Vm template IDs");
final Set<Hypervisor.HypervisorType> hypervisorsListInUse = new HashSet<Hypervisor.HypervisorType>();
try (PreparedStatement pstmt = conn.prepareStatement("select distinct(hypervisor_type) from `cloud`.`cluster` where removed is null"); ResultSet rs = pstmt.executeQuery()) {
while (rs.next()) {
switch (Hypervisor.HypervisorType.getType(rs.getString(1))) {
case XenServer:
hypervisorsListInUse.add(Hypervisor.HypervisorType.XenServer);
break;
case KVM:
hypervisorsListInUse.add(Hypervisor.HypervisorType.KVM);
break;
case VMware:
hypervisorsListInUse.add(Hypervisor.HypervisorType.VMware);
break;
case Hyperv:
hypervisorsListInUse.add(Hypervisor.HypervisorType.Hyperv);
break;
case LXC:
hypervisorsListInUse.add(Hypervisor.HypervisorType.LXC);
break;
case Ovm3:
hypervisorsListInUse.add(Hypervisor.HypervisorType.Ovm3);
break;
default:
break;
}
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates: Exception caught while getting hypervisor types from clusters: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting hypervisor types from clusters", e);
}
final Map<Hypervisor.HypervisorType, String> NewTemplateNameList = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "systemvm-kvm-4.14.0");
put(Hypervisor.HypervisorType.VMware, "systemvm-vmware-4.14.0");
put(Hypervisor.HypervisorType.XenServer, "systemvm-xenserver-4.14.0");
put(Hypervisor.HypervisorType.Hyperv, "systemvm-hyperv-4.14.0");
put(Hypervisor.HypervisorType.LXC, "systemvm-lxc-4.14.0");
put(Hypervisor.HypervisorType.Ovm3, "systemvm-ovm3-4.14.0");
}
};
final Map<Hypervisor.HypervisorType, String> routerTemplateConfigurationNames = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "router.template.kvm");
put(Hypervisor.HypervisorType.VMware, "router.template.vmware");
put(Hypervisor.HypervisorType.XenServer, "router.template.xenserver");
put(Hypervisor.HypervisorType.Hyperv, "router.template.hyperv");
put(Hypervisor.HypervisorType.LXC, "router.template.lxc");
put(Hypervisor.HypervisorType.Ovm3, "router.template.ovm3");
}
};
final Map<Hypervisor.HypervisorType, String> newTemplateUrl = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.VMware, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-vmware.ova");
put(Hypervisor.HypervisorType.XenServer, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-xen.vhd.bz2");
put(Hypervisor.HypervisorType.Hyperv, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-hyperv.vhd.zip");
put(Hypervisor.HypervisorType.LXC, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-kvm.qcow2.bz2");
put(Hypervisor.HypervisorType.Ovm3, "https://download.cloudstack.org/systemvm/4.14/systemvmtemplate-4.14.0-ovm.raw.bz2");
}
};
final Map<Hypervisor.HypervisorType, String> newTemplateChecksum = new HashMap<Hypervisor.HypervisorType, String>() {
{
put(Hypervisor.HypervisorType.KVM, "d15ed159be32151b07e3211caf9cb802");
put(Hypervisor.HypervisorType.XenServer, "fcaf1abc9aa62e7ed75f62b3092a01a2");
put(Hypervisor.HypervisorType.VMware, "eb39f8b5a556dfc93c6be23ae45f34e1");
put(Hypervisor.HypervisorType.Hyperv, "b4e91c14958e0fca9470695b0be05f99");
put(Hypervisor.HypervisorType.LXC, "d15ed159be32151b07e3211caf9cb802");
put(Hypervisor.HypervisorType.Ovm3, "1f97f4beb30af8cda886f1e977514704");
}
};
for (final Map.Entry<Hypervisor.HypervisorType, String> hypervisorAndTemplateName : NewTemplateNameList.entrySet()) {
LOG.debug("Updating " + hypervisorAndTemplateName.getKey() + " System Vms");
try (PreparedStatement pstmt = conn.prepareStatement("select id from `cloud`.`vm_template` where name = ? and removed is null order by id desc limit 1")) {
// Get 4.11 systemvm template id for corresponding hypervisor
long templateId = -1;
pstmt.setString(1, hypervisorAndTemplateName.getValue());
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next()) {
templateId = rs.getLong(1);
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates: Exception caught while getting ids of templates: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates: Exception caught while getting ids of templates", e);
}
// change template type to SYSTEM
if (templateId != -1) {
try (PreparedStatement templ_type_pstmt = conn.prepareStatement("update `cloud`.`vm_template` set type='SYSTEM' where id = ?");) {
templ_type_pstmt.setLong(1, templateId);
templ_type_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system': " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating template with id " + templateId + " to be marked as 'system'", e);
}
// update template ID of system Vms
try (PreparedStatement update_templ_id_pstmt = conn
.prepareStatement("update `cloud`.`vm_instance` set vm_template_id = ? where type <> 'User' and hypervisor_type = ? and removed is NULL");) {
update_templ_id_pstmt.setLong(1, templateId);
update_templ_id_pstmt.setString(2, hypervisorAndTemplateName.getKey().toString());
update_templ_id_pstmt.executeUpdate();
} catch (final Exception e) {
LOG.error("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to " + templateId
+ ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting template for " + hypervisorAndTemplateName.getKey().toString() + " to "
+ templateId, e);
}
// Change value of global configuration parameter
// router.template.* for the corresponding hypervisor
try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
update_pstmt.setString(1, hypervisorAndTemplateName.getValue());
update_pstmt.setString(2, routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()));
update_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while setting " + routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to "
+ hypervisorAndTemplateName.getValue() + ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting "
+ routerTemplateConfigurationNames.get(hypervisorAndTemplateName.getKey()) + " to " + hypervisorAndTemplateName.getValue(), e);
}
// Change value of global configuration parameter
// minreq.sysvmtemplate.version for the ACS version
try (PreparedStatement update_pstmt = conn.prepareStatement("UPDATE `cloud`.`configuration` SET value = ? WHERE name = ?");) {
update_pstmt.setString(1, "4.14.0");
update_pstmt.setString(2, "minreq.sysvmtemplate.version");
update_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.14.0: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while setting 'minreq.sysvmtemplate.version' to 4.14.0", e);
}
} else {
if (hypervisorsListInUse.contains(hypervisorAndTemplateName.getKey())) {
throw new CloudRuntimeException(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. Cannot upgrade system Vms");
} else {
LOG.warn(getUpgradedVersion() + hypervisorAndTemplateName.getKey() + " SystemVm template not found. " + hypervisorAndTemplateName.getKey()
+ " hypervisor is not used, so not failing upgrade");
// Update the latest template URLs for corresponding
// hypervisor
try (PreparedStatement update_templ_url_pstmt = conn
.prepareStatement("UPDATE `cloud`.`vm_template` SET url = ? , checksum = ? WHERE hypervisor_type = ? AND type = 'SYSTEM' AND removed is null order by id desc limit 1");) {
update_templ_url_pstmt.setString(1, newTemplateUrl.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(2, newTemplateChecksum.get(hypervisorAndTemplateName.getKey()));
update_templ_url_pstmt.setString(3, hypervisorAndTemplateName.getKey().toString());
update_templ_url_pstmt.executeUpdate();
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type "
+ hypervisorAndTemplateName.getKey().toString() + ": " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while updating 'url' and 'checksum' for hypervisor type "
+ hypervisorAndTemplateName.getKey().toString(), e);
}
}
}
} catch (final SQLException e) {
LOG.error("updateSystemVmTemplates:Exception while getting ids of templates: " + e.getMessage());
throw new CloudRuntimeException("updateSystemVmTemplates:Exception while getting ids of templates", e);
}
}
LOG.debug("Updating System Vm Template IDs Complete");
} }
@Override @Override

View File

@ -22,6 +22,9 @@
-- KVM: enable storage data motion on KVM hypervisor_capabilities -- KVM: enable storage data motion on KVM hypervisor_capabilities
UPDATE `cloud`.`hypervisor_capabilities` SET `storage_motion_supported` = 1 WHERE `hypervisor_capabilities`.`hypervisor_type` = 'KVM'; UPDATE `cloud`.`hypervisor_capabilities` SET `storage_motion_supported` = 1 WHERE `hypervisor_capabilities`.`hypervisor_type` = 'KVM';
-- Use 'Other Linux 64-bit' as guest os for the default systemvmtemplate for XenServer
UPDATE `cloud`.`vm_template` SET guest_os_id=99 WHERE id=1;
-- #3659 Fix typo: the past tense of shutdown is shutdown, not shutdowned -- #3659 Fix typo: the past tense of shutdown is shutdown, not shutdowned
UPDATE `cloud`.`vm_instance` SET state='Shutdown' WHERE state='Shutdowned'; UPDATE `cloud`.`vm_instance` SET state='Shutdown' WHERE state='Shutdowned';

View File

@ -34,8 +34,8 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class DatabaseAccessObjectTest { public class DatabaseAccessObjectTest {
@ -53,7 +53,7 @@ public class DatabaseAccessObjectTest {
@Before @Before
public void setup() { public void setup() {
Whitebox.setInternalState(dao, "s_logger", loggerMock); Whitebox.setInternalState(dao.getClass(), "s_logger", loggerMock);
} }
@Test @Test

View File

@ -16,9 +16,12 @@
// under the License. // under the License.
package org.apache.cloudstack.storage.datastore.db; package org.apache.cloudstack.storage.datastore.db;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -29,9 +32,9 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Matchers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Spy; import org.mockito.Spy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.storage.ScopeType; import com.cloud.storage.ScopeType;
@ -41,6 +44,7 @@ import com.cloud.storage.dao.StoragePoolTagsDao;
import junit.framework.TestCase; import junit.framework.TestCase;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class PrimaryDataStoreDaoImplTest extends TestCase { public class PrimaryDataStoreDaoImplTest extends TestCase {
@Mock @Mock
@ -77,12 +81,13 @@ public class PrimaryDataStoreDaoImplTest extends TestCase {
private static final Long CLUSTER_ID = null; private static final Long CLUSTER_ID = null;
private static final ScopeType SCOPE = ScopeType.ZONE; private static final ScopeType SCOPE = ScopeType.ZONE;
@Before @Before
public void setup() { public void setup() throws IOException, ClassNotFoundException, SQLException {
STORAGE_POOL_DETAILS.put(DETAIL_KEY, DETAIL_VALUE); STORAGE_POOL_DETAILS.put(DETAIL_KEY, DETAIL_VALUE);
doReturn(Arrays.asList(storagePoolVO)).when(primaryDataStoreDao). doReturn(Arrays.asList(storagePoolVO)).when(primaryDataStoreDao).
searchStoragePoolsPreparedStatement(Matchers.anyString(), Matchers.anyLong(), Matchers.anyLong(), Matchers.anyLong(), searchStoragePoolsPreparedStatement(nullable(String.class), nullable(Long.class), nullable(Long.class), nullable(Long.class),
Matchers.any(ScopeType.class), Matchers.anyInt()); nullable(ScopeType.class), nullable(Integer.class));
} }
@Test @Test

View File

@ -17,6 +17,9 @@
package org.apache.cloudstack.storage.configdrive; package org.apache.cloudstack.storage.configdrive;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import java.io.File; import java.io.File;
@ -53,7 +56,7 @@ public class ConfigDriveBuilderTest {
ConfigDriveBuilder.writeFile(new File("folder"), "subfolder", "content"); ConfigDriveBuilder.writeFile(new File("folder"), "subfolder", "content");
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(FileUtils.class);
FileUtils.write(Mockito.any(File.class), Mockito.anyString(), Mockito.any(Charset.class), Mockito.eq(false)); FileUtils.write(Mockito.any(File.class), Mockito.anyString(), Mockito.any(Charset.class), Mockito.eq(false));
} }
@ -130,8 +133,10 @@ public class ConfigDriveBuilderTest {
public void buildConfigDriveTestIoException() throws Exception { public void buildConfigDriveTestIoException() throws Exception {
PowerMockito.mockStatic(ConfigDriveBuilder.class); PowerMockito.mockStatic(ConfigDriveBuilder.class);
Method method1 = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeFile")).iterator().next();
Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeVendorAndNetworkEmptyJsonFile")).iterator().next(); Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("writeVendorAndNetworkEmptyJsonFile")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.any(File.class)).thenThrow(IOException.class);
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(File.class)).thenThrow(CloudRuntimeException.class);
//This is odd, but it was necessary to allow us to check if we catch the IOexception and re-throw as a CloudRuntimeException //This is odd, but it was necessary to allow us to check if we catch the IOexception and re-throw as a CloudRuntimeException
//We are mocking the class being tested; therefore, we needed to force the execution of the real method we want to test. //We are mocking the class being tested; therefore, we needed to force the execution of the real method we want to test.
@ -165,7 +170,7 @@ public class ConfigDriveBuilderTest {
Assert.assertEquals("mockIsoDataBase64", returnedIsoData); Assert.assertEquals("mockIsoDataBase64", returnedIsoData);
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(ConfigDriveBuilder.class);
ConfigDriveBuilder.writeVendorAndNetworkEmptyJsonFile(Mockito.any(File.class)); ConfigDriveBuilder.writeVendorAndNetworkEmptyJsonFile(Mockito.any(File.class));
ConfigDriveBuilder.writeVmMetadata(Mockito.anyListOf(String[].class), Mockito.anyString(), Mockito.any(File.class)); ConfigDriveBuilder.writeVmMetadata(Mockito.anyListOf(String[].class), Mockito.anyString(), Mockito.any(File.class));
ConfigDriveBuilder.linkUserData(Mockito.anyString()); ConfigDriveBuilder.linkUserData(Mockito.anyString());
@ -211,7 +216,7 @@ public class ConfigDriveBuilderTest {
Mockito.verify(folderFileMock).exists(); Mockito.verify(folderFileMock).exists();
Mockito.verify(folderFileMock).mkdirs(); Mockito.verify(folderFileMock).mkdirs();
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(ConfigDriveBuilder.class);
ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("vendor_data.json"), Mockito.eq("{}")); ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("vendor_data.json"), Mockito.eq("{}"));
ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("network_data.json"), Mockito.eq("{}")); ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("network_data.json"), Mockito.eq("{}"));
} }
@ -228,15 +233,20 @@ public class ConfigDriveBuilderTest {
PowerMockito.mockStatic(ConfigDriveBuilder.class); PowerMockito.mockStatic(ConfigDriveBuilder.class);
Method method = getWriteVmMetadataMethod(); Method method = getWriteVmMetadataMethod();
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(new ArrayList<>(), "metadataFile", new File("folder")).thenCallRealMethod(); PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.anyListOf(String[].class), anyString(), any(File.class)).thenCallRealMethod();
Method createJsonObjectWithVmDataMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("createJsonObjectWithVmData")).iterator().next(); Method createJsonObjectWithVmDataMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("createJsonObjectWithVmData")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, createJsonObjectWithVmDataMethod).withArguments(Mockito.anyListOf(String[].class), Mockito.any(File.class)).thenReturn(new JsonObject());
ConfigDriveBuilder.writeVmMetadata(new ArrayList<>(), "metadataFile", new File("folder")); PowerMockito.when(ConfigDriveBuilder.class, createJsonObjectWithVmDataMethod).withArguments(Mockito.anyListOf(String[].class), Mockito.anyString()).thenReturn(new JsonObject());
PowerMockito.verifyStatic(); List<String[]> vmData = new ArrayList<>();
ConfigDriveBuilder.createJsonObjectWithVmData(Mockito.anyListOf(String[].class), Mockito.anyString()); vmData.add(new String[] {"dataType", "fileName", "content"});
vmData.add(new String[] {"dataType2", "fileName2", "content2"});
ConfigDriveBuilder.writeVmMetadata(vmData, "metadataFile", new File("folder"));
PowerMockito.verifyStatic(ConfigDriveBuilder.class);
ConfigDriveBuilder.createJsonObjectWithVmData(vmData, "metadataFile");
ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("meta_data.json"), Mockito.eq("{}")); ConfigDriveBuilder.writeFile(Mockito.any(File.class), Mockito.eq("meta_data.json"), Mockito.eq("{}"));
} }
@ -306,7 +316,7 @@ public class ConfigDriveBuilderTest {
Mockito.doReturn("scriptMessage").when(scriptMock).execute(); Mockito.doReturn("scriptMessage").when(scriptMock).execute();
Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next(); Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.any(File.class), Mockito.any(File.class), Mockito.any(File.class)).thenCallRealMethod(); PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(String.class), nullable(String.class), nullable(String.class)).thenCallRealMethod();
Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next(); Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage"); PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage");
@ -330,7 +340,7 @@ public class ConfigDriveBuilderTest {
Mockito.doReturn(64L * 1024L * 1024L + 1l).when(fileMock).length(); Mockito.doReturn(64L * 1024L * 1024L + 1l).when(fileMock).length();
Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next(); Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.any(File.class), Mockito.any(File.class), Mockito.any(File.class)).thenCallRealMethod(); PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(String.class), nullable(String.class), nullable(String.class)).thenCallRealMethod();
Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next(); Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage"); PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage");
@ -355,7 +365,7 @@ public class ConfigDriveBuilderTest {
Mockito.doReturn(64L * 1024L * 1024L).when(fileMock).length(); Mockito.doReturn(64L * 1024L * 1024L).when(fileMock).length();
Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next(); Method method = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("generateAndRetrieveIsoAsBase64Iso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(Mockito.any(File.class), Mockito.any(File.class), Mockito.any(File.class)).thenCallRealMethod(); PowerMockito.when(ConfigDriveBuilder.class, method).withArguments(nullable(String.class), nullable(String.class), nullable(String.class)).thenCallRealMethod();
Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next(); Method getProgramToGenerateIsoMethod = ReflectionUtils.getMethods(ConfigDriveBuilder.class, ReflectionUtils.withName("getProgramToGenerateIso")).iterator().next();
PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage"); PowerMockito.when(ConfigDriveBuilder.class, getProgramToGenerateIsoMethod).withNoArguments().thenReturn("/usr/bin/genisoimage");
@ -376,8 +386,8 @@ public class ConfigDriveBuilderTest {
inOrder.verify(scriptMock).add("tempDirName"); inOrder.verify(scriptMock).add("tempDirName");
inOrder.verify(scriptMock).execute(); inOrder.verify(scriptMock).execute();
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(ConfigDriveBuilder.class);
ConfigDriveBuilder.fileToBase64String(Mockito.any(File.class)); ConfigDriveBuilder.fileToBase64String(nullable(File.class));
} }
@ -396,7 +406,7 @@ public class ConfigDriveBuilderTest {
ConfigDriveBuilder.createJsonObjectWithVmData(vmData, "tempDirName"); ConfigDriveBuilder.createJsonObjectWithVmData(vmData, "tempDirName");
PowerMockito.verifyStatic(Mockito.times(1)); PowerMockito.verifyStatic(ConfigDriveBuilder.class, Mockito.times(1));
ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType"), Mockito.eq("fileName"), ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType"), Mockito.eq("fileName"),
Mockito.eq("content")); Mockito.eq("content"));
ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType2"), Mockito.eq("fileName2"), ConfigDriveBuilder.createFileInTempDirAnAppendOpenStackMetadataToJsonObject(Mockito.eq("tempDirName"), Mockito.any(JsonObject.class), Mockito.eq("dataType2"), Mockito.eq("fileName2"),
@ -494,4 +504,4 @@ public class ConfigDriveBuilderTest {
Mockito.verify(mkIsoProgramInMacOsFileMock, Mockito.times(1)).canExecute(); Mockito.verify(mkIsoProgramInMacOsFileMock, Mockito.times(1)).canExecute();
Mockito.verify(mkIsoProgramInMacOsFileMock, Mockito.times(1)).getCanonicalPath(); Mockito.verify(mkIsoProgramInMacOsFileMock, Mockito.times(1)).getCanonicalPath();
} }
} }

View File

@ -19,6 +19,7 @@
package org.apache.cloudstack.storage.motion; package org.apache.cloudstack.storage.motion;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.HashMap; import java.util.HashMap;
@ -270,7 +271,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
sourceTemplate.setId(0l); sourceTemplate.setId(0l);
TemplateObjectTO destTemplate = new TemplateObjectTO(); TemplateObjectTO destTemplate = new TemplateObjectTO();
ImageStoreVO dataStoreVO = Mockito.mock(ImageStoreVO.class); ImageStoreVO dataStoreVO = Mockito.mock(ImageStoreVO.class);
Mockito.when(dataStoreVO.getId()).thenReturn(0l); Mockito.lenient().when(dataStoreVO.getId()).thenReturn(0l);
ImageStoreEntity destDataStore = Mockito.mock(ImageStoreImpl.class); ImageStoreEntity destDataStore = Mockito.mock(ImageStoreImpl.class);
Mockito.doReturn(0l).when(destDataStore).getId(); Mockito.doReturn(0l).when(destDataStore).getId();
@ -299,7 +300,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
@Test @Test
public void copyTemplateToTargetStorageIfNeededTestTemplateAlreadyOnTargetHost() throws AgentUnavailableException, OperationTimedoutException { public void copyTemplateToTargetStorageIfNeededTestTemplateAlreadyOnTargetHost() throws AgentUnavailableException, OperationTimedoutException {
Answer copyCommandAnswer = Mockito.mock(Answer.class); Answer copyCommandAnswer = Mockito.mock(Answer.class);
Mockito.when(copyCommandAnswer.getResult()).thenReturn(true); Mockito.lenient().when(copyCommandAnswer.getResult()).thenReturn(true);
configureAndTestcopyTemplateToTargetStorageIfNeeded(new VMTemplateStoragePoolVO(0l, 0l), StoragePoolType.Filesystem, 0); configureAndTestcopyTemplateToTargetStorageIfNeeded(new VMTemplateStoragePoolVO(0l, 0l), StoragePoolType.Filesystem, 0);
} }
@ -329,14 +330,14 @@ public class KvmNonManagedStorageSystemDataMotionTest {
StoragePool srcStoragePool = Mockito.mock(StoragePool.class); StoragePool srcStoragePool = Mockito.mock(StoragePool.class);
VolumeInfo destVolumeInfo = Mockito.mock(VolumeInfo.class); VolumeInfo destVolumeInfo = Mockito.mock(VolumeInfo.class);
Mockito.when(volumeDataFactory.getVolume(Mockito.anyLong(), Mockito.any(DataStore.class))).thenReturn(destVolumeInfo); Mockito.lenient().when(volumeDataFactory.getVolume(Mockito.anyLong(), Mockito.any(DataStore.class))).thenReturn(destVolumeInfo);
StoragePool destStoragePool = Mockito.mock(StoragePool.class); StoragePool destStoragePool = Mockito.mock(StoragePool.class);
Mockito.when(destStoragePool.getId()).thenReturn(0l); Mockito.when(destStoragePool.getId()).thenReturn(0l);
Mockito.when(destStoragePool.getPoolType()).thenReturn(storagePoolType); Mockito.when(destStoragePool.getPoolType()).thenReturn(storagePoolType);
DataStore sourceTemplateDataStore = Mockito.mock(DataStore.class); DataStore sourceTemplateDataStore = Mockito.mock(DataStore.class);
Mockito.when(sourceTemplateDataStore.getName()).thenReturn("sourceTemplateName"); Mockito.lenient().when(sourceTemplateDataStore.getName()).thenReturn("sourceTemplateName");
TemplateInfo sourceTemplateInfo = Mockito.mock(TemplateInfo.class); TemplateInfo sourceTemplateInfo = Mockito.mock(TemplateInfo.class);
Mockito.when(sourceTemplateInfo.getInstallPath()).thenReturn("installPath"); Mockito.when(sourceTemplateInfo.getInstallPath()).thenReturn("installPath");
@ -357,7 +358,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
Mockito.when(templateDataFactory.getTemplate(Mockito.anyLong(), Mockito.eq(sourceTemplateDataStore))).thenReturn(sourceTemplateInfo); Mockito.when(templateDataFactory.getTemplate(Mockito.anyLong(), Mockito.eq(sourceTemplateDataStore))).thenReturn(sourceTemplateInfo);
Mockito.when(templateDataFactory.getTemplate(Mockito.anyLong(), Mockito.eq(destDataStore))).thenReturn(sourceTemplateInfo); Mockito.when(templateDataFactory.getTemplate(Mockito.anyLong(), Mockito.eq(destDataStore))).thenReturn(sourceTemplateInfo);
kvmNonManagedStorageDataMotionStrategy.copyTemplateToTargetFilesystemStorageIfNeeded(srcVolumeInfo, srcStoragePool, destDataStore, destStoragePool, destHost); kvmNonManagedStorageDataMotionStrategy.copyTemplateToTargetFilesystemStorageIfNeeded(srcVolumeInfo, srcStoragePool, destDataStore, destStoragePool, destHost);
Mockito.doNothing().when(kvmNonManagedStorageDataMotionStrategy).updateTemplateReferenceIfSuccessfulCopy(Mockito.any(VolumeInfo.class), Mockito.any(StoragePool.class), Mockito.lenient().doNothing().when(kvmNonManagedStorageDataMotionStrategy).updateTemplateReferenceIfSuccessfulCopy(Mockito.any(VolumeInfo.class), Mockito.any(StoragePool.class),
Mockito.any(TemplateInfo.class), Mockito.any(DataStore.class)); Mockito.any(TemplateInfo.class), Mockito.any(DataStore.class));
InOrder verifyInOrder = Mockito.inOrder(vmTemplatePoolDao, dataStoreManagerImpl, templateDataFactory, kvmNonManagedStorageDataMotionStrategy); InOrder verifyInOrder = Mockito.inOrder(vmTemplatePoolDao, dataStoreManagerImpl, templateDataFactory, kvmNonManagedStorageDataMotionStrategy);
@ -384,23 +385,23 @@ public class KvmNonManagedStorageSystemDataMotionTest {
when(volumeInfo1.getDataStore()).thenReturn(dataStore1); when(volumeInfo1.getDataStore()).thenReturn(dataStore1);
when(volumeInfo2.getPoolId()).thenReturn(POOL_1_ID); when(volumeInfo2.getPoolId()).thenReturn(POOL_1_ID);
when(volumeInfo2.getDataStore()).thenReturn(dataStore1); lenient().when(volumeInfo2.getDataStore()).thenReturn(dataStore1);
when(dataStore1.getId()).thenReturn(POOL_1_ID); lenient().when(dataStore1.getId()).thenReturn(POOL_1_ID);
when(pool1.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); when(pool1.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
when(pool2.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); when(pool2.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
when(pool2.getScope()).thenReturn(ScopeType.CLUSTER); when(pool2.getScope()).thenReturn(ScopeType.CLUSTER);
when(dataStore3.getId()).thenReturn(POOL_3_ID); lenient().when(dataStore3.getId()).thenReturn(POOL_3_ID);
when(primaryDataStoreDao.findById(POOL_3_ID)).thenReturn(pool3); lenient().when(primaryDataStoreDao.findById(POOL_3_ID)).thenReturn(pool3);
when(pool3.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem); lenient().when(pool3.getPoolType()).thenReturn(Storage.StoragePoolType.NetworkFilesystem);
when(pool3.getScope()).thenReturn(ScopeType.CLUSTER); lenient().when(pool3.getScope()).thenReturn(ScopeType.CLUSTER);
when(host1.getId()).thenReturn(HOST_1_ID); when(host1.getId()).thenReturn(HOST_1_ID);
when(host1.getClusterId()).thenReturn(CLUSTER_ID); when(host1.getClusterId()).thenReturn(CLUSTER_ID);
when(host1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); lenient().when(host1.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM);
when(host2.getId()).thenReturn(HOST_2_ID); when(host2.getId()).thenReturn(HOST_2_ID);
when(host2.getClusterId()).thenReturn(CLUSTER_ID); when(host2.getClusterId()).thenReturn(CLUSTER_ID);
when(host2.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM); lenient().when(host2.getHypervisorType()).thenReturn(Hypervisor.HypervisorType.KVM);
} }
@Test @Test
@ -424,7 +425,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
@Test @Test
public void canHandleKVMLiveStorageMigrationMultipleSources() { public void canHandleKVMLiveStorageMigrationMultipleSources() {
when(volumeInfo1.getDataStore()).thenReturn(dataStore2); lenient().when(volumeInfo1.getDataStore()).thenReturn(dataStore2);
StrategyPriority priority = kvmNonManagedStorageDataMotionStrategy.canHandleKVMNonManagedLiveNFSStorageMigration(migrationMap, host1, host2); StrategyPriority priority = kvmNonManagedStorageDataMotionStrategy.canHandleKVMNonManagedLiveNFSStorageMigration(migrationMap, host1, host2);
assertEquals(StrategyPriority.HYPERVISOR, priority); assertEquals(StrategyPriority.HYPERVISOR, priority);
} }
@ -438,7 +439,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
@Test @Test
public void testCanHandleLiveMigrationUnmanagedStorage() { public void testCanHandleLiveMigrationUnmanagedStorage() {
when(pool2.isManaged()).thenReturn(false); lenient().when(pool2.isManaged()).thenReturn(false);
StrategyPriority priority = kvmNonManagedStorageDataMotionStrategy.canHandleKVMNonManagedLiveNFSStorageMigration(migrationMap, host1, host2); StrategyPriority priority = kvmNonManagedStorageDataMotionStrategy.canHandleKVMNonManagedLiveNFSStorageMigration(migrationMap, host1, host2);
assertEquals(StrategyPriority.HYPERVISOR, priority); assertEquals(StrategyPriority.HYPERVISOR, priority);
} }
@ -463,7 +464,7 @@ public class KvmNonManagedStorageSystemDataMotionTest {
@Test(expected = CloudRuntimeException.class) @Test(expected = CloudRuntimeException.class)
public void testVerifyLiveMigrationMapForKVMMixedManagedUnmagedStorage() { public void testVerifyLiveMigrationMapForKVMMixedManagedUnmagedStorage() {
when(pool1.isManaged()).thenReturn(true); when(pool1.isManaged()).thenReturn(true);
when(pool2.isManaged()).thenReturn(false); lenient().when(pool2.isManaged()).thenReturn(false);
kvmNonManagedStorageDataMotionStrategy.verifyLiveMigrationForKVM(migrationMap, host2); kvmNonManagedStorageDataMotionStrategy.verifyLiveMigrationForKVM(migrationMap, host2);
} }
} }

View File

@ -20,6 +20,7 @@ package org.apache.cloudstack.storage.motion;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.MockitoAnnotations.initMocks; import static org.mockito.MockitoAnnotations.initMocks;
@ -85,9 +86,9 @@ public class StorageSystemDataMotionStrategyTest {
@Test @Test
public void cantHandleSecondary() { public void cantHandleSecondary() {
doReturn(sourceStore).when(volumeObjectSource).getDataStore(); lenient().doReturn(sourceStore).when(volumeObjectSource).getDataStore();
doReturn(DataStoreRole.Primary).when(sourceStore).getRole(); doReturn(DataStoreRole.Primary).when(sourceStore).getRole();
doReturn(destinationStore).when(dataObjectDestination).getDataStore(); lenient().doReturn(destinationStore).when(dataObjectDestination).getDataStore();
doReturn(DataStoreRole.Image).when((DataStore)destinationStore).getRole(); doReturn(DataStoreRole.Image).when((DataStore)destinationStore).getRole();
doReturn(sourceStore).when(volumeObjectSource).getDataStore(); doReturn(sourceStore).when(volumeObjectSource).getDataStore();
doReturn(destinationStore).when(dataObjectDestination).getDataStore(); doReturn(destinationStore).when(dataObjectDestination).getDataStore();
@ -199,7 +200,7 @@ public class StorageSystemDataMotionStrategyTest {
StoragePoolVO destStoragePool = new StoragePoolVO(); StoragePoolVO destStoragePool = new StoragePoolVO();
StoragePoolType[] storagePoolTypes = StoragePoolType.values(); StoragePoolType[] storagePoolTypes = StoragePoolType.values();
for (int i = 0; i < storagePoolTypes.length; i++) { for (int i = 0; i < storagePoolTypes.length; i++) {
Mockito.doReturn(storagePoolTypes[i]).when(sourceStoragePool).getPoolType(); Mockito.lenient().doReturn(storagePoolTypes[i]).when(sourceStoragePool).getPoolType();
boolean result = strategy.shouldMigrateVolume(sourceStoragePool, destHost, destStoragePool); boolean result = strategy.shouldMigrateVolume(sourceStoragePool, destHost, destStoragePool);
Assert.assertTrue(result); Assert.assertTrue(result);
} }
@ -244,7 +245,7 @@ public class StorageSystemDataMotionStrategyTest {
private void configureAndVerifyIsSourceAndDestinationPoolTypeOfNfs(StoragePoolType destStoragePoolType, StoragePoolType sourceStoragePoolType, boolean expected) { private void configureAndVerifyIsSourceAndDestinationPoolTypeOfNfs(StoragePoolType destStoragePoolType, StoragePoolType sourceStoragePoolType, boolean expected) {
VolumeInfo srcVolumeInfo = Mockito.mock(VolumeObject.class); VolumeInfo srcVolumeInfo = Mockito.mock(VolumeObject.class);
Mockito.when(srcVolumeInfo.getId()).thenReturn(0l); Mockito.lenient().when(srcVolumeInfo.getId()).thenReturn(0l);
DataStore destDataStore = Mockito.mock(PrimaryDataStoreImpl.class); DataStore destDataStore = Mockito.mock(PrimaryDataStoreImpl.class);
Mockito.when(destDataStore.getId()).thenReturn(1l); Mockito.when(destDataStore.getId()).thenReturn(1l);

View File

@ -81,7 +81,7 @@ public class CephSnapshotStrategyTest {
VolumeVO volumeVO = Mockito.mock(VolumeVO.class); VolumeVO volumeVO = Mockito.mock(VolumeVO.class);
Mockito.when(volumeVO.getRemoved()).thenReturn(removed); Mockito.when(volumeVO.getRemoved()).thenReturn(removed);
Mockito.when(volumeDao.findByIdIncludingRemoved(Mockito.anyLong())).thenReturn(volumeVO); Mockito.when(volumeDao.findByIdIncludingRemoved(Mockito.anyLong())).thenReturn(volumeVO);
Mockito.doReturn(isSnapshotStoredOnRbdStoragePool).when(cephSnapshotStrategy).isSnapshotStoredOnRbdStoragePool(Mockito.any()); Mockito.lenient().doReturn(isSnapshotStoredOnRbdStoragePool).when(cephSnapshotStrategy).isSnapshotStoredOnRbdStoragePool(Mockito.any());
for (int i = 0; i < snapshotOps.length - 1; i++) { for (int i = 0; i < snapshotOps.length - 1; i++) {
StrategyPriority strategyPriority = cephSnapshotStrategy.canHandle(snapshot, snapshotOps[i]); StrategyPriority strategyPriority = cephSnapshotStrategy.canHandle(snapshot, snapshotOps[i]);
@ -105,7 +105,7 @@ public class CephSnapshotStrategyTest {
VolumeInfo volumeInfo = Mockito.mock(VolumeInfo.class); VolumeInfo volumeInfo = Mockito.mock(VolumeInfo.class);
Mockito.when(snapshotInfo.getBaseVolume()).thenReturn(volumeInfo); Mockito.when(snapshotInfo.getBaseVolume()).thenReturn(volumeInfo);
Mockito.when(volumeInfo.getFormat()).thenReturn(imageFormatValues[i]); Mockito.when(volumeInfo.getFormat()).thenReturn(imageFormatValues[i]);
Mockito.doNothing().when(cephSnapshotStrategy).executeRevertSnapshot(Mockito.any(), Mockito.any()); Mockito.lenient().doNothing().when(cephSnapshotStrategy).executeRevertSnapshot(Mockito.any(), Mockito.any());
boolean revertResult = cephSnapshotStrategy.revertSnapshot(snapshotInfo); boolean revertResult = cephSnapshotStrategy.revertSnapshot(snapshotInfo);

View File

@ -104,7 +104,7 @@ public class SnapshotDataFactoryImplTest {
Assert.assertEquals(dataStoreMock, snapshotInfo.getDataStore()); Assert.assertEquals(dataStoreMock, snapshotInfo.getDataStore());
Assert.assertEquals(snapshotVoMock, ((SnapshotObject)snapshotInfo).getSnapshotVO()); Assert.assertEquals(snapshotVoMock, ((SnapshotObject)snapshotInfo).getSnapshotVO());
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(ComponentContext.class);
ComponentContext.inject(SnapshotObject.class); ComponentContext.inject(SnapshotObject.class);
} }
} }

View File

@ -16,14 +16,15 @@
// under the License. // under the License.
package com.cloud.utils.db; package com.cloud.utils.db;
import com.cloud.utils.exception.CloudRuntimeException;
import org.apache.log4j.Logger;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.log4j.Logger;
import com.cloud.utils.exception.CloudRuntimeException;
public class DriverLoader { public class DriverLoader {
private static final Logger LOGGER = Logger.getLogger(DriverLoader.class.getName()); private static final Logger LOGGER = Logger.getLogger(DriverLoader.class.getName());
@ -32,7 +33,7 @@ public class DriverLoader {
static { static {
DRIVERS = new HashMap<String, String>(); DRIVERS = new HashMap<String, String>();
DRIVERS.put("jdbc:mysql", "com.mysql.jdbc.Driver"); DRIVERS.put("jdbc:mysql", "com.mysql.cj.jdbc.Driver");
DRIVERS.put("jdbc:postgresql", "org.postgresql.Driver"); DRIVERS.put("jdbc:postgresql", "org.postgresql.Driver");
DRIVERS.put("jdbc:h2", "org.h2.Driver"); DRIVERS.put("jdbc:h2", "org.h2.Driver");

View File

@ -22,6 +22,7 @@ import java.lang.reflect.Array;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.math.BigInteger;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -1421,7 +1422,11 @@ public abstract class GenericDaoBase<T, ID extends Serializable> extends Compone
try { try {
if (_idField != null) { if (_idField != null) {
if (id != null) { if (id != null) {
_idField.set(entity, id); if (id instanceof BigInteger) {
_idField.set(entity, ((BigInteger) id).longValue());
} else {
_idField.set(entity, id);
}
} else { } else {
id = (ID)_idField.get(entity); id = (ID)_idField.get(entity);
} }

View File

@ -101,7 +101,7 @@ public class QuotaAlertManagerImplTest extends TestCase {
// Don't test sendQuotaAlert yet // Don't test sendQuotaAlert yet
Mockito.doNothing().when(quotaAlertManager).sendQuotaAlert(Mockito.any(QuotaAlertManagerImpl.DeferredQuotaEmail.class)); Mockito.doNothing().when(quotaAlertManager).sendQuotaAlert(Mockito.any(QuotaAlertManagerImpl.DeferredQuotaEmail.class));
Mockito.doReturn(true).when(quotaAlertManager).lockAccount(Mockito.anyLong()); Mockito.lenient().doReturn(true).when(quotaAlertManager).lockAccount(Mockito.anyLong());
// call real method on send monthly statement // call real method on send monthly statement
Mockito.doCallRealMethod().when(quotaAlertManager).checkAndSendQuotaAlertEmails(); Mockito.doCallRealMethod().when(quotaAlertManager).checkAndSendQuotaAlertEmails();

View File

@ -16,14 +16,18 @@
// under the License. // under the License.
package org.apache.cloudstack.quota; package org.apache.cloudstack.quota;
import com.cloud.usage.UsageVO; import static org.mockito.ArgumentMatchers.nullable;
import com.cloud.usage.dao.UsageDao;
import com.cloud.user.Account; import java.lang.reflect.Field;
import com.cloud.user.AccountVO; import java.math.BigDecimal;
import com.cloud.user.dao.AccountDao; import java.util.ArrayList;
import com.cloud.utils.Pair; import java.util.Date;
import com.cloud.utils.db.TransactionLegacy; import java.util.HashMap;
import junit.framework.TestCase; import java.util.List;
import java.util.Map;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.quota.dao.QuotaAccountDao; import org.apache.cloudstack.quota.dao.QuotaAccountDao;
import org.apache.cloudstack.quota.dao.QuotaBalanceDao; import org.apache.cloudstack.quota.dao.QuotaBalanceDao;
@ -42,14 +46,15 @@ import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import javax.naming.ConfigurationException; import com.cloud.usage.UsageVO;
import java.lang.reflect.Field; import com.cloud.usage.dao.UsageDao;
import java.math.BigDecimal; import com.cloud.user.Account;
import java.util.ArrayList; import com.cloud.user.AccountVO;
import java.util.Date; import com.cloud.user.dao.AccountDao;
import java.util.HashMap; import com.cloud.utils.Pair;
import java.util.List; import com.cloud.utils.db.TransactionLegacy;
import java.util.Map;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class QuotaManagerImplTest extends TestCase { public class QuotaManagerImplTest extends TestCase {
@ -163,7 +168,7 @@ public class QuotaManagerImplTest extends TestCase {
QuotaTariffVO tariffVO = new QuotaTariffVO(); QuotaTariffVO tariffVO = new QuotaTariffVO();
tariffVO.setCurrencyValue(new BigDecimal(1)); tariffVO.setCurrencyValue(new BigDecimal(1));
Mockito.when(quotaTariffDao.findTariffPlanByUsageType(Mockito.anyInt(), Mockito.any(Date.class))).thenReturn(tariffVO); Mockito.when(quotaTariffDao.findTariffPlanByUsageType(nullable(Integer.class), nullable(Date.class))).thenReturn(tariffVO);
QuotaUsageVO qu = quotaManager.updateQuotaNetwork(usageVO, UsageTypes.NETWORK_BYTES_SENT); QuotaUsageVO qu = quotaManager.updateQuotaNetwork(usageVO, UsageTypes.NETWORK_BYTES_SENT);
assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0); assertTrue(qu.getQuotaUsed().compareTo(BigDecimal.ZERO) > 0);

View File

@ -16,10 +16,17 @@
// under the License. // under the License.
package org.apache.cloudstack.quota; package org.apache.cloudstack.quota;
import com.cloud.user.AccountVO; import java.io.UnsupportedEncodingException;
import com.cloud.user.dao.AccountDao; import java.lang.reflect.Field;
import com.cloud.utils.db.TransactionLegacy; import java.math.BigDecimal;
import junit.framework.TestCase; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.mail.MessagingException;
import javax.naming.ConfigurationException;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.quota.QuotaStatementImpl.QuotaStatementPeriods; import org.apache.cloudstack.quota.QuotaStatementImpl.QuotaStatementPeriods;
import org.apache.cloudstack.quota.dao.QuotaAccountDao; import org.apache.cloudstack.quota.dao.QuotaAccountDao;
@ -33,16 +40,11 @@ import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import javax.mail.MessagingException; import com.cloud.user.AccountVO;
import javax.naming.ConfigurationException; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.db.TransactionLegacy;
import java.io.UnsupportedEncodingException; import junit.framework.TestCase;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class QuotaStatementTest extends TestCase { public class QuotaStatementTest extends TestCase {
@ -230,16 +232,16 @@ public class QuotaStatementTest extends TestCase {
AccountVO accountVO = new AccountVO(); AccountVO accountVO = new AccountVO();
accountVO.setId(2L); accountVO.setId(2L);
accountVO.setDomainId(1L); accountVO.setDomainId(1L);
Mockito.when(accountDao.findById(Mockito.anyLong())).thenReturn(accountVO); Mockito.lenient().when(accountDao.findById(Mockito.anyLong())).thenReturn(accountVO);
QuotaAccountVO acc = new QuotaAccountVO(2L); QuotaAccountVO acc = new QuotaAccountVO(2L);
acc.setQuotaBalance(new BigDecimal(404)); acc.setQuotaBalance(new BigDecimal(404));
acc.setLastStatementDate(null); acc.setLastStatementDate(null);
List<QuotaAccountVO> accounts = new ArrayList<>(); List<QuotaAccountVO> accounts = new ArrayList<>();
accounts.add(acc); accounts.add(acc);
Mockito.when(quotaAcc.listAllQuotaAccount()).thenReturn(accounts); Mockito.lenient().when(quotaAcc.listAllQuotaAccount()).thenReturn(accounts);
Mockito.when(quotaUsage.findTotalQuotaUsage(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.any(Date.class), Mockito.any(Date.class))) Mockito.lenient().when(quotaUsage.findTotalQuotaUsage(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyInt(), Mockito.any(Date.class), Mockito.any(Date.class)))
.thenReturn(new BigDecimal(100)); .thenReturn(new BigDecimal(100));
// call real method on send monthly statement // call real method on send monthly statement

View File

@ -55,6 +55,21 @@
<artifactId>jackson-jaxrs-json-provider</artifactId> <artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${cs.jackson.version}</version> <version>${cs.jackson.version}</version>
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId> <artifactId>cxf-rt-frontend-jaxrs</artifactId>

View File

@ -38,7 +38,7 @@ Group: System Environment/Libraries
Source0: %{name}-%{_maventag}.tgz Source0: %{name}-%{_maventag}.tgz
BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build BuildRoot: %{_tmppath}/%{name}-%{_maventag}-%{release}-build
BuildRequires: java-1.8.0-openjdk-devel BuildRequires: java-11-openjdk-devel
BuildRequires: ws-commons-util BuildRequires: ws-commons-util
BuildRequires: jpackage-utils BuildRequires: jpackage-utils
BuildRequires: gcc BuildRequires: gcc
@ -54,7 +54,7 @@ intelligent IaaS cloud implementation.
%package management %package management
Summary: CloudStack management server UI Summary: CloudStack management server UI
Requires: java-1.8.0-openjdk Requires: java-11-openjdk
Requires: python Requires: python
Requires: python3 Requires: python3
Requires: bash Requires: bash
@ -68,7 +68,6 @@ Requires: nfs-utils
Requires: iproute Requires: iproute
Requires: wget Requires: wget
Requires: mysql Requires: mysql
Requires: mysql-connector-java
Requires: sudo Requires: sudo
Requires: /sbin/service Requires: /sbin/service
Requires: /sbin/chkconfig Requires: /sbin/chkconfig
@ -99,7 +98,7 @@ The Apache CloudStack files shared between agent and management server
%package agent %package agent
Summary: CloudStack Agent for KVM hypervisors Summary: CloudStack Agent for KVM hypervisors
Requires: openssh-clients Requires: openssh-clients
Requires: java-1.8.0-openjdk Requires: java-11-openjdk
Requires: %{name}-common = %{_ver} Requires: %{name}-common = %{_ver}
Requires: libvirt Requires: libvirt
Requires: bridge-utils Requires: bridge-utils
@ -132,8 +131,7 @@ The CloudStack baremetal agent
%package usage %package usage
Summary: CloudStack Usage calculation server Summary: CloudStack Usage calculation server
Requires: java-1.8.0-openjdk Requires: java-11-openjdk
Requires: mysql-connector-java
Group: System Environment/Libraries Group: System Environment/Libraries
%description usage %description usage
The CloudStack usage calculation service The CloudStack usage calculation service
@ -166,7 +164,6 @@ Apache CloudStack Marvin integration tests
%if "%{_ossnoss}" == "noredist" %if "%{_ossnoss}" == "noredist"
%package mysql-ha %package mysql-ha
Summary: Apache CloudStack Balancing Strategy for MySQL Summary: Apache CloudStack Balancing Strategy for MySQL
Requires: mysql-connector-java
Group: System Environmnet/Libraries Group: System Environmnet/Libraries
%description mysql-ha %description mysql-ha
Apache CloudStack Balancing Strategy for MySQL Apache CloudStack Balancing Strategy for MySQL
@ -271,7 +268,7 @@ done
ln -sf log4j-cloud.xml ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/log4j.xml ln -sf log4j-cloud.xml ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/management/log4j.xml
install python/bindir/cloud-external-ipallocator.py ${RPM_BUILD_ROOT}%{_bindir}/%{name}-external-ipallocator.py install python/bindir/cloud-external-ipallocator.py ${RPM_BUILD_ROOT}%{_bindir}/%{name}-external-ipallocator.py
install -D client/target/pythonlibs/jasypt-1.9.2.jar ${RPM_BUILD_ROOT}%{_datadir}/%{name}-common/lib/jasypt-1.9.2.jar install -D client/target/pythonlibs/jasypt-1.9.3.jar ${RPM_BUILD_ROOT}%{_datadir}/%{name}-common/lib/jasypt-1.9.3.jar
install -D packaging/centos7/cloud-ipallocator.rc ${RPM_BUILD_ROOT}%{_initrddir}/%{name}-ipallocator install -D packaging/centos7/cloud-ipallocator.rc ${RPM_BUILD_ROOT}%{_initrddir}/%{name}-ipallocator
install -D packaging/centos7/cloud.limits ${RPM_BUILD_ROOT}%{_sysconfdir}/security/limits.d/cloud install -D packaging/centos7/cloud.limits ${RPM_BUILD_ROOT}%{_sysconfdir}/security/limits.d/cloud
@ -316,6 +313,7 @@ install -D usage/target/cloud-usage-%{_maventag}.jar ${RPM_BUILD_ROOT}%{_datadir
install -D usage/target/transformed/db.properties ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/usage/db.properties install -D usage/target/transformed/db.properties ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/usage/db.properties
install -D usage/target/transformed/log4j-cloud_usage.xml ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/usage/log4j-cloud.xml install -D usage/target/transformed/log4j-cloud_usage.xml ${RPM_BUILD_ROOT}%{_sysconfdir}/%{name}/usage/log4j-cloud.xml
cp usage/target/dependencies/* ${RPM_BUILD_ROOT}%{_datadir}/%{name}-usage/lib/ cp usage/target/dependencies/* ${RPM_BUILD_ROOT}%{_datadir}/%{name}-usage/lib/
cp client/target/lib/mysql*jar ${RPM_BUILD_ROOT}%{_datadir}/%{name}-usage/lib/
install -D packaging/systemd/cloudstack-usage.service ${RPM_BUILD_ROOT}%{_unitdir}/%{name}-usage.service install -D packaging/systemd/cloudstack-usage.service ${RPM_BUILD_ROOT}%{_unitdir}/%{name}-usage.service
install -D packaging/systemd/cloudstack-usage.default ${RPM_BUILD_ROOT}%{_sysconfdir}/default/%{name}-usage install -D packaging/systemd/cloudstack-usage.default ${RPM_BUILD_ROOT}%{_sysconfdir}/default/%{name}-usage
mkdir -p ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/usage/ mkdir -p ${RPM_BUILD_ROOT}%{_localstatedir}/log/%{name}/usage/
@ -542,7 +540,7 @@ pip install --upgrade /usr/share/cloudstack-marvin/Marvin-*.tar.gz
%attr(0644,root,root) %{python_sitearch}/cloud_utils.py %attr(0644,root,root) %{python_sitearch}/cloud_utils.py
%attr(0644,root,root) %{python_sitearch}/cloud_utils.pyc %attr(0644,root,root) %{python_sitearch}/cloud_utils.pyc
%attr(0644,root,root) %{python_sitearch}/cloudutils/* %attr(0644,root,root) %{python_sitearch}/cloudutils/*
%attr(0644, root, root) %{_datadir}/%{name}-common/lib/jasypt-1.9.2.jar %attr(0644, root, root) %{_datadir}/%{name}-common/lib/jasypt-1.9.3.jar
%{_defaultdocdir}/%{name}-common-%{version}/LICENSE %{_defaultdocdir}/%{name}-common-%{version}/LICENSE
%{_defaultdocdir}/%{name}-common-%{version}/NOTICE %{_defaultdocdir}/%{name}-common-%{version}/NOTICE

View File

@ -28,12 +28,11 @@ import java.security.NoSuchAlgorithmException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import com.google.gson.Gson;
import org.apache.cloudstack.api.response.SuccessResponse; import org.apache.cloudstack.api.response.SuccessResponse;
import com.cloud.api.ApiGsonHelper; import com.cloud.api.ApiGsonHelper;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.google.gson.Gson;
/** /**
* Base class for API Test * Base class for API Test

View File

@ -33,6 +33,12 @@
<artifactId>cloud-plugin-hypervisor-vmware</artifactId> <artifactId>cloud-plugin-hypervisor-vmware</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-ri</artifactId>
<version>${cs.jaxws.version}</version>
<type>pom</type>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

View File

@ -41,7 +41,7 @@ import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class RootCAProviderTest { public class RootCAProviderTest {
@ -135,7 +135,7 @@ public class RootCAProviderTest {
public void testCreateSSLEngineWithoutAuthStrictness() throws Exception { public void testCreateSSLEngineWithoutAuthStrictness() throws Exception {
overrideDefaultConfigValue(RootCAProvider.rootCAAuthStrictness, "_defaultValue", "false"); overrideDefaultConfigValue(RootCAProvider.rootCAAuthStrictness, "_defaultValue", "false");
final SSLEngine e = provider.createSSLEngine(SSLUtils.getSSLContext(), "/1.2.3.4:5678", null); final SSLEngine e = provider.createSSLEngine(SSLUtils.getSSLContext(), "/1.2.3.4:5678", null);
Assert.assertFalse(e.getUseClientMode()); Assert.assertTrue(e.getUseClientMode());
Assert.assertFalse(e.getNeedClientAuth()); Assert.assertFalse(e.getNeedClientAuth());
} }
@ -143,7 +143,7 @@ public class RootCAProviderTest {
public void testCreateSSLEngineWithAuthStrictness() throws Exception { public void testCreateSSLEngineWithAuthStrictness() throws Exception {
overrideDefaultConfigValue(RootCAProvider.rootCAAuthStrictness, "_defaultValue", "true"); overrideDefaultConfigValue(RootCAProvider.rootCAAuthStrictness, "_defaultValue", "true");
final SSLEngine e = provider.createSSLEngine(SSLUtils.getSSLContext(), "/1.2.3.4:5678", null); final SSLEngine e = provider.createSSLEngine(SSLUtils.getSSLContext(), "/1.2.3.4:5678", null);
Assert.assertFalse(e.getUseClientMode()); Assert.assertTrue(e.getUseClientMode());
Assert.assertTrue(e.getNeedClientAuth()); Assert.assertTrue(e.getNeedClientAuth());
} }

View File

@ -16,20 +16,20 @@
// under the License. // under the License.
package com.cloud.utils.db; package com.cloud.utils.db;
import java.lang.reflect.InvocationHandler;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import com.mysql.jdbc.BalanceStrategy; import com.mysql.cj.jdbc.ConnectionImpl;
import com.mysql.jdbc.Connection; import com.mysql.cj.jdbc.JdbcConnection;
import com.mysql.jdbc.ConnectionImpl; import com.mysql.cj.jdbc.exceptions.SQLError;
import com.mysql.jdbc.LoadBalancingConnectionProxy; import com.mysql.cj.jdbc.ha.BalanceStrategy;
import com.mysql.jdbc.SQLError; import com.mysql.cj.jdbc.ha.LoadBalancedConnectionProxy;
public class StaticStrategy implements BalanceStrategy { public class StaticStrategy implements BalanceStrategy {
private static final Logger s_logger = Logger.getLogger(StaticStrategy.class); private static final Logger s_logger = Logger.getLogger(StaticStrategy.class);
@ -38,18 +38,8 @@ public class StaticStrategy implements BalanceStrategy {
} }
@Override @Override
public void destroy() { public JdbcConnection pickConnection(InvocationHandler proxy, List<String> configuredHosts, Map<String, JdbcConnection> liveConnections,
// we don't have anything to clean up long[] responseTimes, int numRetries) throws SQLException {
}
@Override
public void init(Connection conn, Properties props) throws SQLException {
// we don't have anything to initialize
}
@Override
public ConnectionImpl pickConnection(LoadBalancingConnectionProxy proxy, List<String> configuredHosts, Map<String, ConnectionImpl> liveConnections,
long[] responseTimes, int numRetries) throws SQLException {
int numHosts = configuredHosts.size(); int numHosts = configuredHosts.size();
SQLException ex = null; SQLException ex = null;
@ -57,7 +47,7 @@ public class StaticStrategy implements BalanceStrategy {
List<String> whiteList = new ArrayList<String>(numHosts); List<String> whiteList = new ArrayList<String>(numHosts);
whiteList.addAll(configuredHosts); whiteList.addAll(configuredHosts);
Map<String, Long> blackList = proxy.getGlobalBlacklist(); Map<String, Long> blackList = ((LoadBalancedConnectionProxy) proxy).getGlobalBlacklist();
whiteList.removeAll(blackList.keySet()); whiteList.removeAll(blackList.keySet());
@ -70,15 +60,15 @@ public class StaticStrategy implements BalanceStrategy {
String hostPortSpec = whiteList.get(0); //Always take the first host String hostPortSpec = whiteList.get(0); //Always take the first host
ConnectionImpl conn = liveConnections.get(hostPortSpec); ConnectionImpl conn = (ConnectionImpl) liveConnections.get(hostPortSpec);
if (conn == null) { if (conn == null) {
try { try {
conn = proxy.createConnectionForHost(hostPortSpec); conn = ((LoadBalancedConnectionProxy) proxy).createConnectionForHost(hostPortSpec);
} catch (SQLException sqlEx) { } catch (SQLException sqlEx) {
ex = sqlEx; ex = sqlEx;
if (proxy.shouldExceptionTriggerFailover(sqlEx)) { if (((LoadBalancedConnectionProxy) proxy).shouldExceptionTriggerFailover(sqlEx)) {
Integer whiteListIndex = whiteListMap.get(hostPortSpec); Integer whiteListIndex = whiteListMap.get(hostPortSpec);
@ -87,7 +77,7 @@ public class StaticStrategy implements BalanceStrategy {
whiteList.remove(whiteListIndex.intValue()); whiteList.remove(whiteListIndex.intValue());
whiteListMap = this.getArrayIndexMap(whiteList); whiteListMap = this.getArrayIndexMap(whiteList);
} }
proxy.addToGlobalBlacklist(hostPortSpec); ((LoadBalancedConnectionProxy) proxy).addToGlobalBlacklist(hostPortSpec);
if (whiteList.size() == 0) { if (whiteList.size() == 0) {
attempts++; attempts++;
@ -100,7 +90,7 @@ public class StaticStrategy implements BalanceStrategy {
// start fresh // start fresh
whiteListMap = new HashMap<String, Integer>(numHosts); whiteListMap = new HashMap<String, Integer>(numHosts);
whiteList.addAll(configuredHosts); whiteList.addAll(configuredHosts);
blackList = proxy.getGlobalBlacklist(); blackList = ((LoadBalancedConnectionProxy) proxy).getGlobalBlacklist();
whiteList.removeAll(blackList.keySet()); whiteList.removeAll(blackList.keySet());
whiteListMap = this.getArrayIndexMap(whiteList); whiteListMap = this.getArrayIndexMap(whiteList);
@ -126,10 +116,9 @@ public class StaticStrategy implements BalanceStrategy {
private Map<String, Integer> getArrayIndexMap(List<String> l) { private Map<String, Integer> getArrayIndexMap(List<String> l) {
Map<String, Integer> m = new HashMap<String, Integer>(l.size()); Map<String, Integer> m = new HashMap<String, Integer>(l.size());
for (int i = 0; i < l.size(); i++) { for (int i = 0; i < l.size(); i++) {
m.put(l.get(i), Integer.valueOf(i)); m.put(l.get(i), i);
} }
return m; return m;
} }
} }

View File

@ -16,7 +16,11 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command; package org.apache.cloudstack.api.command;
import junit.framework.TestCase; import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.cloudstack.api.response.QuotaBalanceResponse; import org.apache.cloudstack.api.response.QuotaBalanceResponse;
import org.apache.cloudstack.api.response.QuotaResponseBuilder; import org.apache.cloudstack.api.response.QuotaResponseBuilder;
import org.apache.cloudstack.quota.vo.QuotaBalanceVO; import org.apache.cloudstack.quota.vo.QuotaBalanceVO;
@ -26,10 +30,7 @@ import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import java.lang.reflect.Field; import junit.framework.TestCase;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class QuotaBalanceCmdTest extends TestCase { public class QuotaBalanceCmdTest extends TestCase {
@ -48,7 +49,7 @@ public class QuotaBalanceCmdTest extends TestCase {
Mockito.when(responseBuilder.getQuotaBalance(Mockito.any(cmd.getClass()))).thenReturn(quotaBalanceVOList); Mockito.when(responseBuilder.getQuotaBalance(Mockito.any(cmd.getClass()))).thenReturn(quotaBalanceVOList);
Mockito.when(responseBuilder.createQuotaLastBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse()); Mockito.when(responseBuilder.createQuotaLastBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse());
Mockito.when(responseBuilder.createQuotaBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse()); Mockito.when(responseBuilder.createQuotaBalanceResponse(Mockito.eq(quotaBalanceVOList), Mockito.any(Date.class), Mockito.any(Date.class))).thenReturn(new QuotaBalanceResponse());
Mockito.when(responseBuilder.startOfNextDay(Mockito.any(Date.class))).thenReturn(new Date()); Mockito.lenient().when(responseBuilder.startOfNextDay(Mockito.any(Date.class))).thenReturn(new Date());
// end date not specified // end date not specified
cmd.setStartDate(new Date()); cmd.setStartDate(new Date());

View File

@ -16,10 +16,12 @@
// under the License. // under the License.
package org.apache.cloudstack.api.command; package org.apache.cloudstack.api.command;
import com.cloud.user.AccountService; import static org.mockito.ArgumentMatchers.anyBoolean;
import com.cloud.user.AccountVO; import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.nullable;
import junit.framework.TestCase; import java.lang.reflect.Field;
import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd; import org.apache.cloudstack.api.BaseCmd;
@ -27,13 +29,17 @@ import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.QuotaCreditsResponse; import org.apache.cloudstack.api.response.QuotaCreditsResponse;
import org.apache.cloudstack.api.response.QuotaResponseBuilder; import org.apache.cloudstack.api.response.QuotaResponseBuilder;
import org.apache.cloudstack.quota.QuotaService; import org.apache.cloudstack.quota.QuotaService;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field; import com.cloud.user.AccountService;
import com.cloud.user.AccountVO;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class QuotaCreditsCmdTest extends TestCase { public class QuotaCreditsCmdTest extends TestCase {
@ -44,9 +50,16 @@ public class QuotaCreditsCmdTest extends TestCase {
@Mock @Mock
AccountService accountService; AccountService accountService;
private QuotaCreditsCmd cmd;
@Override
@Before
public void setUp() {
cmd = new QuotaCreditsCmd();
}
@Test @Test
public void testQuotaCreditsCmd() throws NoSuchFieldException, IllegalAccessException { public void testQuotaCreditsCmd() throws NoSuchFieldException, IllegalAccessException {
QuotaCreditsCmd cmd = new QuotaCreditsCmd();
cmd.setAccountName("admin"); cmd.setAccountName("admin");
cmd.setMinBalance(200.0); cmd.setMinBalance(200.0);
@ -64,8 +77,10 @@ public class QuotaCreditsCmdTest extends TestCase {
AccountVO acc = new AccountVO(); AccountVO acc = new AccountVO();
acc.setId(2L); acc.setId(2L);
Mockito.when(accountService.getActiveAccountByName(Mockito.anyString(), Mockito.anyLong())).thenReturn(acc);
Mockito.when(responseBuilder.addQuotaCredits(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyDouble(), Mockito.anyLong(), Mockito.anyBoolean())).thenReturn(new QuotaCreditsResponse()); Mockito.when(accountService.getActiveAccountByName(nullable(String.class), nullable(Long.class))).thenReturn(acc);
Mockito.when(responseBuilder.addQuotaCredits(nullable(Long.class), nullable(Long.class), nullable(Double.class), nullable(Long.class), nullable(Boolean.class))).thenReturn(new QuotaCreditsResponse());
// No value provided test // No value provided test
try { try {
@ -77,11 +92,9 @@ public class QuotaCreditsCmdTest extends TestCase {
// With value provided test // With value provided test
cmd.setValue(11.80); cmd.setValue(11.80);
cmd.execute(); cmd.execute();
Mockito.verify(quotaService, Mockito.times(0)).setLockAccount(Mockito.anyLong(), Mockito.anyBoolean()); Mockito.verify(quotaService, Mockito.times(0)).setLockAccount(anyLong(), anyBoolean());
Mockito.verify(quotaService, Mockito.times(1)).setMinBalance(Mockito.anyLong(), Mockito.anyDouble()); Mockito.verify(quotaService, Mockito.times(1)).setMinBalance(anyLong(), anyDouble());
Mockito.verify(responseBuilder, Mockito.times(1)).addQuotaCredits(Mockito.anyLong(), Mockito.anyLong(), Mockito.anyDouble(), Mockito.anyLong(), Mockito.anyBoolean()); Mockito.verify(responseBuilder, Mockito.times(1)).addQuotaCredits(nullable(Long.class), nullable(Long.class), nullable(Double.class), nullable(Long.class), nullable(Boolean.class));
} }
} }

View File

@ -217,7 +217,7 @@ public class QuotaResponseBuilderImplTest extends TestCase {
entry.setCreditBalance(new BigDecimal(100)); entry.setCreditBalance(new BigDecimal(100));
quotaBalance.add(entry); quotaBalance.add(entry);
quotaBalance.add(entry); quotaBalance.add(entry);
Mockito.when(quotaService.computeAdjustedTime(Mockito.any(Date.class))).thenReturn(new Date()); Mockito.lenient().when(quotaService.computeAdjustedTime(Mockito.any(Date.class))).thenReturn(new Date());
QuotaBalanceResponse resp = quotaResponseBuilder.createQuotaLastBalanceResponse(quotaBalance, null); QuotaBalanceResponse resp = quotaResponseBuilder.createQuotaLastBalanceResponse(quotaBalance, null);
assertTrue(resp.getStartQuota().compareTo(new BigDecimal(200)) == 0); assertTrue(resp.getStartQuota().compareTo(new BigDecimal(200)) == 0);
} }

View File

@ -16,9 +16,9 @@
// under the License. // under the License.
package org.apache.cloudstack.dedicated.manager; package org.apache.cloudstack.dedicated.manager;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
@ -26,10 +26,11 @@ import java.util.UUID;
import javax.inject.Inject; import javax.inject.Inject;
import com.cloud.user.User; import org.apache.cloudstack.affinity.AffinityGroupService;
import junit.framework.Assert; import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.dedicated.DedicatedResourceManagerImpl; import org.apache.cloudstack.dedicated.DedicatedResourceManagerImpl;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.test.utils.SpringUtils; import org.apache.cloudstack.test.utils.SpringUtils;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.junit.After; import org.junit.After;
@ -49,11 +50,6 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader; import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.apache.cloudstack.affinity.AffinityGroupService;
import org.apache.cloudstack.affinity.dao.AffinityGroupDao;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import com.cloud.dc.DedicatedResourceVO; import com.cloud.dc.DedicatedResourceVO;
import com.cloud.dc.dao.ClusterDao; import com.cloud.dc.dao.ClusterDao;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
@ -66,12 +62,15 @@ import com.cloud.host.dao.HostDao;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.user.AccountManager; import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO; import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.user.dao.AccountDao; import com.cloud.user.dao.AccountDao;
import com.cloud.utils.component.ComponentContext; import com.cloud.utils.component.ComponentContext;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
import junit.framework.Assert;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class) @ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class DedicatedApiUnitTest { public class DedicatedApiUnitTest {
@ -122,7 +121,7 @@ public class DedicatedApiUnitTest {
UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN); UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
CallContext.register(user, account); CallContext.register(user, account);
when(_acctMgr.finalizeOwner((Account)anyObject(), anyString(), anyLong(), anyLong())).thenReturn(account); when(_acctMgr.finalizeOwner(any(Account.class), nullable(String.class), nullable(Long.class), nullable(Long.class))).thenReturn(account);
when(_accountDao.findByIdIncludingRemoved(0L)).thenReturn(account); when(_accountDao.findByIdIncludingRemoved(0L)).thenReturn(account);
when(_accountDao.findById(anyLong())).thenReturn(account); when(_accountDao.findById(anyLong())).thenReturn(account);
when(_domainDao.findById(domainId)).thenReturn(domain); when(_domainDao.findById(domainId)).thenReturn(domain);

View File

@ -32,5 +32,20 @@
<groupId>commons-lang</groupId> <groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId> <artifactId>commons-lang</artifactId>
</dependency> </dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>${cs.jaxb.version}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -2967,7 +2967,7 @@ public class LibvirtComputingResource extends ServerResourceBase implements Serv
return vmStates; return vmStates;
} }
public String rebootVM(final Connect conn, final String vmName) { public String rebootVM(final Connect conn, final String vmName) throws LibvirtException{
Domain dm = null; Domain dm = null;
String msg = null; String msg = null;
try { try {

View File

@ -19,6 +19,19 @@
package com.cloud.hypervisor.kvm.resource; package com.cloud.hypervisor.kvm.resource;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
@ -41,9 +54,11 @@ import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory; import javax.xml.xpath.XPathFactory;
import com.cloud.agent.api.Command; import org.apache.cloudstack.storage.command.AttachAnswer;
import com.cloud.agent.api.UnsupportedAnswer; import org.apache.cloudstack.storage.command.AttachCommand;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef; import org.apache.cloudstack.utils.linux.CPUStat;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import org.apache.commons.lang.SystemUtils; import org.apache.commons.lang.SystemUtils;
import org.joda.time.Duration; import org.joda.time.Duration;
import org.junit.Assert; import org.junit.Assert;
@ -61,22 +76,17 @@ import org.libvirt.MemoryStatistic;
import org.libvirt.NodeInfo; import org.libvirt.NodeInfo;
import org.libvirt.StorageVol; import org.libvirt.StorageVol;
import org.libvirt.jna.virDomainMemoryStats; import org.libvirt.jna.virDomainMemoryStats;
import org.mockito.Matchers; import org.mockito.BDDMockito;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.apache.cloudstack.storage.command.AttachAnswer;
import org.apache.cloudstack.storage.command.AttachCommand;
import org.apache.cloudstack.utils.linux.CPUStat;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.cloudstack.utils.qemu.QemuImg.PhysicalDiskFormat;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachIsoCommand;
import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.BackupSnapshotCommand;
@ -87,6 +97,7 @@ import com.cloud.agent.api.CheckRouterAnswer;
import com.cloud.agent.api.CheckRouterCommand; import com.cloud.agent.api.CheckRouterCommand;
import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.CheckVirtualMachineCommand;
import com.cloud.agent.api.CleanupNetworkRulesCmd; import com.cloud.agent.api.CleanupNetworkRulesCmd;
import com.cloud.agent.api.Command;
import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand;
import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand;
import com.cloud.agent.api.CreateStoragePoolCommand; import com.cloud.agent.api.CreateStoragePoolCommand;
@ -129,6 +140,7 @@ import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StopCommand;
import com.cloud.agent.api.UnPlugNicCommand; import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.UnsupportedAnswer;
import com.cloud.agent.api.UpdateHostPasswordCommand; import com.cloud.agent.api.UpdateHostPasswordCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.VmStatsEntry;
@ -150,6 +162,7 @@ import com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource;
import com.cloud.exception.InternalErrorException; import com.cloud.exception.InternalErrorException;
import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool; import com.cloud.hypervisor.kvm.resource.KVMHABase.NfsStoragePool;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.ChannelDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.CpuTuneDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.InterfaceDef;
import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper; import com.cloud.hypervisor.kvm.resource.wrapper.LibvirtRequestWrapper;
@ -177,20 +190,9 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VirtualMachine.Type; import com.cloud.vm.VirtualMachine.Type;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class}) @PrepareForTest(value = {MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*"})
public class LibvirtComputingResourceTest { public class LibvirtComputingResourceTest {
@Mock @Mock
@ -492,7 +494,8 @@ public class LibvirtComputingResourceTest {
nodeInfo.model = "Foo processor"; nodeInfo.model = "Foo processor";
Mockito.when(connect.nodeInfo()).thenReturn(nodeInfo); Mockito.when(connect.nodeInfo()).thenReturn(nodeInfo);
// this is testing the interface stats, returns an increasing number of sent and received bytes // this is testing the interface stats, returns an increasing number of sent and received bytes
Mockito.when(domain.interfaceStats(Matchers.anyString())).thenAnswer(new org.mockito.stubbing.Answer<DomainInterfaceStats>() {
Mockito.when(domain.interfaceStats(nullable(String.class))).thenAnswer(new org.mockito.stubbing.Answer<DomainInterfaceStats>() {
// increment with less than a KB, so this should be less than 1 KB // increment with less than a KB, so this should be less than 1 KB
final static int increment = 1000; final static int increment = 1000;
int rxBytes = 1000; int rxBytes = 1000;
@ -509,7 +512,8 @@ public class LibvirtComputingResourceTest {
}); });
Mockito.when(domain.blockStats(Matchers.anyString())).thenAnswer(new org.mockito.stubbing.Answer<DomainBlockStats>() {
Mockito.when(domain.blockStats(nullable(String.class))).thenAnswer(new org.mockito.stubbing.Answer<DomainBlockStats>() {
// a little less than a KB // a little less than a KB
final static int increment = 1000; final static int increment = 1000;
@ -1000,7 +1004,7 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResource.getCPUStat()).thenReturn(cpuStat); when(libvirtComputingResource.getCPUStat()).thenReturn(cpuStat);
when(libvirtComputingResource.getMemStat()).thenReturn(memStat); when(libvirtComputingResource.getMemStat()).thenReturn(memStat);
when(libvirtComputingResource.getNicStats(Mockito.anyString())).thenReturn(new Pair<Double, Double>(1.0d, 1.0d)); when(libvirtComputingResource.getNicStats(nullable(String.class))).thenReturn(new Pair<Double, Double>(1.0d, 1.0d));
when(cpuStat.getCpuUsedPercent()).thenReturn(0.5d); when(cpuStat.getCpuUsedPercent()).thenReturn(0.5d);
when(memStat.getAvailable()).thenReturn(1500L); when(memStat.getAvailable()).thenReturn(1500L);
when(memStat.getTotal()).thenReturn(15000L); when(memStat.getTotal()).thenReturn(15000L);
@ -1247,7 +1251,7 @@ public class LibvirtComputingResourceTest {
when(vm.getNics()).thenReturn(new NicTO[]{nicTO}); when(vm.getNics()).thenReturn(new NicTO[]{nicTO});
when(nicTO.getType()).thenReturn(TrafficType.Guest); when(nicTO.getType()).thenReturn(TrafficType.Guest);
when(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).thenThrow(InternalErrorException.class); BDDMockito.given(libvirtComputingResource.getVifDriver(nicTO.getType(), nicTO.getName())).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");});
when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager); when(libvirtComputingResource.getStoragePoolMgr()).thenReturn(storagePoolManager);
try { try {
when(libvirtComputingResource.getVolumePath(conn, volume)).thenReturn("/path"); when(libvirtComputingResource.getVolumePath(conn, volume)).thenReturn("/path");
@ -1535,7 +1539,7 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try { try {
when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(URISyntaxException.class); BDDMockito.given(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).willAnswer(invocationOnMock -> {throw new URISyntaxException("Exception trying to get connection by VM name", vmName);});
} catch (final LibvirtException e) { } catch (final LibvirtException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
@ -1564,7 +1568,7 @@ public class LibvirtComputingResourceTest {
when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper); when(libvirtComputingResource.getLibvirtUtilitiesHelper()).thenReturn(libvirtUtilitiesHelper);
try { try {
when(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).thenThrow(InternalErrorException.class); BDDMockito.given(libvirtUtilitiesHelper.getConnectionByVmName(vmName)).willAnswer(invocationOnMock -> {throw new InternalErrorException("Exception Occurred");});
} catch (final LibvirtException e) { } catch (final LibvirtException e) {
fail(e.getMessage()); fail(e.getMessage());
} }
@ -2252,7 +2256,7 @@ public class LibvirtComputingResourceTest {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test(expected = Exception.class)
public void testOvsVpcPhysicalTopologyConfigCommandFailure() { public void testOvsVpcPhysicalTopologyConfigCommandFailure() {
final Host[] hosts = null; final Host[] hosts = null;
final Tier[] tiers = null; final Tier[] tiers = null;
@ -2296,7 +2300,7 @@ public class LibvirtComputingResourceTest {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test(expected = Exception.class)
public void testOvsVpcRoutingPolicyConfigCommandFailure() { public void testOvsVpcRoutingPolicyConfigCommandFailure() {
final String id = null; final String id = null;
final String cidr = null; final String cidr = null;
@ -2702,7 +2706,7 @@ public class LibvirtComputingResourceTest {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test(expected = Exception.class)
public void testOvsDestroyTunnelCommandFailure2() { public void testOvsDestroyTunnelCommandFailure2() {
final String networkName = "Test"; final String networkName = "Test";
final Long networkId = 1l; final Long networkId = 1l;
@ -2802,7 +2806,7 @@ public class LibvirtComputingResourceTest {
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test(expected = Exception.class)
public void testOvsCreateTunnelCommandFailure2() { public void testOvsCreateTunnelCommandFailure2() {
final String remoteIp = "127.0.0.1"; final String remoteIp = "127.0.0.1";
final Integer key = 1; final Integer key = 1;

View File

@ -22,22 +22,25 @@ import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Scanner;
import org.apache.cloudstack.utils.linux.MemStat;
import java.util.Map; import java.util.Map;
import org.apache.commons.io.IOUtils; import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.cloudstack.utils.linux.MemStat;
import org.apache.commons.io.IOUtils;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
import com.cloud.agent.api.to.DpdkTO;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.libvirt.Connect; import org.libvirt.Connect;
@ -45,8 +48,10 @@ import org.libvirt.StorageVol;
import org.mockito.InOrder; import org.mockito.InOrder;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import org.w3c.dom.Document;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.MigrateCommand;
@ -54,19 +59,15 @@ import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo;
import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DiskType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DiskType;
import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DriverType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DriverType;
import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.Source; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.Source;
import com.cloud.agent.api.to.DpdkTO;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.hypervisor.kvm.resource.LibvirtConnection; import com.cloud.hypervisor.kvm.resource.LibvirtConnection;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(value = {LibvirtConnection.class, LibvirtMigrateCommandWrapper.class, MemStat.class}) @PrepareForTest(value = {LibvirtConnection.class, LibvirtMigrateCommandWrapper.class, MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
public class LibvirtMigrateCommandWrapperTest { public class LibvirtMigrateCommandWrapperTest {
String fullfile = String fullfile =
"<domain type='kvm' id='4'>\n" + "<domain type='kvm' id='4'>\n" +
@ -648,7 +649,7 @@ public class LibvirtMigrateCommandWrapperTest {
libvirtMigrateCmdWrapper.deleteLocalVolume("localPath"); libvirtMigrateCmdWrapper.deleteLocalVolume("localPath");
PowerMockito.verifyStatic(Mockito.times(1)); PowerMockito.verifyStatic(LibvirtConnection.class, Mockito.times(1));
LibvirtConnection.getConnection(); LibvirtConnection.getConnection();
InOrder inOrder = Mockito.inOrder(conn, storageVolLookupByPath); InOrder inOrder = Mockito.inOrder(conn, storageVolLookupByPath);
inOrder.verify(conn, Mockito.times(1)).storageVolLookupByPath("localPath"); inOrder.verify(conn, Mockito.times(1)).storageVolLookupByPath("localPath");

View File

@ -19,12 +19,14 @@
package com.cloud.hypervisor.kvm.resource.wrapper; package com.cloud.hypervisor.kvm.resource.wrapper;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString; import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.Scanner;
import org.apache.cloudstack.utils.linux.MemStat; import org.apache.cloudstack.utils.linux.MemStat;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -32,6 +34,10 @@ import org.junit.runner.RunWith;
import org.libvirt.Connect; import org.libvirt.Connect;
import org.libvirt.Domain; import org.libvirt.Domain;
import org.libvirt.LibvirtException; import org.libvirt.LibvirtException;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand;
import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.NetworkElementCommand;
@ -39,14 +45,10 @@ import com.cloud.agent.api.to.IpAddressTO;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.network.Networks; import com.cloud.network.Networks;
import com.cloud.utils.ExecutionResult; import com.cloud.utils.ExecutionResult;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.util.Scanner;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(value = {MemStat.class}) @PrepareForTest(value = {MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
public class LibvirtNetworkElementCommandWrapperTest { public class LibvirtNetworkElementCommandWrapperTest {
private static final String fullfile = "<domain type='kvm' id='143'>\n" private static final String fullfile = "<domain type='kvm' id='143'>\n"
+ " <name>r-3-VM</name>\n" + " <name>r-3-VM</name>\n"
@ -245,8 +247,8 @@ public class LibvirtNetworkElementCommandWrapperTest {
LibvirtUtilitiesHelper helper = mock(LibvirtUtilitiesHelper.class); LibvirtUtilitiesHelper helper = mock(LibvirtUtilitiesHelper.class);
when(_domain.getXMLDesc(0)).thenReturn(fullfile); when(_domain.getXMLDesc(0)).thenReturn(fullfile);
when(conn.domainLookupByName(anyString())).thenReturn(_domain); when(conn.domainLookupByName(nullable(String.class))).thenReturn(_domain);
when(helper.getConnectionByVmName(anyString())).thenReturn(conn); when(helper.getConnectionByVmName(nullable(String.class))).thenReturn(conn);
doReturn(helper).when(res).getLibvirtUtilitiesHelper(); doReturn(helper).when(res).getLibvirtUtilitiesHelper();
} }

View File

@ -26,8 +26,10 @@ import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Scanner; import java.util.Scanner;
@ -39,7 +41,10 @@ import org.libvirt.Connect;
import org.libvirt.Domain; import org.libvirt.Domain;
import org.libvirt.LibvirtException; import org.libvirt.LibvirtException;
import org.mockito.BDDMockito; import org.mockito.BDDMockito;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
@ -48,6 +53,7 @@ import com.cloud.agent.api.ReplugNicCommand;
import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.NicTO;
import com.cloud.hypervisor.kvm.resource.BridgeVifDriver; import com.cloud.hypervisor.kvm.resource.BridgeVifDriver;
import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource;
import com.cloud.hypervisor.kvm.resource.LibvirtVMDef;
import com.cloud.hypervisor.kvm.resource.OvsVifDriver; import com.cloud.hypervisor.kvm.resource.OvsVifDriver;
import com.cloud.network.Networks; import com.cloud.network.Networks;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
@ -55,8 +61,12 @@ import com.cloud.vm.VirtualMachine;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(value = {Script.class, MemStat.class}) @PrepareForTest(value = {Script.class, MemStat.class})
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
public class LibvirtReplugNicCommandWrapperTest { public class LibvirtReplugNicCommandWrapperTest {
@Mock
private LibvirtComputingResource libvirtComputingResource;
private static final String part_1 = private static final String part_1 =
"<domain type='kvm' id='143'>\n" "<domain type='kvm' id='143'>\n"
+ " <name>i-85-285-VM</name>\n" + " <name>i-85-285-VM</name>\n"
@ -276,6 +286,13 @@ public class LibvirtReplugNicCommandWrapperTest {
+ "<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>\n" + "<address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>\n"
+ "</interface>\n"; + "</interface>\n";
final LibvirtVMDef.InterfaceDef interfaceDef = Mockito.mock(LibvirtVMDef.InterfaceDef.class);
final List<LibvirtVMDef.InterfaceDef> ifaces = new ArrayList<LibvirtVMDef.InterfaceDef>();
ifaces.add(interfaceDef);
final Connect conn = Mockito.mock(Connect.class);
when(libvirtComputingResource.getInterfaces(conn, "")).thenReturn(ifaces);
final LibvirtReplugNicCommandWrapper wrapper = new LibvirtReplugNicCommandWrapper(); final LibvirtReplugNicCommandWrapper wrapper = new LibvirtReplugNicCommandWrapper();
final NicTO nic = new NicTO(); final NicTO nic = new NicTO();
nic.setType(Networks.TrafficType.Guest); nic.setType(Networks.TrafficType.Guest);

View File

@ -18,10 +18,13 @@
*/ */
package org.apache.cloudstack.kvm.ha; package org.apache.cloudstack.kvm.ha;
import com.cloud.exception.StorageUnavailableException; import static org.junit.Assert.assertFalse;
import com.cloud.host.Host; import static org.junit.Assert.assertTrue;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
import org.apache.cloudstack.ha.provider.HACheckerException; import org.apache.cloudstack.ha.provider.HACheckerException;
import org.joda.time.DateTime;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
@ -29,11 +32,9 @@ import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertFalse; import com.cloud.exception.StorageUnavailableException;
import static org.junit.Assert.assertTrue; import com.cloud.host.Host;
import static org.mockito.Mockito.when; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import org.joda.time.DateTime;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class KVMHostHATest { public class KVMHostHATest {
@ -53,21 +54,21 @@ public class KVMHostHATest {
@Test @Test
public void testHostActivityForHealthyHost() throws HACheckerException, StorageUnavailableException { public void testHostActivityForHealthyHost() throws HACheckerException, StorageUnavailableException {
when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); lenient().when(host.getHypervisorType()).thenReturn(HypervisorType.KVM);
when(kvmHostActivityChecker.isHealthy(host)).thenReturn(true); when(kvmHostActivityChecker.isHealthy(host)).thenReturn(true);
assertTrue(kvmHAProvider.isHealthy(host)); assertTrue(kvmHAProvider.isHealthy(host));
} }
@Test @Test
public void testHostActivityForUnHealthyHost() throws HACheckerException, StorageUnavailableException { public void testHostActivityForUnHealthyHost() throws HACheckerException, StorageUnavailableException {
when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); lenient().when(host.getHypervisorType()).thenReturn(HypervisorType.KVM);
when(kvmHostActivityChecker.isHealthy(host)).thenReturn(false); when(kvmHostActivityChecker.isHealthy(host)).thenReturn(false);
assertFalse(kvmHAProvider.isHealthy(host)); assertFalse(kvmHAProvider.isHealthy(host));
} }
@Test @Test
public void testHostActivityForActiveHost() throws HACheckerException, StorageUnavailableException { public void testHostActivityForActiveHost() throws HACheckerException, StorageUnavailableException {
when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); lenient().when(host.getHypervisorType()).thenReturn(HypervisorType.KVM);
DateTime dt = new DateTime(); DateTime dt = new DateTime();
when(kvmHostActivityChecker.isActive(host, dt)).thenReturn(true); when(kvmHostActivityChecker.isActive(host, dt)).thenReturn(true);
assertTrue(kvmHAProvider.hasActivity(host, dt)); assertTrue(kvmHAProvider.hasActivity(host, dt));
@ -75,7 +76,7 @@ public class KVMHostHATest {
@Test @Test
public void testHostActivityForDownHost() throws HACheckerException, StorageUnavailableException { public void testHostActivityForDownHost() throws HACheckerException, StorageUnavailableException {
when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); lenient().when(host.getHypervisorType()).thenReturn(HypervisorType.KVM);
DateTime dt = new DateTime(); DateTime dt = new DateTime();
when(kvmHostActivityChecker.isActive(host, dt)).thenReturn(false); when(kvmHostActivityChecker.isActive(host, dt)).thenReturn(false);
assertFalse(kvmHAProvider.hasActivity(host, dt)); assertFalse(kvmHAProvider.hasActivity(host, dt));

View File

@ -55,6 +55,11 @@
<version>${cs.vmware.api.version}</version> <version>${cs.vmware.api.version}</version>
<scope>compile</scope> <scope>compile</scope>
</dependency> </dependency>
<dependency>
<groupId>com.sun.org.apache.xml.internal</groupId>
<artifactId>resolver</artifactId>
<version>20050927</version>
</dependency>
<dependency> <dependency>
<groupId>org.apache.axis</groupId> <groupId>org.apache.axis</groupId>
<artifactId>axis</artifactId> <artifactId>axis</artifactId>

View File

@ -34,40 +34,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.vmware.vim25.VmConfigInfo;
import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand; import org.apache.cloudstack.agent.directdownload.DirectDownloadCommand;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.vmware.vim25.DatastoreHostMount;
import com.vmware.vim25.HostHostBusAdapter;
import com.vmware.vim25.HostInternetScsiHba;
import com.vmware.vim25.HostInternetScsiHbaAuthenticationProperties;
import com.vmware.vim25.HostInternetScsiHbaSendTarget;
import com.vmware.vim25.HostInternetScsiHbaStaticTarget;
import com.vmware.vim25.HostInternetScsiTargetTransport;
import com.vmware.vim25.HostResignatureRescanResult;
import com.vmware.vim25.HostUnresolvedVmfsResignatureSpec;
import com.vmware.vim25.HostScsiDisk;
import com.vmware.vim25.HostScsiTopology;
import com.vmware.vim25.HostScsiTopologyInterface;
import com.vmware.vim25.HostScsiTopologyLun;
import com.vmware.vim25.HostScsiTopologyTarget;
import com.vmware.vim25.HostUnresolvedVmfsExtent;
import com.vmware.vim25.HostUnresolvedVmfsVolume;
import com.vmware.vim25.InvalidStateFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualDisk;
import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo;
import com.vmware.vim25.VmfsDatastoreExpandSpec;
import com.vmware.vim25.VmfsDatastoreOption;
import org.apache.cloudstack.storage.command.AttachAnswer; import org.apache.cloudstack.storage.command.AttachAnswer;
import org.apache.cloudstack.storage.command.AttachCommand; import org.apache.cloudstack.storage.command.AttachCommand;
import org.apache.cloudstack.storage.command.CopyCmdAnswer; import org.apache.cloudstack.storage.command.CopyCmdAnswer;
@ -87,6 +54,8 @@ import org.apache.cloudstack.storage.to.SnapshotObjectTO;
import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.TemplateObjectTO;
import org.apache.cloudstack.storage.to.VolumeObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO;
import org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo; import org.apache.cloudstack.utils.volume.VirtualMachineDiskInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
import com.cloud.agent.api.Command; import com.cloud.agent.api.Command;
@ -127,6 +96,35 @@ import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.script.Script; import com.cloud.utils.script.Script;
import com.cloud.vm.VirtualMachine.PowerState; import com.cloud.vm.VirtualMachine.PowerState;
import com.cloud.vm.VmDetailConstants; import com.cloud.vm.VmDetailConstants;
import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.vmware.vim25.DatastoreHostMount;
import com.vmware.vim25.HostHostBusAdapter;
import com.vmware.vim25.HostInternetScsiHba;
import com.vmware.vim25.HostInternetScsiHbaAuthenticationProperties;
import com.vmware.vim25.HostInternetScsiHbaSendTarget;
import com.vmware.vim25.HostInternetScsiHbaStaticTarget;
import com.vmware.vim25.HostInternetScsiTargetTransport;
import com.vmware.vim25.HostResignatureRescanResult;
import com.vmware.vim25.HostScsiDisk;
import com.vmware.vim25.HostScsiTopology;
import com.vmware.vim25.HostScsiTopologyInterface;
import com.vmware.vim25.HostScsiTopologyLun;
import com.vmware.vim25.HostScsiTopologyTarget;
import com.vmware.vim25.HostUnresolvedVmfsExtent;
import com.vmware.vim25.HostUnresolvedVmfsResignatureSpec;
import com.vmware.vim25.HostUnresolvedVmfsVolume;
import com.vmware.vim25.InvalidStateFaultMsg;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualDeviceConfigSpecOperation;
import com.vmware.vim25.VirtualDisk;
import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VmConfigInfo;
import com.vmware.vim25.VmfsDatastoreExpandSpec;
import com.vmware.vim25.VmfsDatastoreOption;
public class VmwareStorageProcessor implements StorageProcessor { public class VmwareStorageProcessor implements StorageProcessor {
@ -3527,9 +3525,9 @@ public class VmwareStorageProcessor implements StorageProcessor {
private static String deriveTemplateUuidOnHost(VmwareHypervisorHost hyperHost, String storeIdentifier, String templateName) { private static String deriveTemplateUuidOnHost(VmwareHypervisorHost hyperHost, String storeIdentifier, String templateName) {
String templateUuid; String templateUuid;
try{ try {
templateUuid = UUID.nameUUIDFromBytes((templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue()).getBytes("UTF-8")).toString(); templateUuid = UUID.nameUUIDFromBytes((templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue()).getBytes("UTF-8")).toString();
}catch(UnsupportedEncodingException e){ } catch(UnsupportedEncodingException e){
s_logger.warn("unexpected encoding error, using default Charset: " + e.getLocalizedMessage()); s_logger.warn("unexpected encoding error, using default Charset: " + e.getLocalizedMessage());
templateUuid = UUID.nameUUIDFromBytes((templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue()).getBytes(Charset.defaultCharset())) templateUuid = UUID.nameUUIDFromBytes((templateName + "@" + storeIdentifier + "-" + hyperHost.getMor().getValue()).getBytes(Charset.defaultCharset()))
.toString(); .toString();

View File

@ -102,7 +102,7 @@ public class VmwareManagerImplTest {
host.setDataCenterId(1); host.setDataCenterId(1);
host.setHypervisorType(Hypervisor.HypervisorType.VMware); host.setHypervisorType(Hypervisor.HypervisorType.VMware);
Mockito.doReturn(Collections.singletonList(host)).when(hostDao).listAllHostsByZoneAndHypervisorType(Mockito.anyLong(), Mockito.any()); Mockito.doReturn(Collections.singletonList(host)).when(hostDao).listAllHostsByZoneAndHypervisorType(Mockito.anyLong(), Mockito.any());
Mockito.doReturn(hostDetails).when(hostDetailsDao).findDetails(Mockito.anyLong()); Mockito.lenient().doReturn(hostDetails).when(hostDetailsDao).findDetails(Mockito.anyLong());
Mockito.doReturn("some-old-guid").when(hostDetails).get("guid"); Mockito.doReturn("some-old-guid").when(hostDetails).get("guid");
Mockito.doReturn(hostDetails).when(hostDetailsDao).findDetails(Mockito.anyLong()); Mockito.doReturn(hostDetails).when(hostDetailsDao).findDetails(Mockito.anyLong());

View File

@ -16,20 +16,19 @@
// under the License. // under the License.
package com.cloud.hypervisor.vmware.resource; package com.cloud.hypervisor.vmware.resource;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.never;
import static org.mockito.Matchers.eq; import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import java.util.ArrayList; import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.whenNew; import static org.powermock.api.mockito.PowerMockito.whenNew;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.EnumMap; import java.util.EnumMap;
import java.util.HashMap; import java.util.HashMap;
@ -51,14 +50,6 @@ import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import com.vmware.vim25.HostCapability;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineVideoCard;
import com.cloud.agent.api.Command; import com.cloud.agent.api.Command;
import com.cloud.agent.api.ScaleVmAnswer; import com.cloud.agent.api.ScaleVmAnswer;
import com.cloud.agent.api.ScaleVmCommand; import com.cloud.agent.api.ScaleVmCommand;
@ -67,19 +58,25 @@ import com.cloud.agent.api.to.NfsTO;
import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.NicTO;
import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VirtualMachineTO;
import com.cloud.agent.api.to.VolumeTO; import com.cloud.agent.api.to.VolumeTO;
import com.cloud.hypervisor.vmware.mo.DatacenterMO;
import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.hypervisor.vmware.mo.DatacenterMO;
import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.HostMO;
import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; import com.cloud.hypervisor.vmware.mo.VirtualMachineMO;
import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost;
import com.cloud.hypervisor.vmware.util.VmwareClient; import com.cloud.hypervisor.vmware.util.VmwareClient;
import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareContext;
import com.cloud.vm.VmDetailConstants;
import com.cloud.storage.resource.VmwareStorageProcessor; import com.cloud.storage.resource.VmwareStorageProcessor;
import com.cloud.storage.resource.VmwareStorageSubsystemCommandHandler;
import com.cloud.storage.resource.VmwareStorageProcessor.VmwareStorageProcessorConfigurableFields; import com.cloud.storage.resource.VmwareStorageProcessor.VmwareStorageProcessorConfigurableFields;
import com.cloud.storage.resource.VmwareStorageSubsystemCommandHandler;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.VmDetailConstants;
import com.vmware.vim25.HostCapability;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDeviceConfigSpec;
import com.vmware.vim25.VirtualMachineConfigSpec;
import com.vmware.vim25.VirtualMachineVideoCard;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest({CopyCommand.class, DatacenterMO.class, VmwareResource.class}) @PrepareForTest({CopyCommand.class, DatacenterMO.class, VmwareResource.class})
@ -399,7 +396,7 @@ public class VmwareResourceTest {
verify(_resource, never()).examineStorageSubSystemCommandNfsVersion(Matchers.eq(storageCmd), any(EnumMap.class)); verify(_resource, never()).examineStorageSubSystemCommandNfsVersion(Matchers.eq(storageCmd), any(EnumMap.class));
} }
@Test(expected=CloudRuntimeException.class) @Test(expected= CloudRuntimeException.class)
public void testFindVmOnDatacenterNullHyperHostReference() throws Exception { public void testFindVmOnDatacenterNullHyperHostReference() throws Exception {
when(hyperHost.getMor()).thenReturn(null); when(hyperHost.getMor()).thenReturn(null);
_resource.findVmOnDatacenter(context, hyperHost, volume); _resource.findVmOnDatacenter(context, hyperHost, volume);

View File

@ -82,11 +82,11 @@ public class XenServerGuruTest {
Mockito.when(copyCommandMock.getDestTO()).thenReturn(destinationDataMock); Mockito.when(copyCommandMock.getDestTO()).thenReturn(destinationDataMock);
Mockito.when(changedHost.getId()).thenReturn(changedHostId); Mockito.when(changedHost.getId()).thenReturn(changedHostId);
Mockito.when(defaultHost.getId()).thenReturn(defaultHostId); Mockito.lenient().when(defaultHost.getId()).thenReturn(defaultHostId);
Mockito.when(defaultHost.getDataCenterId()).thenReturn(zoneId); Mockito.when(defaultHost.getDataCenterId()).thenReturn(zoneId);
Mockito.when(hostDaoMock.findById(defaultHostId)).thenReturn(defaultHost); Mockito.when(hostDaoMock.findById(defaultHostId)).thenReturn(defaultHost);
Mockito.when(hostDaoMock.findById(changedHostId)).thenReturn(changedHost); Mockito.lenient().when(hostDaoMock.findById(changedHostId)).thenReturn(changedHost);
} }
@Test @Test

View File

@ -21,6 +21,7 @@ package com.cloud.hypervisor.xenserver.resource;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import java.util.HashSet; import java.util.HashSet;
@ -177,7 +178,7 @@ public class Xenserver625StorageProcessorTest {
SR sr = xenserver625StorageProcessor.retrieveAlreadyConfiguredSr(connectionMock, pathMock); SR sr = xenserver625StorageProcessor.retrieveAlreadyConfiguredSr(connectionMock, pathMock);
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(SR.class);
SR.getByNameLabel(connectionMock, pathMock); SR.getByNameLabel(connectionMock, pathMock);
Assert.assertNull(sr); Assert.assertNull(sr);
} }
@ -337,7 +338,7 @@ public class Xenserver625StorageProcessorTest {
SR sr = xenserver625StorageProcessor.createNewFileSr(connectionMock, pathMock); SR sr = xenserver625StorageProcessor.createNewFileSr(connectionMock, pathMock);
assertNull(sr); assertNull(sr);
Mockito.verify(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock), Mockito.any(SR.class), Mockito.any(PBD.class)); Mockito.verify(xenserver625StorageProcessor).removeSrAndPbdIfPossible(Mockito.eq(connectionMock), nullable(SR.class), nullable(PBD.class));
} }
@Test @Test
@ -403,7 +404,7 @@ public class Xenserver625StorageProcessorTest {
Mockito.verify(srMock).scan(connectionMock); Mockito.verify(srMock).scan(connectionMock);
Mockito.verify(pbdMock).plug(connectionMock); Mockito.verify(pbdMock).plug(connectionMock);
PowerMockito.verifyStatic(); PowerMockito.verifyStatic(PBD.class);
SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock), Mockito.eq(pathMock), Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false), SR.introduce(Mockito.eq(connectionMock), Mockito.eq(srUuid), Mockito.eq(pathMock), Mockito.eq(pathMock), Mockito.eq("file"), Mockito.eq("file"), Mockito.eq(false),
Mockito.anyMapOf(String.class, String.class)); Mockito.anyMapOf(String.class, String.class));
PBD.create(Mockito.eq(connectionMock), Mockito.any(Record.class)); PBD.create(Mockito.eq(connectionMock), Mockito.any(Record.class));

View File

@ -45,8 +45,9 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.cloud.agent.api.Answer; import com.cloud.agent.api.Answer;
import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachIsoCommand;
@ -95,6 +96,7 @@ import com.cloud.agent.api.RebootRouterCommand;
import com.cloud.agent.api.RevertToVMSnapshotCommand; import com.cloud.agent.api.RevertToVMSnapshotCommand;
import com.cloud.agent.api.ScaleVmCommand; import com.cloud.agent.api.ScaleVmCommand;
import com.cloud.agent.api.SecurityGroupRulesCmd; import com.cloud.agent.api.SecurityGroupRulesCmd;
import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.SetupCommand;
import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartCommand;
import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StopCommand;
@ -102,7 +104,6 @@ import com.cloud.agent.api.UnPlugNicCommand;
import com.cloud.agent.api.UpdateHostPasswordCommand; import com.cloud.agent.api.UpdateHostPasswordCommand;
import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.UpgradeSnapshotCommand;
import com.cloud.agent.api.VMSnapshotTO; import com.cloud.agent.api.VMSnapshotTO;
import com.cloud.agent.api.SecurityGroupRulesCmd.IpPortAndProto;
import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.check.CheckSshCommand;
import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.CheckConsoleProxyLoadCommand;
import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand; import com.cloud.agent.api.proxy.WatchConsoleProxyLoadCommand;
@ -144,7 +145,8 @@ import com.xensource.xenapi.Types.XenAPIException;
import com.xensource.xenapi.VM; import com.xensource.xenapi.VM;
import com.xensource.xenapi.VMGuestMetrics; import com.xensource.xenapi.VMGuestMetrics;
@RunWith(MockitoJUnitRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(value = {Pool.Record.class})
public class CitrixRequestWrapperTest { public class CitrixRequestWrapperTest {
@Mock @Mock

View File

@ -32,7 +32,7 @@
<plugin> <plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId> <groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId> <artifactId>maven-jaxb2-plugin</artifactId>
<version>0.7.1</version> <version>0.14.0</version>
<executions> <executions>
<execution> <execution>
<id>interface</id> <id>interface</id>

View File

@ -25,8 +25,8 @@ import static org.mockito.Mockito.when;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;
import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshAnswer;
import com.cloud.agent.manager.Commands; import com.cloud.agent.manager.Commands;

View File

@ -36,8 +36,8 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.reflect.Whitebox;
import com.cloud.dc.PodVlanMapVO; import com.cloud.dc.PodVlanMapVO;
import com.cloud.dc.dao.PodVlanMapDao; import com.cloud.dc.dao.PodVlanMapDao;

View File

@ -16,6 +16,8 @@
// under the License. // under the License.
package org.apache.cloudstack.internallbvmmgr; package org.apache.cloudstack.internallbvmmgr;
import static org.mockito.ArgumentMatchers.nullable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@ -124,14 +126,13 @@ public class InternalLBVMManagerTest extends TestCase {
List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>(); List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
list.add(off); list.add(off);
list.add(off); list.add(off);
Mockito.when(_svcOffDao.createSystemServiceOfferings(Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Mockito.when(_svcOffDao.createSystemServiceOfferings(nullable(String.class), nullable(String.class), nullable(Integer.class), nullable(Integer.class), nullable(Integer.class),
Matchers.anyInt(), Matchers.anyInt(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.any(ProvisioningType.class), Matchers.anyBoolean(), nullable(Integer.class), nullable(Integer.class), nullable(Boolean.class), nullable(String.class), nullable(ProvisioningType.class), nullable(Boolean.class),
Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(VirtualMachine.Type.class), Matchers.anyBoolean())).thenReturn(list); nullable(String.class), nullable(Boolean.class), nullable(VirtualMachine.Type.class), nullable(Boolean.class))).thenReturn(list);
ComponentContext.initComponentsLifeCycle(); ComponentContext.initComponentsLifeCycle();
vm = vm = new DomainRouterVO(1L, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false,
new DomainRouterVO(1L, off.getId(), 1, "alena", 1, HypervisorType.XenServer, 1, 1, 1, 1, false, null, false, false,
VirtualMachine.Type.InternalLoadBalancerVm, null); VirtualMachine.Type.InternalLoadBalancerVm, null);
vm.setRole(Role.INTERNAL_LB_VM); vm.setRole(Role.INTERNAL_LB_VM);
vm = setId(vm, 1); vm = setId(vm, 1);
@ -154,7 +155,7 @@ public class InternalLBVMManagerTest extends TestCase {
answers[0] = answer; answers[0] = answer;
try { try {
Mockito.when(_agentMgr.send(Matchers.anyLong(), Matchers.any(Commands.class))).thenReturn(answers); Mockito.when(_agentMgr.send(nullable(Long.class), nullable(Commands.class))).thenReturn(answers);
} catch (final AgentUnavailableException e) { } catch (final AgentUnavailableException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); e.printStackTrace();

View File

@ -16,14 +16,14 @@
// under the License. // under the License.
package org.apache.cloudstack.internallbvmmgr; package org.apache.cloudstack.internallbvmmgr;
import static org.mockito.ArgumentMatchers.nullable;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import junit.framework.TestCase;
import org.apache.cloudstack.context.CallContext; import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService; import org.apache.cloudstack.network.lb.InternalLoadBalancerVMService;
import org.junit.After; import org.junit.After;
@ -57,6 +57,8 @@ import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachineManager; import com.cloud.vm.VirtualMachineManager;
import com.cloud.vm.dao.DomainRouterDao; import com.cloud.vm.dao.DomainRouterDao;
import junit.framework.TestCase;
/** /**
* Set of unittests for InternalLoadBalancerVMService * Set of unittests for InternalLoadBalancerVMService
* *
@ -96,9 +98,9 @@ public class InternalLBVMServiceTest extends TestCase {
List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>(); List<ServiceOfferingVO> list = new ArrayList<ServiceOfferingVO>();
list.add(off); list.add(off);
list.add(off); list.add(off);
Mockito.when(_svcOffDao.createSystemServiceOfferings(Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Mockito.when(_svcOffDao.createSystemServiceOfferings(nullable(String.class), nullable(String.class), nullable(Integer.class), nullable(Integer.class), nullable(Integer.class),
Matchers.anyInt(), Matchers.anyInt(), Matchers.anyBoolean(), Matchers.anyString(), Matchers.any(ProvisioningType.class), Matchers.anyBoolean(), nullable(Integer.class), nullable(Integer.class), nullable(Boolean.class), nullable(String.class), nullable(ProvisioningType.class), nullable(Boolean.class),
Matchers.anyString(), Matchers.anyBoolean(), Matchers.any(VirtualMachine.Type.class), Matchers.anyBoolean())).thenReturn(list); nullable(String.class), nullable(Boolean.class), nullable(VirtualMachine.Type.class), nullable(Boolean.class))).thenReturn(list);
ComponentContext.initComponentsLifeCycle(); ComponentContext.initComponentsLifeCycle();

View File

@ -20,10 +20,10 @@
http://www.springframework.org/schema/context http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config /> <context:annotation-config />
<!-- @DB support -->
<!-- @DB support -->
<bean id="componentContext" class="com.cloud.utils.component.ComponentContext" /> <bean id="componentContext" class="com.cloud.utils.component.ComponentContext" />
<bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" /> <bean id="transactionContextBuilder" class="com.cloud.utils.db.TransactionContextBuilder" />
@ -37,10 +37,10 @@
</property> </property>
</bean> </bean>
<bean id="InternalLoadBalancerElementService" class="org.apache.cloudstack.network.element.InternalLoadBalancerElement"> <bean id="InternalLoadBalancerElementService" class="org.apache.cloudstack.network.element.InternalLoadBalancerElement">
<property name="name" value="InternalLoadBalancerElementService"/> <property name="name" value="InternalLoadBalancerElementService"/>
</bean> </bean>
<bean class="org.apache.cloudstack.internallbelement.ElementChildTestConfiguration" /> <bean class="org.apache.cloudstack.internallbelement.ElementChildTestConfiguration" />
</beans> </beans>

View File

@ -259,11 +259,8 @@ public class NiciraNvpElementTest {
verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() { verify(agentManager, atLeast(1)).easySend(eq(NETWORK_ID), argThat(new ArgumentMatcher<ConfigurePublicIpsOnLogicalRouterCommand>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final ConfigurePublicIpsOnLogicalRouterCommand command) {
final ConfigurePublicIpsOnLogicalRouterCommand command = (ConfigurePublicIpsOnLogicalRouterCommand)argument; return command.getPublicCidrs().size() == 1;
if (command.getPublicCidrs().size() == 1)
return true;
return false;
} }
})); }));
} }

View File

@ -45,11 +45,11 @@ public class NiciraNvpApiIT {
final String user = System.getProperty("nvp.admin.user"); final String user = System.getProperty("nvp.admin.user");
final String pass = System.getProperty("nvp.admin.pwd"); final String pass = System.getProperty("nvp.admin.pwd");
api = NiciraNvpApi.create() api = NiciraNvpApi.create()
.host(host) .host(host)
.username(user) .username(user)
.password(pass) .password(pass)
.httpClient(HttpClientHelper.createHttpClient(5)) .httpClient(HttpClientHelper.createHttpClient(5))
.build(); .build();
} }
@Test @Test
@ -209,7 +209,7 @@ public class NiciraNvpApiIT {
api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment); api.updateLogicalSwitchPortAttachment(logicalSwitch.getUuid(), logicalSwitchPort.getUuid(), vifAttachment);
assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected", assertEquals("Read a LogicalSwitchPort by vifAttachment different than expected",
api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), logicalSwitchPort.getUuid()); api.findLogicalSwitchPortUuidByVifAttachmentUuid(logicalSwitch.getUuid(), vifAttachment.getVifUuid()), logicalSwitchPort.getUuid());
api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid()); api.deleteLogicalSwitchPort(logicalSwitch.getUuid(), logicalSwitchPort.getUuid());
@ -225,7 +225,7 @@ public class NiciraNvpApiIT {
logicalRouter.setNatSynchronizationEnabled(true); logicalRouter.setNatSynchronizationEnabled(true);
logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE); logicalRouter.setReplicationMode(LogicalRouter.REPLICATION_MODE_SERVICE);
final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig( final RoutingConfig routingConfig = new SingleDefaultRouteImplicitRoutingConfig(
new RouterNextHop("192.168.10.20")); new RouterNextHop("192.168.10.20"));
logicalRouter.setRoutingConfig(routingConfig); logicalRouter.setRoutingConfig(routingConfig);
// In the creation we don't get to specify UUID, href or schema: they don't exist yet // In the creation we don't get to specify UUID, href or schema: they don't exist yet
@ -312,7 +312,7 @@ public class NiciraNvpApiIT {
final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus(); final ControlClusterStatus controlClusterStatus = api.getControlClusterStatus();
final String clusterStatus = controlClusterStatus.getClusterStatus(); final String clusterStatus = controlClusterStatus.getClusterStatus();
final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") || final boolean correctStatus = clusterStatus.equalsIgnoreCase("stable") ||
clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable"); clusterStatus.equalsIgnoreCase("joining") || clusterStatus.equalsIgnoreCase("unstable");
assertTrue("Not recognizable cluster status", correctStatus); assertTrue("Not recognizable cluster status", correctStatus);
} }

View File

@ -47,6 +47,7 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
@ -57,6 +58,7 @@ import com.cloud.utils.rest.HttpUriRequestBuilder;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(NiciraRestClient.class) @PrepareForTest(NiciraRestClient.class)
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.apache.log4j.*"})
public class NiciraRestClientTest { public class NiciraRestClientTest {
private static final int HTTPS_PORT = 443; private static final int HTTPS_PORT = 443;

View File

@ -21,9 +21,9 @@ package com.cloud.network.resource;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.argThat; import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Matchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.doThrow;
@ -465,8 +465,8 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final NatRule argument) {
final NatRule rule = (NatRule) argument; final NatRule rule = argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -508,8 +508,8 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final NatRule argument) {
final NatRule rule = (NatRule) argument; final NatRule rule = argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -553,8 +553,7 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() { verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final UUID uuid) {
final UUID uuid = (UUID) argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true; return true;
} }
@ -626,8 +625,7 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, atLeast(2)).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final NatRule rule) {
final NatRule rule = (NatRule) argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -669,8 +667,7 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() { verify(nvpApi, never()).createLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<NatRule>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final NatRule rule) {
final NatRule rule = (NatRule) argument;
if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) { if (rule.getType().equals("DestinationNatRule") && ((DestinationNatRule) rule).getToDestinationIpAddress().equals("10.10.10.10")) {
return true; return true;
} }
@ -714,8 +711,7 @@ public class NiciraNvpResourceTest {
assertTrue(a.getResult()); assertTrue(a.getResult());
verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() { verify(nvpApi, atLeast(2)).deleteLogicalRouterNatRule(eq("aaaaa"), argThat(new ArgumentMatcher<UUID>() {
@Override @Override
public boolean matches(final Object argument) { public boolean matches(final UUID uuid) {
final UUID uuid = (UUID) argument;
if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) { if (rule0Uuid.equals(uuid) || rule1Uuid.equals(uuid)) {
return true; return true;
} }

View File

@ -17,7 +17,6 @@
# under the License. # under the License.
# #
nvp.host=localhost
nvp.host=${nvp-host} nvp.admin.user=admin
nvp.admin.user=${nvp-admin-user} nvp.admin.pwd=adminpassword
nvp.admin.pwd=${nvp-admin-pwd}

View File

@ -46,6 +46,7 @@
<version>${gmaven.version}</version> <version>${gmaven.version}</version>
<configuration> <configuration>
<providerSelection>1.7</providerSelection> <providerSelection>1.7</providerSelection>
<source/>
</configuration> </configuration>
<executions> <executions>
<execution> <execution>
@ -147,9 +148,20 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId> <artifactId>mockito-core</artifactId>
<version>${cs.mockito.version}</version> <version>${cs.mockito.version}</version>
<scope>compile</scope> <scope>compile</scope>
<exclusions>
<exclusion>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>1.10.5</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>

View File

@ -27,11 +27,11 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Matchers.anyString; import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Matchers.isNull; import static org.mockito.ArgumentMatchers.nullable;
import static org.powermock.api.mockito.PowerMockito.spy; import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when; import static org.powermock.api.mockito.PowerMockito.when;
@ -56,7 +56,7 @@ public class LdapCreateAccountCmdTest implements LdapConfigurationChanger {
@Test(expected = ServerApiException.class) @Test(expected = ServerApiException.class)
public void failureToRetrieveLdapUser() throws Exception { public void failureToRetrieveLdapUser() throws Exception {
// We have an LdapManager, AccountService and LdapCreateAccountCmd and LDAP user that doesn't exist // We have an LdapManager, AccountService and LdapCreateAccountCmd and LDAP user that doesn't exist
when(ldapManager.getUser(anyString(), isNull(Long.class))).thenThrow(NoLdapUserMatchingQueryException.class); when(ldapManager.getUser(nullable(String.class), isNull())).thenThrow(NoLdapUserMatchingQueryException.class);
ldapCreateAccountCmd.execute(); ldapCreateAccountCmd.execute();
fail("An exception should have been thrown: " + ServerApiException.class); fail("An exception should have been thrown: " + ServerApiException.class);
} }
@ -65,7 +65,7 @@ public class LdapCreateAccountCmdTest implements LdapConfigurationChanger {
public void failedCreationDueToANullResponseFromCloudstackAccountCreator() throws Exception { public void failedCreationDueToANullResponseFromCloudstackAccountCreator() throws Exception {
// We have an LdapManager, AccountService and LdapCreateAccountCmd // We have an LdapManager, AccountService and LdapCreateAccountCmd
LdapUser mrMurphy = new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering", false, null); LdapUser mrMurphy = new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,ou=engineering,dc=cloudstack,dc=org", "engineering", false, null);
when(ldapManager.getUser(anyString(), isNull(Long.class))).thenReturn(mrMurphy).thenReturn(mrMurphy); when(ldapManager.getUser(nullable(String.class), isNull())).thenReturn(mrMurphy).thenReturn(mrMurphy);
ldapCreateAccountCmd.execute(); ldapCreateAccountCmd.execute();
fail("An exception should have been thrown: " + ServerApiException.class); fail("An exception should have been thrown: " + ServerApiException.class);
} }

View File

@ -27,10 +27,10 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.apache.cloudstack.api.response.LdapUserResponse; import org.apache.cloudstack.api.response.LdapUserResponse;
import org.apache.cloudstack.ldap.LdapManager; import org.apache.cloudstack.ldap.LdapManager;
import org.apache.cloudstack.ldap.LdapUser; import org.apache.cloudstack.ldap.LdapUser;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;

View File

@ -36,6 +36,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
@ -47,9 +48,8 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.times; import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.doReturn; import static org.powermock.api.mockito.PowerMockito.doReturn;
@ -59,6 +59,7 @@ import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(CallContext.class) @PrepareForTest(CallContext.class)
@PowerMockIgnore({"javax.xml.*", "org.w3c.dom.*", "org.apache.xerces.*", "org.xml.*"})
public class LdapListUsersCmdTest implements LdapConfigurationChanger { public class LdapListUsersCmdTest implements LdapConfigurationChanger {
public static final String LOCAL_DOMAIN_ID = "12345678-90ab-cdef-fedc-ba0987654321"; public static final String LOCAL_DOMAIN_ID = "12345678-90ab-cdef-fedc-ba0987654321";
@ -133,7 +134,7 @@ public class LdapListUsersCmdTest implements LdapConfigurationChanger {
ldapListUsersCmd.execute(); ldapListUsersCmd.execute();
verify(queryService, times(1)).searchForUsers(anyLong(), anyBoolean()); verify(queryService, times(1)).searchForUsers(nullable(Long.class), nullable(Boolean.class));
assertNotEquals(0, ((ListResponse)ldapListUsersCmd.getResponseObject()).getResponses().size()); assertNotEquals(0, ((ListResponse)ldapListUsersCmd.getResponseObject()).getResponses().size());
} }
@ -174,7 +175,7 @@ public class LdapListUsersCmdTest implements LdapConfigurationChanger {
*/ */
@Test @Test
public void isNotACloudstackUser() { public void isNotACloudstackUser() {
doReturn(new ListResponse<UserResponse>()).when(queryService).searchForUsers(anyLong(), anyBoolean()); doReturn(new ListResponse<UserResponse>()).when(queryService).searchForUsers(nullable(Long.class), nullable(Boolean.class));
LdapUser ldapUser = new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,dc=cloudstack,dc=org", null, false, null); LdapUser ldapUser = new LdapUser("rmurphy", "rmurphy@cloudstack.org", "Ryan", "Murphy", "cn=rmurphy,dc=cloudstack,dc=org", null, false, null);
@ -413,7 +414,7 @@ public class LdapListUsersCmdTest implements LdapConfigurationChanger {
domainVO.setName(domainName); domainVO.setName(domainName);
domainVO.setId(domainId); domainVO.setId(domainId);
domainVO.setUuid(LOCAL_DOMAIN_ID); domainVO.setUuid(LOCAL_DOMAIN_ID);
when(domainService.getDomain(anyLong())).thenReturn(domainVO); when(domainService.getDomain(nullable(Long.class))).thenReturn(domainVO);
return domainVO; return domainVO;
} }
@ -430,7 +431,7 @@ public class LdapListUsersCmdTest implements LdapConfigurationChanger {
ListResponse<UserResponse> queryServiceResponse = new ListResponse<>(); ListResponse<UserResponse> queryServiceResponse = new ListResponse<>();
queryServiceResponse.setResponses(responses); queryServiceResponse.setResponses(responses);
doReturn(queryServiceResponse).when(queryService).searchForUsers(anyLong(), anyBoolean()); doReturn(queryServiceResponse).when(queryService).searchForUsers(nullable(Long.class), nullable(Boolean.class));
} }
private UserResponse createMockUserResponse(String uid, User.Source source) { private UserResponse createMockUserResponse(String uid, User.Source source) {

View File

@ -20,13 +20,14 @@ import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.ldap.LdapContext; import javax.naming.ldap.LdapContext;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any; import static org.mockito.Matchers.any;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
@ -78,9 +79,9 @@ public class ADLdapUserManagerImplTest {
@Test(expected = IllegalArgumentException.class) @Test(expected = IllegalArgumentException.class)
public void testGetUsersInGroupUsingNullGroup() throws Exception { public void testGetUsersInGroupUsingNullGroup() throws Exception {
String[] returnAttributes = {"username", "firstname", "lastname", "email"}; String[] returnAttributes = {"username", "firstname", "lastname", "email"};
when(ldapConfiguration.getScope()).thenReturn(SearchControls.SUBTREE_SCOPE); lenient().when(ldapConfiguration.getScope()).thenReturn(SearchControls.SUBTREE_SCOPE);
when(ldapConfiguration.getReturnAttributes(null)).thenReturn(returnAttributes); lenient().when(ldapConfiguration.getReturnAttributes(null)).thenReturn(returnAttributes);
when(ldapConfiguration.getBaseDn(any())).thenReturn(null).thenReturn(null).thenReturn("DC=cloud,DC=citrix,DC=com"); lenient().when(ldapConfiguration.getBaseDn(any())).thenReturn(null).thenReturn(null).thenReturn("DC=cloud,DC=citrix,DC=com");
LdapContext context = ldapContext; LdapContext context = ldapContext;
String [] groups = {null, "group", null}; String [] groups = {null, "group", null};

View File

@ -30,7 +30,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -41,6 +41,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.spy; import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -73,7 +74,7 @@ public class LdapAuthenticatorTest {
final UserAccountVO user = new UserAccountVO(); final UserAccountVO user = new UserAccountVO();
user.setSource(User.Source.NATIVE); user.setSource(User.Source.NATIVE);
when(userAccountDao.getUserAccount(username, domainId)).thenReturn(user); lenient().when(userAccountDao.getUserAccount(username, domainId)).thenReturn(user);
Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> rc; Pair<Boolean, UserAuthenticator.ActionOnFailedAuthentication> rc;
rc = ldapAuthenticator.authenticate(username, "password", domainId, (Map<String, Object[]>)null); rc = ldapAuthenticator.authenticate(username, "password", domainId, (Map<String, Object[]>)null);
assertFalse("authentication succeeded when it should have failed", rc.first()); assertFalse("authentication succeeded when it should have failed", rc.first());

View File

@ -38,7 +38,7 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@ -51,7 +51,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail; import static org.junit.Assert.fail;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.lenient;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class LdapDirectoryServerConnectionTest { public class LdapDirectoryServerConnectionTest {
@ -82,15 +82,15 @@ public class LdapDirectoryServerConnectionTest {
@Before @Before
public void setup() throws Exception { public void setup() throws Exception {
LdapConfigurationVO configurationVO = new LdapConfigurationVO("localhost",10389,null); LdapConfigurationVO configurationVO = new LdapConfigurationVO("localhost",10389,null);
when(configurationDao.find("localhost",10389,null)).thenReturn(configurationVO); lenient().when(configurationDao.find("localhost",10389,null)).thenReturn(configurationVO);
ldapTestConfigTool.overrideConfigValue(configuration, "ldapBaseDn", "ou=system"); ldapTestConfigTool.overrideConfigValue(configuration, "ldapBaseDn", "ou=system");
ldapTestConfigTool.overrideConfigValue(configuration, "ldapBindPassword", "secret"); ldapTestConfigTool.overrideConfigValue(configuration, "ldapBindPassword", "secret");
ldapTestConfigTool.overrideConfigValue(configuration, "ldapBindPrincipal", "uid=admin,ou=system"); ldapTestConfigTool.overrideConfigValue(configuration, "ldapBindPrincipal", "uid=admin,ou=system");
ldapTestConfigTool.overrideConfigValue(configuration, "ldapMemberOfAttribute", "memberOf"); ldapTestConfigTool.overrideConfigValue(configuration, "ldapMemberOfAttribute", "memberOf");
when(userManagerFactory.getInstance(LdapUserManager.Provider.OPENLDAP)).thenReturn(new OpenLdapUserManagerImpl(configuration)); lenient().when(userManagerFactory.getInstance(LdapUserManager.Provider.OPENLDAP)).thenReturn(new OpenLdapUserManagerImpl(configuration));
// construct an ellaborate structure around a single object // construct an ellaborate structure around a single object
Pair<List<LdapConfigurationVO>, Integer> vos = new Pair<List<LdapConfigurationVO>, Integer>( Collections.singletonList(configurationVO),1); Pair<List<LdapConfigurationVO>, Integer> vos = new Pair<List<LdapConfigurationVO>, Integer>( Collections.singletonList(configurationVO),1);
when(configurationDao.searchConfigurations(null, 0, 1L)).thenReturn(vos); lenient().when(configurationDao.searchConfigurations(null, 0, 1L)).thenReturn(vos);
contextFactory = new LdapContextFactory(configuration); contextFactory = new LdapContextFactory(configuration);
ldapManager = new LdapManagerImpl(configurationDao, contextFactory, userManagerFactory, configuration); ldapManager = new LdapManagerImpl(configurationDao, contextFactory, userManagerFactory, configuration);

View File

@ -19,11 +19,8 @@
package org.apache.cloudstack; package org.apache.cloudstack;
import com.cloud.user.DomainManager; import java.lang.reflect.Field;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.user.dao.UserDao;
import junit.framework.TestCase;
import org.apache.cloudstack.framework.security.keystore.KeystoreDao; import org.apache.cloudstack.framework.security.keystore.KeystoreDao;
import org.apache.cloudstack.saml.SAML2AuthManagerImpl; import org.apache.cloudstack.saml.SAML2AuthManagerImpl;
import org.apache.cloudstack.saml.SAMLTokenDao; import org.apache.cloudstack.saml.SAMLTokenDao;
@ -35,7 +32,12 @@ import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import java.lang.reflect.Field; import com.cloud.user.DomainManager;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.user.dao.UserDao;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class SAML2AuthManagerImplTest extends TestCase { public class SAML2AuthManagerImplTest extends TestCase {
@ -164,7 +166,7 @@ public class SAML2AuthManagerImplTest extends TestCase {
assertTrue(saml2AuthManager.getCommands().size() == 0); assertTrue(saml2AuthManager.getCommands().size() == 0);
assertTrue(saml2AuthManager.getAuthCommands().size() == 0); assertTrue(saml2AuthManager.getAuthCommands().size() == 0);
// Re-enable the plugin // Re-enable the plugin
Mockito.doReturn(true).when(saml2AuthManager).isSAMLPluginEnabled(); Mockito.lenient().doReturn(true).when(saml2AuthManager).isSAMLPluginEnabled();
} }
@Test @Test

View File

@ -19,24 +19,25 @@
package org.apache.cloudstack; package org.apache.cloudstack;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.apache.cloudstack.saml.SAML2UserAuthenticator;
import org.apache.cloudstack.saml.SAMLPluginConstants;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication; import com.cloud.server.auth.UserAuthenticator.ActionOnFailedAuthentication;
import com.cloud.user.UserAccountVO; import com.cloud.user.UserAccountVO;
import com.cloud.user.UserVO; import com.cloud.user.UserVO;
import com.cloud.user.dao.UserAccountDao; import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.utils.Pair; import com.cloud.utils.Pair;
import org.apache.cloudstack.saml.SAMLPluginConstants;
import org.apache.cloudstack.saml.SAML2UserAuthenticator;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class SAML2UserAuthenticatorTest { public class SAML2UserAuthenticatorTest {
@ -69,7 +70,7 @@ public class SAML2UserAuthenticatorTest {
UserVO user = new UserVO(); UserVO user = new UserVO();
Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account); Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(account);
Mockito.when(userDao.getUser(Mockito.anyLong())).thenReturn(user); Mockito.lenient().when(userDao.getUser(Mockito.anyLong())).thenReturn(user);
Pair<Boolean, ActionOnFailedAuthentication> pair; Pair<Boolean, ActionOnFailedAuthentication> pair;
Map<String, Object[]> params = new HashMap<String, Object[]>(); Map<String, Object[]> params = new HashMap<String, Object[]>();

View File

@ -19,17 +19,18 @@
package org.apache.cloudstack.api.command; package org.apache.cloudstack.api.command;
import com.cloud.domain.DomainVO; import static org.mockito.ArgumentMatchers.anyString;
import com.cloud.domain.dao.DomainDao; import static org.mockito.ArgumentMatchers.nullable;
import com.cloud.user.Account;
import com.cloud.user.AccountService; import java.lang.reflect.Field;
import com.cloud.user.User; import java.net.InetAddress;
import com.cloud.user.UserAccountVO; import java.util.HashMap;
import com.cloud.user.UserVO; import java.util.Map;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao; import javax.servlet.http.HttpServletRequest;
import com.cloud.utils.HttpUtils; import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase; import javax.servlet.http.HttpSession;
import org.apache.cloudstack.api.ApiConstants; import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode; import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.ApiServerService; import org.apache.cloudstack.api.ApiServerService;
@ -45,13 +46,18 @@ import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import javax.servlet.http.HttpServletRequest; import com.cloud.domain.DomainVO;
import javax.servlet.http.HttpServletResponse; import com.cloud.domain.dao.DomainDao;
import javax.servlet.http.HttpSession; import com.cloud.user.Account;
import java.lang.reflect.Field; import com.cloud.user.AccountService;
import java.net.InetAddress; import com.cloud.user.User;
import java.util.HashMap; import com.cloud.user.UserAccountVO;
import java.util.Map; import com.cloud.user.UserVO;
import com.cloud.user.dao.UserAccountDao;
import com.cloud.user.dao.UserDao;
import com.cloud.utils.HttpUtils;
import junit.framework.TestCase;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ListAndSwitchSAMLAccountCmdTest extends TestCase { public class ListAndSwitchSAMLAccountCmdTest extends TestCase {
@ -91,8 +97,8 @@ public class ListAndSwitchSAMLAccountCmdTest extends TestCase {
Mockito.when(session.getAttribute("userid")).thenReturn(2L); Mockito.when(session.getAttribute("userid")).thenReturn(2L);
params.put(ApiConstants.USER_ID, new String[]{"2"}); params.put(ApiConstants.USER_ID, new String[]{"2"});
params.put(ApiConstants.DOMAIN_ID, new String[]{"1"}); params.put(ApiConstants.DOMAIN_ID, new String[]{"1"});
Mockito.when(userDao.findByUuid(Mockito.anyString())).thenReturn(new UserVO(2L)); Mockito.when(userDao.findByUuid(anyString())).thenReturn(new UserVO(2L));
Mockito.when(domainDao.findByUuid(Mockito.anyString())).thenReturn(new DomainVO()); Mockito.when(domainDao.findByUuid(anyString())).thenReturn(new DomainVO());
// Mock/field setup // Mock/field setup
ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd(); ListAndSwitchSAMLAccountCmd cmd = new ListAndSwitchSAMLAccountCmd();
@ -181,8 +187,9 @@ public class ListAndSwitchSAMLAccountCmdTest extends TestCase {
loginCmdResponse.setFirstName("firstName"); loginCmdResponse.setFirstName("firstName");
loginCmdResponse.setLastName("lastName"); loginCmdResponse.setLastName("lastName");
loginCmdResponse.setSessionKey("newSessionKeyString"); loginCmdResponse.setSessionKey("newSessionKeyString");
Mockito.when(apiServer.loginUser(Mockito.any(HttpSession.class), Mockito.anyString(), Mockito.anyString(), Mockito.when(apiServer.loginUser(nullable(HttpSession.class), nullable(String.class), nullable(String.class),
Mockito.anyLong(), Mockito.anyString(), Mockito.any(InetAddress.class), Mockito.anyMap())).thenReturn(loginCmdResponse); nullable(Long.class), nullable(String.class), nullable(InetAddress.class), nullable(Map.class))).thenReturn(loginCmdResponse);
Mockito.doNothing().when(resp).sendRedirect(nullable(String.class));
try { try {
cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp); cmd.authenticate("command", params, session, null, HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
} catch (ServerApiException exception) { } catch (ServerApiException exception) {
@ -190,7 +197,7 @@ public class ListAndSwitchSAMLAccountCmdTest extends TestCase {
} finally { } finally {
// accountService should have been called 4 times by now, for this case twice and 2 for cases above // accountService should have been called 4 times by now, for this case twice and 2 for cases above
Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong()); Mockito.verify(accountService, Mockito.times(4)).getUserAccountById(Mockito.anyLong());
Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString()); Mockito.verify(resp, Mockito.times(1)).sendRedirect(anyString());
} }
} }

View File

@ -20,6 +20,7 @@
package org.apache.cloudstack.api.command; package org.apache.cloudstack.api.command;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.mockito.ArgumentMatchers.nullable;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -51,7 +52,7 @@ import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.Spy; import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import org.opensaml.common.SAMLVersion; import org.opensaml.common.SAMLVersion;
import org.opensaml.saml2.core.Assertion; import org.opensaml.saml2.core.Assertion;
import org.opensaml.saml2.core.AttributeStatement; import org.opensaml.saml2.core.AttributeStatement;
@ -178,16 +179,16 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
providerMetadata.setSsoUrl("http://test.local"); providerMetadata.setSsoUrl("http://test.local");
providerMetadata.setSloUrl("http://test.local"); providerMetadata.setSloUrl("http://test.local");
Mockito.when(session.getAttribute(Mockito.anyString())).thenReturn(null); Mockito.lenient().when(session.getAttribute(Mockito.anyString())).thenReturn(null);
Mockito.when(domain.getId()).thenReturn(1L); Mockito.lenient().when(domain.getId()).thenReturn(1L);
Mockito.when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain); Mockito.lenient().when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain);
UserAccountVO user = new UserAccountVO(); UserAccountVO user = new UserAccountVO();
user.setId(1000L); user.setId(1000L);
Mockito.when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(user); Mockito.lenient().when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(user);
Mockito.when(apiServer.verifyUser(Mockito.anyLong())).thenReturn(false); Mockito.lenient().when(apiServer.verifyUser(nullable(Long.class))).thenReturn(false);
Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata); Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
Mockito.when(samlAuthManager.getIdPMetadata(Mockito.anyString())).thenReturn(providerMetadata); Mockito.when(samlAuthManager.getIdPMetadata(nullable(String.class))).thenReturn(providerMetadata);
Map<String, Object[]> params = new HashMap<String, Object[]>(); Map<String, Object[]> params = new HashMap<String, Object[]>();
@ -197,7 +198,7 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
// SSO SAMLResponse verification test, this should throw ServerApiException for auth failure // SSO SAMLResponse verification test, this should throw ServerApiException for auth failure
params.put(SAMLPluginConstants.SAML_RESPONSE, new String[]{"Some String"}); params.put(SAMLPluginConstants.SAML_RESPONSE, new String[]{"Some String"});
Mockito.stub(cmd.processSAMLResponse(Mockito.anyString())).toReturn(buildMockResponse()); Mockito.when(cmd.processSAMLResponse(Mockito.anyString())).thenReturn(buildMockResponse());
boolean failing = true; boolean failing = true;
try { try {
cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp); cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
@ -272,7 +273,7 @@ public class SAML2LoginAPIAuthenticatorCmdTest {
private UserAccountVO configureTestWhenFailToAuthenticateThrowExceptionOrRedirectToUrl(String entity, String configurationValue, Boolean isUserAuthorized) private UserAccountVO configureTestWhenFailToAuthenticateThrowExceptionOrRedirectToUrl(String entity, String configurationValue, Boolean isUserAuthorized)
throws IOException { throws IOException {
Mockito.when(samlAuthManager.isUserAuthorized(Mockito.anyLong(), Mockito.anyString())).thenReturn(isUserAuthorized); Mockito.when(samlAuthManager.isUserAuthorized(nullable(Long.class), nullable(String.class))).thenReturn(isUserAuthorized);
SAML2LoginAPIAuthenticatorCmd.saml2FailedLoginRedirectUrl = new ConfigKey<String>("Advanced", String.class, "saml2.failed.login.redirect.url", configurationValue, SAML2LoginAPIAuthenticatorCmd.saml2FailedLoginRedirectUrl = new ConfigKey<String>("Advanced", String.class, "saml2.failed.login.redirect.url", configurationValue,
"The URL to redirect the SAML2 login failed message (the default vaulue is empty).", true); "The URL to redirect the SAML2 login failed message (the default vaulue is empty).", true);
UserAccountVO userAccount = new UserAccountVO(); UserAccountVO userAccount = new UserAccountVO();

131
pom.xml
View File

@ -51,26 +51,26 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Build properties --> <!-- Build properties -->
<cs.jdk.version>1.8</cs.jdk.version> <cs.jdk.version>11</cs.jdk.version>
<cs.target.dir>target</cs.target.dir> <cs.target.dir>target</cs.target.dir>
<cs.replace.properties>build/replace.properties</cs.replace.properties> <cs.replace.properties>build/replace.properties</cs.replace.properties>
<!-- Plugins versions --> <!-- Plugins versions -->
<cs.antrun-plugin.version>1.8</cs.antrun-plugin.version> <cs.antrun-plugin.version>1.8</cs.antrun-plugin.version>
<cs.builder-helper-plugin.version>3.0.0</cs.builder-helper-plugin.version> <cs.builder-helper-plugin.version>3.0.0</cs.builder-helper-plugin.version>
<cs.checkstyle-plugin.version>3.0.0</cs.checkstyle-plugin.version> <cs.checkstyle-plugin.version>3.1.0</cs.checkstyle-plugin.version>
<cs.cobertura-plugin.version>2.7</cs.cobertura-plugin.version> <cs.cobertura-plugin.version>2.7</cs.cobertura-plugin.version>
<cs.compiler-plugin.version>3.7.0</cs.compiler-plugin.version> <cs.compiler-plugin.version>3.8.1</cs.compiler-plugin.version>
<cs.dependency-plugin.version>3.1.0</cs.dependency-plugin.version> <cs.dependency-plugin.version>3.1.1</cs.dependency-plugin.version>
<cs.failsafe-plugin.version>2.21.0</cs.failsafe-plugin.version> <cs.failsafe-plugin.version>2.22.2</cs.failsafe-plugin.version>
<cs.findbugs-plugin.version>3.0.5</cs.findbugs-plugin.version> <cs.findbugs-plugin.version>3.0.5</cs.findbugs-plugin.version>
<cs.jar-plugin.version>3.1.0</cs.jar-plugin.version> <cs.jar-plugin.version>3.2.0</cs.jar-plugin.version>
<cs.pmd-plugin.version>3.9.0</cs.pmd-plugin.version> <cs.pmd-plugin.version>3.12.0</cs.pmd-plugin.version>
<cs.project-info-plugin.version>2.9</cs.project-info-plugin.version> <cs.project-info-plugin.version>3.0.0</cs.project-info-plugin.version>
<cs.release-plugin.version>2.5.3</cs.release-plugin.version> <cs.release-plugin.version>2.5.3</cs.release-plugin.version>
<cs.resources-plugin.version>3.1.0</cs.resources-plugin.version> <cs.resources-plugin.version>3.1.0</cs.resources-plugin.version>
<cs.site-plugin.version>3.7.1</cs.site-plugin.version> <cs.site-plugin.version>3.8.2</cs.site-plugin.version>
<cs.surefire-plugin.version>2.21.0</cs.surefire-plugin.version> <cs.surefire-plugin.version>2.22.2</cs.surefire-plugin.version>
<!-- Logging versions --> <!-- Logging versions -->
<cs.log4j.version>1.2.17</cs.log4j.version> <cs.log4j.version>1.2.17</cs.log4j.version>
@ -78,95 +78,98 @@
<cs.logging.version>1.1.1</cs.logging.version> <cs.logging.version>1.1.1</cs.logging.version>
<!-- Apache Commons versions --> <!-- Apache Commons versions -->
<cs.codec.version>1.11</cs.codec.version> <cs.codec.version>1.14</cs.codec.version>
<cs.commons-collections.version>4.1</cs.commons-collections.version> <cs.commons-collections.version>4.4</cs.commons-collections.version>
<cs.commons-compress.version>1.15</cs.commons-compress.version> <cs.commons-compress.version>1.19</cs.commons-compress.version>
<cs.commons-exec.version>1.3</cs.commons-exec.version> <cs.commons-exec.version>1.3</cs.commons-exec.version>
<cs.commons-fileupload.version>1.3.3</cs.commons-fileupload.version> <cs.commons-fileupload.version>1.4</cs.commons-fileupload.version>
<cs.commons-httpclient.version>3.1</cs.commons-httpclient.version> <cs.commons-httpclient.version>3.1</cs.commons-httpclient.version>
<cs.commons-io.version>2.6</cs.commons-io.version> <cs.commons-io.version>2.6</cs.commons-io.version>
<cs.commons-lang3.version>3.6</cs.commons-lang3.version> <cs.commons-lang3.version>3.9</cs.commons-lang3.version>
<cs.commons-net.version>3.6</cs.commons-net.version> <cs.commons-net.version>3.6</cs.commons-net.version>
<cs.commons-validator.version>1.6</cs.commons-validator.version> <cs.commons-validator.version>1.6</cs.commons-validator.version>
<cs.configuration.version>1.10</cs.configuration.version> <cs.configuration.version>1.10</cs.configuration.version>
<cs.daemon.version>1.1.0</cs.daemon.version> <cs.daemon.version>1.2.2</cs.daemon.version>
<cs.dbcp.version>2.2.0</cs.dbcp.version> <cs.dbcp.version>2.7.0</cs.dbcp.version>
<cs.discovery.version>0.5</cs.discovery.version> <cs.discovery.version>0.5</cs.discovery.version>
<cs.lang.version>2.6</cs.lang.version> <cs.lang.version>2.6</cs.lang.version>
<cs.pool.version>2.4.3</cs.pool.version> <cs.pool.version>2.7.0</cs.pool.version>
<!-- Testing versions --> <!-- Testing versions -->
<!-- do not forget to also upgrade hamcrest library with junit --> <!-- do not forget to also upgrade hamcrest library with junit -->
<cs.dbunit.version>2.5.4</cs.dbunit.version> <cs.dbunit.version>2.5.4</cs.dbunit.version>
<cs.hamcrest.version>1.3</cs.hamcrest.version> <cs.hamcrest.version>1.3</cs.hamcrest.version>
<cs.junit.version>4.12</cs.junit.version> <cs.junit.version>4.13</cs.junit.version>
<cs.junit.dataprovider.version>1.13.1</cs.junit.dataprovider.version> <cs.junit.dataprovider.version>1.13.1</cs.junit.dataprovider.version>
<cs.guava-testlib.version>18.0</cs.guava-testlib.version> <cs.guava-testlib.version>18.0</cs.guava-testlib.version>
<cs.mockito.version>1.10.19</cs.mockito.version> <cs.mockito.version>3.2.4</cs.mockito.version>
<cs.powermock.version>1.6.4</cs.powermock.version> <cs.powermock.version>2.0.5</cs.powermock.version>
<cs.selenium.server.version>1.0-20081010.060147</cs.selenium.server.version> <cs.selenium.server.version>1.0-20081010.060147</cs.selenium.server.version>
<cs.selenium-java-client-driver.version>1.0.1</cs.selenium-java-client-driver.version> <cs.selenium-java-client-driver.version>1.0.1</cs.selenium-java-client-driver.version>
<cs.testng.version>6.1.1</cs.testng.version> <cs.testng.version>7.1.0</cs.testng.version>
<cs.wiremock.version>2.11.0</cs.wiremock.version> <cs.wiremock.version>2.11.0</cs.wiremock.version>
<cs.xercesImpl.version>2.11.0</cs.xercesImpl.version> <cs.xercesImpl.version>2.11.0</cs.xercesImpl.version>
<!-- Dependencies versions --> <!-- Dependencies versions -->
<cs.amqp-client.version>5.1.1</cs.amqp-client.version> <cs.amqp-client.version>5.8.0</cs.amqp-client.version>
<cs.apache-cloudstack-java-client.version>1.0.9</cs.apache-cloudstack-java-client.version> <cs.apache-cloudstack-java-client.version>1.0.9</cs.apache-cloudstack-java-client.version>
<cs.aspectjrt.version>1.7.1</cs.aspectjrt.version> <cs.aspectjrt.version>1.9.5</cs.aspectjrt.version>
<cs.aws.sdk.version>1.11.213</cs.aws.sdk.version> <cs.aws.sdk.version>1.11.717</cs.aws.sdk.version>
<cs.axiom.version>1.2.8</cs.axiom.version> <cs.axiom.version>1.2.8</cs.axiom.version>
<cs.axis.version>1.4</cs.axis.version> <cs.axis.version>1.4</cs.axis.version>
<cs.axis2.version>1.5.6</cs.axis2.version> <cs.axis2.version>1.5.6</cs.axis2.version>
<cs.batik.version>1.9.1</cs.batik.version> <cs.batik.version>1.12</cs.batik.version>
<cs.bcprov.version>1.59</cs.bcprov.version> <cs.bcprov.version>1.64</cs.bcprov.version>
<cs.cglib.version>3.2.5</cs.cglib.version> <cs.cglib.version>3.3.0</cs.cglib.version>
<cs.checkstyle-lib.version>8.7</cs.checkstyle-lib.version> <cs.checkstyle-lib.version>8.18</cs.checkstyle-lib.version>
<cs.cxf.version>3.2.0</cs.cxf.version> <cs.cxf.version>3.2.0</cs.cxf.version>
<cs.ehcache.version>2.6.11</cs.ehcache.version> <cs.ehcache.version>2.6.11</cs.ehcache.version>
<cs.globodns-client.version>0.0.23</cs.globodns-client.version> <cs.globodns-client.version>0.0.27</cs.globodns-client.version>
<cs.groovy.version>2.4.12</cs.groovy.version> <cs.groovy.version>2.4.17</cs.groovy.version>
<cs.gson.version>1.7.2</cs.gson.version> <cs.gson.version>1.7.2</cs.gson.version>
<cs.guava.version>23.6-jre</cs.guava.version> <cs.guava.version>28.2-jre</cs.guava.version>
<cs.httpclient.version>4.5.4</cs.httpclient.version> <cs.httpclient.version>4.5.11</cs.httpclient.version>
<cs.httpcore.version>4.4.8</cs.httpcore.version> <cs.httpcore.version>4.4.13</cs.httpcore.version>
<cs.influxdb-java.version>2.15</cs.influxdb-java.version> <cs.influxdb-java.version>2.17</cs.influxdb-java.version>
<cs.jackson.version>2.9.2</cs.jackson.version> <cs.jackson.version>2.9.2</cs.jackson.version>
<cs.jasypt.version>1.9.2</cs.jasypt.version> <cs.jasypt.version>1.9.3</cs.jasypt.version>
<cs.java-ipv6.version>0.16</cs.java-ipv6.version> <cs.java-ipv6.version>0.17</cs.java-ipv6.version>
<cs.javassist.version>3.22.0-GA</cs.javassist.version> <cs.javassist.version>3.26.0-GA</cs.javassist.version>
<cs.javadoc.version>2.10.3</cs.javadoc.version> <cs.javadoc.version>3.1.1</cs.javadoc.version>
<cs.javax.annotation.version>1.3.2</cs.javax.annotation.version>
<cs.jaxb.version>2.3.0</cs.jaxb.version>
<cs.jaxws.version>2.3.2</cs.jaxws.version>
<cs.jersey-bundle.version>1.19.4</cs.jersey-bundle.version> <cs.jersey-bundle.version>1.19.4</cs.jersey-bundle.version>
<cs.jetty.version>9.4.8.v20171121</cs.jetty.version> <cs.jetty.version>9.4.26.v20200117</cs.jetty.version>
<cs.jetty-maven-plugin.version>9.2.22.v20170606</cs.jetty-maven-plugin.version> <cs.jetty-maven-plugin.version>9.4.26.v20200117</cs.jetty-maven-plugin.version>
<cs.jna.version>4.0.0</cs.jna.version> <cs.jna.version>4.0.0</cs.jna.version>
<cs.joda-time.version>2.8.1</cs.joda-time.version> <cs.joda-time.version>2.8.1</cs.joda-time.version>
<cs.jpa.version>2.2.0</cs.jpa.version> <cs.jpa.version>2.2.1</cs.jpa.version>
<cs.jsch.version>0.1.54</cs.jsch.version> <cs.jsch.version>0.1.55</cs.jsch.version>
<cs.json.version>20090211</cs.json.version> <cs.json.version>20090211</cs.json.version>
<cs.jstl.version>1.2</cs.jstl.version> <cs.jstl.version>1.2</cs.jstl.version>
<cs.jstl-api.version>1.2.1</cs.jstl-api.version> <cs.jstl-api.version>1.2.1</cs.jstl-api.version>
<cs.kafka-clients.version>0.11.0.1</cs.kafka-clients.version> <cs.kafka-clients.version>0.11.0.3</cs.kafka-clients.version>
<cs.libvirt-java.version>0.5.1</cs.libvirt-java.version> <cs.libvirt-java.version>0.5.1</cs.libvirt-java.version>
<cs.mail.version>1.5.0-b01</cs.mail.version> <cs.mail.version>1.5.0-b01</cs.mail.version>
<cs.mysql.version>5.1.34</cs.mysql.version> <cs.mysql.version>8.0.19</cs.mysql.version>
<cs.neethi.version>2.0.4</cs.neethi.version> <cs.neethi.version>2.0.4</cs.neethi.version>
<cs.nitro.version>10.1</cs.nitro.version> <cs.nitro.version>10.1</cs.nitro.version>
<cs.opensaml.version>2.6.4</cs.opensaml.version> <cs.opensaml.version>2.6.4</cs.opensaml.version>
<cs.rados-java.version>0.5.0</cs.rados-java.version> <cs.rados-java.version>0.5.0</cs.rados-java.version>
<cs.rampart.version>1.5.1</cs.rampart.version> <cs.rampart.version>1.5.1</cs.rampart.version>
<cs.reflections.version>0.9.11</cs.reflections.version> <cs.reflections.version>0.9.12</cs.reflections.version>
<cs.servicemix.version>2.5.8_1</cs.servicemix.version> <cs.servicemix.version>3.3.3_1</cs.servicemix.version>
<cs.servlet.version>4.0.0</cs.servlet.version> <cs.servlet.version>4.0.1</cs.servlet.version>
<cs.tomcat-embed-core.version>8.0.30</cs.tomcat-embed-core.version> <cs.tomcat-embed-core.version>8.5.47</cs.tomcat-embed-core.version>
<cs.trilead.version>1.0.0-build221</cs.trilead.version> <cs.trilead.version>1.0.0-build222</cs.trilead.version>
<cs.vmware.api.version>6.7</cs.vmware.api.version> <cs.vmware.api.version>6.7</cs.vmware.api.version>
<cs.xapi.version>6.2.0-3.1</cs.xapi.version> <cs.xapi.version>6.2.0-3.1</cs.xapi.version>
<cs.xml-apis.version>1.4.01</cs.xml-apis.version> <cs.xml-apis.version>1.4.01</cs.xml-apis.version>
<cs.xmlrpc.version>3.1.3</cs.xmlrpc.version> <cs.xmlrpc.version>3.1.3</cs.xmlrpc.version>
<cs.xstream.version>1.4.10</cs.xstream.version> <cs.xstream.version>1.4.11.1</cs.xstream.version>
<cs.slf4j.version>1.7.22</cs.slf4j.version> <cs.slf4j.version>1.7.29</cs.slf4j.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version> <org.springframework.version>5.2.3.RELEASE</org.springframework.version>
</properties> </properties>
<distributionManagement> <distributionManagement>
@ -419,7 +422,7 @@
<groupId>mysql</groupId> <groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId> <artifactId>mysql-connector-java</artifactId>
<version>${cs.mysql.version}</version> <version>${cs.mysql.version}</version>
<scope>provided,test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>net.sf.ehcache</groupId> <groupId>net.sf.ehcache</groupId>
@ -645,7 +648,7 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.mockito</groupId> <groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId> <artifactId>mockito-core</artifactId>
<version>${cs.mockito.version}</version> <version>${cs.mockito.version}</version>
<scope>test</scope> <scope>test</scope>
<exclusions> <exclusions>
@ -675,12 +678,19 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId> <artifactId>powermock-core</artifactId>
<version>${cs.powermock.version}</version> <version>${cs.powermock.version}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.powermock</groupId> <groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId> <artifactId>powermock-module-junit4</artifactId>
<version>${cs.powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${cs.powermock.version}</version> <version>${cs.powermock.version}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
@ -1002,7 +1012,12 @@
<fork>true</fork> <fork>true</fork>
<meminitial>128m</meminitial> <meminitial>128m</meminitial>
<maxmem>512m</maxmem> <maxmem>512m</maxmem>
<compilerArgument>-XDignore.symbol.file=true</compilerArgument> <compilerArgs>
<arg>-XDignore.symbol.file=true</arg>
<arg>--add-opens=java.base/java.lang=ALL-UNNAMED</arg>
<arg>--add-exports=java.base/sun.security.x509=ALL-UNNAMED</arg>
<arg>--add-exports=java.base/sun.security.provider=ALL-UNNAMED</arg>
</compilerArgs>
</configuration> </configuration>
</plugin> </plugin>
<plugin> <plugin>

View File

@ -55,7 +55,7 @@ dbHost="localhost"
dbUser="root" dbUser="root"
dbPassword= dbPassword=
dbPort=3306 dbPort=3306
jasypt='/usr/share/cloudstack-common/lib/jasypt-1.9.2.jar' jasypt='/usr/share/cloudstack-common/lib/jasypt-1.9.3.jar'
# check if first parameter is not a dash (-) then print the usage block # check if first parameter is not a dash (-) then print the usage block
if [[ ! $@ =~ ^\-.+ ]]; then if [[ ! $@ =~ ^\-.+ ]]; then
@ -275,4 +275,4 @@ echo "$ext.virtualsize=$vrtmpltsize" >> $destdir/template.properties
echo "virtualsize=$vrtmpltsize" >> $destdir/template.properties echo "virtualsize=$vrtmpltsize" >> $destdir/template.properties
echo "$ext.size=$tmpltsize" >> $destdir/template.properties echo "$ext.size=$tmpltsize" >> $destdir/template.properties
echo "Successfully installed system VM template $tmpltimg and template.properties to $destdir" echo "Successfully installed system VM template $tmpltimg and template.properties to $destdir"

View File

@ -56,6 +56,11 @@ for caChain in $(ls cloudca.*); do
done done
rm -f cloudca.* rm -f cloudca.*
# Stop cloud service in systemvm
if [ "$MODE" == "ssh" ] && [ -f $SYSTEM_FILE ]; then
systemctl stop cloud > /dev/null 2>&1
fi
# Import private key if available # Import private key if available
if [ ! -z "${PRIVKEY// }" ]; then if [ ! -z "${PRIVKEY// }" ]; then
echo "$PRIVKEY" > "$PRIVKEY_FILE" echo "$PRIVKEY" > "$PRIVKEY_FILE"
@ -93,6 +98,11 @@ if [ -f "$SYSTEM_FILE" ]; then
chmod 755 /usr/local/share/ca-certificates/cloudstack chmod 755 /usr/local/share/ca-certificates/cloudstack
chmod 644 /usr/local/share/ca-certificates/cloudstack/ca.crt chmod 644 /usr/local/share/ca-certificates/cloudstack/ca.crt
update-ca-certificates > /dev/null 2>&1 || true update-ca-certificates > /dev/null 2>&1 || true
# Ensure cloud service is running in systemvm
if [ "$MODE" == "ssh" ]; then
systemctl start cloud > /dev/null 2>&1
fi
fi fi
# Fix file permission # Fix file permission

View File

@ -27,6 +27,10 @@
<version>4.14.0.0-SNAPSHOT</version> <version>4.14.0.0-SNAPSHOT</version>
</parent> </parent>
<dependencies> <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency> <dependency>
<groupId>commons-io</groupId> <groupId>commons-io</groupId>
<artifactId>commons-io</artifactId> <artifactId>commons-io</artifactId>

View File

@ -16,10 +16,16 @@
// under the License. // under the License.
package com.cloud.api; package com.cloud.api;
import com.cloud.domain.DomainVO; import static org.junit.Assert.assertEquals;
import com.cloud.usage.UsageVO; import static org.junit.Assert.assertTrue;
import com.cloud.user.AccountVO; import static org.mockito.Matchers.anyLong;
import com.cloud.vm.NicSecondaryIp; import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.cloudstack.api.response.NicSecondaryIpResponse; import org.apache.cloudstack.api.response.NicSecondaryIpResponse;
import org.apache.cloudstack.api.response.UsageRecordResponse; import org.apache.cloudstack.api.response.UsageRecordResponse;
@ -33,16 +39,10 @@ import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunner;
import java.lang.reflect.Field; import com.cloud.domain.DomainVO;
import java.text.ParseException; import com.cloud.usage.UsageVO;
import java.text.SimpleDateFormat; import com.cloud.user.AccountVO;
import java.util.Date; import com.cloud.vm.NicSecondaryIp;
import java.util.TimeZone;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.when;
@RunWith(PowerMockRunner.class) @RunWith(PowerMockRunner.class)
@PrepareForTest(ApiDBUtils.class) @PrepareForTest(ApiDBUtils.class)
@ -85,8 +85,8 @@ public class ApiResponseHelperTest {
public void testUsageRecordResponse(){ public void testUsageRecordResponse(){
//Creating the usageVO object to be passed to the createUsageResponse. //Creating the usageVO object to be passed to the createUsageResponse.
Long zoneId = null; Long zoneId = null;
Long accountId = null; Long accountId = 1L;
Long domainId = null; Long domainId = 1L;
String Description = "Test Object"; String Description = "Test Object";
String usageDisplay = " "; String usageDisplay = " ";
int usageType = -1; int usageType = -1;

View File

@ -16,16 +16,27 @@
// under the License. // under the License.
package com.cloud.api; package com.cloud.api;
import static org.mockito.ArgumentMatchers.nullable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.auth.APIAuthenticationManager; import org.apache.cloudstack.api.auth.APIAuthenticationManager;
import org.apache.cloudstack.api.auth.APIAuthenticationType; import org.apache.cloudstack.api.auth.APIAuthenticationType;
import org.apache.cloudstack.api.auth.APIAuthenticator; import org.apache.cloudstack.api.auth.APIAuthenticator;
import com.cloud.server.ManagementServer;
import com.cloud.user.Account;
import com.cloud.user.AccountService;
import com.cloud.user.User;
import org.apache.cloudstack.api.ApiConstants;
import org.junit.After; import org.junit.After;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Before; import org.junit.Before;
@ -33,21 +44,12 @@ import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.http.HttpServletRequest; import com.cloud.server.ManagementServer;
import javax.servlet.http.HttpServletResponse; import com.cloud.user.Account;
import javax.servlet.http.HttpSession; import com.cloud.user.AccountService;
import com.cloud.user.User;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ApiServletTest { public class ApiServletTest {
@ -103,7 +105,7 @@ public class ApiServletTest {
accountMgrField.set(servlet, accountService); accountMgrField.set(servlet, accountService);
Mockito.when(authManager.getAPIAuthenticator(Mockito.anyString())).thenReturn(authenticator); Mockito.when(authManager.getAPIAuthenticator(Mockito.anyString())).thenReturn(authenticator);
Mockito.when(authenticator.authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class), Mockito.lenient().when(authenticator.authenticate(Mockito.anyString(), Mockito.anyMap(), Mockito.isA(HttpSession.class),
Mockito.same(InetAddress.getByName("127.0.0.1")), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletRequest.class), Mockito.isA(HttpServletResponse.class))).thenReturn("{\"loginresponse\":{}"); Mockito.same(InetAddress.getByName("127.0.0.1")), Mockito.anyString(), Mockito.isA(StringBuilder.class), Mockito.isA(HttpServletRequest.class), Mockito.isA(HttpServletResponse.class))).thenReturn("{\"loginresponse\":{}");
Field authManagerField = ApiServlet.class.getDeclaredField("authManager"); Field authManagerField = ApiServlet.class.getDeclaredField("authManager");
@ -124,7 +126,7 @@ public class ApiServletTest {
Field smsField = ApiDBUtils.class.getDeclaredField("s_ms"); Field smsField = ApiDBUtils.class.getDeclaredField("s_ms");
smsField.setAccessible(true); smsField.setAccessible(true);
smsField.set(null, managementServer); smsField.set(null, managementServer);
Mockito.when(managementServer.getVersion()).thenReturn( Mockito.lenient().when(managementServer.getVersion()).thenReturn(
"LATEST-AND-GREATEST"); "LATEST-AND-GREATEST");
} }
@ -173,7 +175,7 @@ public class ApiServletTest {
@Test @Test
public void processRequestInContextUnauthorizedGET() { public void processRequestInContextUnauthorizedGET() {
Mockito.when(request.getMethod()).thenReturn("GET"); Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when( Mockito.lenient().when(
apiServer.verifyRequest(Mockito.anyMap(), Mockito.anyLong(), Mockito.any(InetAddress.class))) apiServer.verifyRequest(Mockito.anyMap(), Mockito.anyLong(), Mockito.any(InetAddress.class)))
.thenReturn(false); .thenReturn(false);
servlet.processRequestInContext(request, response); servlet.processRequestInContext(request, response);
@ -188,7 +190,7 @@ public class ApiServletTest {
public void processRequestInContextAuthorizedGet() { public void processRequestInContextAuthorizedGet() {
Mockito.when(request.getMethod()).thenReturn("GET"); Mockito.when(request.getMethod()).thenReturn("GET");
Mockito.when( Mockito.when(
apiServer.verifyRequest(Mockito.anyMap(), Mockito.anyLong(), Mockito.any(InetAddress.class))) apiServer.verifyRequest(nullable(Map.class), nullable(Long.class), nullable(InetAddress.class)))
.thenReturn(true); .thenReturn(true);
servlet.processRequestInContext(request, response); servlet.processRequestInContext(request, response);
Mockito.verify(response).setStatus(HttpServletResponse.SC_OK); Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

View File

@ -16,8 +16,6 @@
// under the License. // under the License.
package com.cloud.api.query.dao; package com.cloud.api.query.dao;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -32,13 +30,11 @@ import org.junit.runner.RunWith;
import org.mockito.InjectMocks; import org.mockito.InjectMocks;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.junit.MockitoJUnitRunner;
import com.cloud.api.query.vo.ResourceTagJoinVO;
import com.cloud.api.query.vo.SecurityGroupJoinVO; import com.cloud.api.query.vo.SecurityGroupJoinVO;
import com.cloud.network.security.SecurityGroupVMMapVO; import com.cloud.network.security.SecurityGroupVMMapVO;
import com.cloud.network.security.dao.SecurityGroupVMMapDao; import com.cloud.network.security.dao.SecurityGroupVMMapDao;
import com.cloud.server.ResourceTag.ResourceObjectType;
import com.cloud.user.Account; import com.cloud.user.Account;
import com.cloud.vm.UserVmVO; import com.cloud.vm.UserVmVO;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
@ -98,8 +94,6 @@ public class SecurityGroupJoinDaoImplTest extends TestCase {
securityGroupVmMap_two.add(securityGroupVMMapVOone); securityGroupVmMap_two.add(securityGroupVMMapVOone);
securityGroupVmMap_two.add(securityGroupVMMapVOtwo); securityGroupVmMap_two.add(securityGroupVMMapVOtwo);
// Mock the resource tags to return an empty list.
when(_resourceTagJoinDao.listBy(anyString(), any(ResourceObjectType.class))).thenReturn(new ArrayList<ResourceTagJoinVO>());
// Mock the listBySecurityGroup method to return a specified list when being called. // Mock the listBySecurityGroup method to return a specified list when being called.
when(_securityGroupVMMapDao.listBySecurityGroup(1L)).thenReturn(securityGroupVmMap_empty); when(_securityGroupVMMapDao.listBySecurityGroup(1L)).thenReturn(securityGroupVmMap_empty);

View File

@ -156,7 +156,7 @@ public class HighAvailabilityManagerImplTest {
public void scheduleRestartForVmsOnHost() { public void scheduleRestartForVmsOnHost() {
Mockito.when(hostVO.getType()).thenReturn(Host.Type.Routing); Mockito.when(hostVO.getType()).thenReturn(Host.Type.Routing);
Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.KVM);
Mockito.when(_instanceDao.listByHostId(42l)).thenReturn(Arrays.asList(Mockito.mock(VMInstanceVO.class))); Mockito.lenient().when(_instanceDao.listByHostId(42l)).thenReturn(Arrays.asList(Mockito.mock(VMInstanceVO.class)));
Mockito.when(_podDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(HostPodVO.class)); Mockito.when(_podDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(HostPodVO.class));
Mockito.when(_dcDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(DataCenterVO.class)); Mockito.when(_dcDao.findById(Mockito.anyLong())).thenReturn(Mockito.mock(DataCenterVO.class));
@ -178,7 +178,7 @@ public class HighAvailabilityManagerImplTest {
Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.XenServer); Mockito.when(hostVO.getHypervisorType()).thenReturn(HypervisorType.XenServer);
List<VMInstanceVO> vms = new ArrayList<VMInstanceVO>(); List<VMInstanceVO> vms = new ArrayList<VMInstanceVO>();
VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class); VMInstanceVO vm1 = Mockito.mock(VMInstanceVO.class);
Mockito.when(vm1.getHostId()).thenReturn(1l); Mockito.lenient().when(vm1.getHostId()).thenReturn(1l);
Mockito.when(vm1.getInstanceName()).thenReturn("i-2-3-VM"); Mockito.when(vm1.getInstanceName()).thenReturn("i-2-3-VM");
Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User); Mockito.when(vm1.getType()).thenReturn(VirtualMachine.Type.User);
Mockito.when(vm1.isHaEnabled()).thenReturn(true); Mockito.when(vm1.isHaEnabled()).thenReturn(true);

View File

@ -102,16 +102,16 @@ public class KVMFencerTest {
Mockito.when(host.getClusterId()).thenReturn(1l); Mockito.when(host.getClusterId()).thenReturn(1l);
Mockito.when(host.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(host.getHypervisorType()).thenReturn(HypervisorType.KVM);
Mockito.when(host.getStatus()).thenReturn(Status.Up); Mockito.when(host.getStatus()).thenReturn(Status.Up);
Mockito.when(host.getDataCenterId()).thenReturn(1l); Mockito.lenient().when(host.getDataCenterId()).thenReturn(1l);
Mockito.when(host.getPodId()).thenReturn(1l); Mockito.lenient().when(host.getPodId()).thenReturn(1l);
Mockito.when(host.getId()).thenReturn(1l); Mockito.when(host.getId()).thenReturn(1l);
HostVO secondHost = Mockito.mock(HostVO.class); HostVO secondHost = Mockito.mock(HostVO.class);
Mockito.when(secondHost.getClusterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getClusterId()).thenReturn(1l);
Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM);
Mockito.when(secondHost.getStatus()).thenReturn(Status.Up); Mockito.when(secondHost.getStatus()).thenReturn(Status.Up);
Mockito.when(secondHost.getDataCenterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getDataCenterId()).thenReturn(1l);
Mockito.when(secondHost.getPodId()).thenReturn(1l); Mockito.lenient().when(secondHost.getPodId()).thenReturn(1l);
Mockito.when(host.getId()).thenReturn(2l); Mockito.when(host.getId()).thenReturn(2l);
VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class); VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class);
@ -135,11 +135,11 @@ public class KVMFencerTest {
Mockito.when(host.getId()).thenReturn(1l); Mockito.when(host.getId()).thenReturn(1l);
HostVO secondHost = Mockito.mock(HostVO.class); HostVO secondHost = Mockito.mock(HostVO.class);
Mockito.when(secondHost.getClusterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getClusterId()).thenReturn(1l);
Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM);
Mockito.when(secondHost.getStatus()).thenReturn(Status.Up); Mockito.when(secondHost.getStatus()).thenReturn(Status.Up);
Mockito.when(secondHost.getDataCenterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getDataCenterId()).thenReturn(1l);
Mockito.when(secondHost.getPodId()).thenReturn(1l); Mockito.lenient().when(secondHost.getPodId()).thenReturn(1l);
Mockito.when(host.getId()).thenReturn(2l); Mockito.when(host.getId()).thenReturn(2l);
VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class); VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class);
@ -162,11 +162,11 @@ public class KVMFencerTest {
Mockito.when(host.getId()).thenReturn(1l); Mockito.when(host.getId()).thenReturn(1l);
HostVO secondHost = Mockito.mock(HostVO.class); HostVO secondHost = Mockito.mock(HostVO.class);
Mockito.when(secondHost.getClusterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getClusterId()).thenReturn(1l);
Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM); Mockito.when(secondHost.getHypervisorType()).thenReturn(HypervisorType.KVM);
Mockito.when(secondHost.getStatus()).thenReturn(Status.Up); Mockito.when(secondHost.getStatus()).thenReturn(Status.Up);
Mockito.when(secondHost.getDataCenterId()).thenReturn(1l); Mockito.lenient().when(secondHost.getDataCenterId()).thenReturn(1l);
Mockito.when(secondHost.getPodId()).thenReturn(1l); Mockito.lenient().when(secondHost.getPodId()).thenReturn(1l);
Mockito.when(host.getId()).thenReturn(2l); Mockito.when(host.getId()).thenReturn(2l);
VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class); VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class);
@ -181,15 +181,15 @@ public class KVMFencerTest {
@Test @Test
public void testWithSingleNotKVM() { public void testWithSingleNotKVM() {
HostVO host = Mockito.mock(HostVO.class); HostVO host = Mockito.mock(HostVO.class);
Mockito.when(host.getClusterId()).thenReturn(1l); Mockito.lenient().when(host.getClusterId()).thenReturn(1l);
Mockito.when(host.getHypervisorType()).thenReturn(HypervisorType.Any); Mockito.when(host.getHypervisorType()).thenReturn(HypervisorType.Any);
Mockito.when(host.getStatus()).thenReturn(Status.Down); Mockito.lenient().when(host.getStatus()).thenReturn(Status.Down);
Mockito.when(host.getId()).thenReturn(1l); Mockito.lenient().when(host.getId()).thenReturn(1l);
Mockito.when(host.getDataCenterId()).thenReturn(1l); Mockito.lenient().when(host.getDataCenterId()).thenReturn(1l);
Mockito.when(host.getPodId()).thenReturn(1l); Mockito.lenient().when(host.getPodId()).thenReturn(1l);
VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class); VirtualMachine virtualMachine = Mockito.mock(VirtualMachine.class);
Mockito.when(resourceManager.listAllHostsInCluster(1l)).thenReturn(Collections.singletonList(host)); Mockito.lenient().when(resourceManager.listAllHostsInCluster(1l)).thenReturn(Collections.singletonList(host));
Assert.assertNull(fencer.fenceOff(virtualMachine, host)); Assert.assertNull(fencer.fenceOff(virtualMachine, host));
} }

View File

@ -79,20 +79,20 @@ public class KVMGuruTest {
Mockito.when(vmProfile.getVirtualMachine()).thenReturn(vm); Mockito.when(vmProfile.getVirtualMachine()).thenReturn(vm);
Mockito.when(vm.getHostId()).thenReturn(hostId); Mockito.when(vm.getHostId()).thenReturn(hostId);
Mockito.when(hostDao.findById(hostId)).thenReturn(host); Mockito.when(hostDao.findById(hostId)).thenReturn(host);
Mockito.when(host.getCpus()).thenReturn(3); Mockito.lenient().when(host.getCpus()).thenReturn(3);
Mockito.when(host.getSpeed()).thenReturn(1995L); Mockito.when(host.getSpeed()).thenReturn(1995L);
Mockito.when(vmTO.getMaxSpeed()).thenReturn(500); Mockito.when(vmTO.getMaxSpeed()).thenReturn(500);
Mockito.when(serviceOffering.getId()).thenReturn(offeringId); Mockito.lenient().when(serviceOffering.getId()).thenReturn(offeringId);
Mockito.when(vmProfile.getServiceOffering()).thenReturn(serviceOffering); Mockito.lenient().when(vmProfile.getServiceOffering()).thenReturn(serviceOffering);
Mockito.when(detail1.getName()).thenReturn(detail1Key); Mockito.lenient().when(detail1.getName()).thenReturn(detail1Key);
Mockito.when(detail1.getValue()).thenReturn(detail1Value); Mockito.lenient().when(detail1.getValue()).thenReturn(detail1Value);
Mockito.when(detail1.getResourceId()).thenReturn(offeringId); Mockito.lenient().when(detail1.getResourceId()).thenReturn(offeringId);
Mockito.when(detail2.getName()).thenReturn(detail2Key); Mockito.lenient().when(detail2.getName()).thenReturn(detail2Key);
Mockito.when(detail2.getResourceId()).thenReturn(offeringId); Mockito.lenient().when(detail2.getResourceId()).thenReturn(offeringId);
Mockito.when(detail2.getValue()).thenReturn(detail2Value); Mockito.lenient().when(detail2.getValue()).thenReturn(detail2Value);
Mockito.when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn( Mockito.lenient().when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn(
Arrays.asList(detail1, detail2)); Arrays.asList(detail1, detail2));
} }

View File

@ -107,13 +107,13 @@ public class DpdkHelperImplTest {
Mockito.when(dpdkVhostUserModeDetailVO.getName()).thenReturn(DpdkHelper.DPDK_VHOST_USER_MODE); Mockito.when(dpdkVhostUserModeDetailVO.getName()).thenReturn(DpdkHelper.DPDK_VHOST_USER_MODE);
Mockito.when(dpdkVhostUserModeDetailVO.getValue()).thenReturn(dpdkVhostMode); Mockito.when(dpdkVhostUserModeDetailVO.getValue()).thenReturn(dpdkVhostMode);
Mockito.when(dpdkVhostUserModeDetailVO.getResourceId()).thenReturn(offeringId); Mockito.lenient().when(dpdkVhostUserModeDetailVO.getResourceId()).thenReturn(offeringId);
Mockito.when(dpdkNumaDetailVO.getName()).thenReturn(DpdkHelper.DPDK_NUMA); Mockito.when(dpdkNumaDetailVO.getName()).thenReturn(DpdkHelper.DPDK_NUMA);
Mockito.when(dpdkNumaDetailVO.getResourceId()).thenReturn(offeringId); Mockito.lenient().when(dpdkNumaDetailVO.getResourceId()).thenReturn(offeringId);
Mockito.when(dpdkNumaDetailVO.getValue()).thenReturn(dpdkNumaValue); Mockito.lenient().when(dpdkNumaDetailVO.getValue()).thenReturn(dpdkNumaValue);
Mockito.when(dpdkHugePagesDetailVO.getName()).thenReturn(DpdkHelper.DPDK_HUGE_PAGES); Mockito.when(dpdkHugePagesDetailVO.getName()).thenReturn(DpdkHelper.DPDK_HUGE_PAGES);
Mockito.when(dpdkHugePagesDetailVO.getResourceId()).thenReturn(offeringId); Mockito.lenient().when(dpdkHugePagesDetailVO.getResourceId()).thenReturn(offeringId);
Mockito.when(dpdkHugePagesDetailVO.getValue()).thenReturn(dpdkHugePagesValue); Mockito.lenient().when(dpdkHugePagesDetailVO.getValue()).thenReturn(dpdkHugePagesValue);
Mockito.when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn( Mockito.when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn(
Arrays.asList(dpdkNumaDetailVO, dpdkHugePagesDetailVO, dpdkVhostUserModeDetailVO)); Arrays.asList(dpdkNumaDetailVO, dpdkHugePagesDetailVO, dpdkVhostUserModeDetailVO));
@ -132,9 +132,9 @@ public class DpdkHelperImplTest {
Mockito.when(vmInstanceVO.getId()).thenReturn(vmId); Mockito.when(vmInstanceVO.getId()).thenReturn(vmId);
Mockito.when(dpdkNumaVmDetail.getName()).thenReturn(DpdkHelper.DPDK_NUMA); Mockito.when(dpdkNumaVmDetail.getName()).thenReturn(DpdkHelper.DPDK_NUMA);
Mockito.when(dpdkNumaVmDetail.getValue()).thenReturn(dpdkNumaConf); Mockito.lenient().when(dpdkNumaVmDetail.getValue()).thenReturn(dpdkNumaConf);
Mockito.when(dpdkHugePagesVmDetail.getName()).thenReturn(DpdkHelper.DPDK_HUGE_PAGES); Mockito.when(dpdkHugePagesVmDetail.getName()).thenReturn(DpdkHelper.DPDK_HUGE_PAGES);
Mockito.when(dpdkHugePagesVmDetail.getValue()).thenReturn(dpdkHugePagesConf); Mockito.lenient().when(dpdkHugePagesVmDetail.getValue()).thenReturn(dpdkHugePagesConf);
Mockito.when(userVmDetailsDao.listDetails(vmId)).thenReturn(Arrays.asList(dpdkNumaVmDetail, dpdkHugePagesVmDetail)); Mockito.when(userVmDetailsDao.listDetails(vmId)).thenReturn(Arrays.asList(dpdkNumaVmDetail, dpdkHugePagesVmDetail));
} }
@ -148,13 +148,13 @@ public class DpdkHelperImplTest {
@Test @Test
public void testSetDpdkVhostUserModeInvalidDetail() { public void testSetDpdkVhostUserModeInvalidDetail() {
Mockito.when(dpdkVhostUserModeDetailVO.getValue()).thenReturn("serverrrr"); Mockito.lenient().when(dpdkVhostUserModeDetailVO.getValue()).thenReturn("serverrrr");
Mockito.verify(vmTO, Mockito.never()).addExtraConfig(Mockito.anyString(), Mockito.anyString()); Mockito.verify(vmTO, Mockito.never()).addExtraConfig(Mockito.anyString(), Mockito.anyString());
} }
@Test @Test
public void testSetDpdkVhostUserModeNotExistingDetail() { public void testSetDpdkVhostUserModeNotExistingDetail() {
Mockito.when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn( Mockito.lenient().when(serviceOfferingDetailsDao.listDetails(offeringId)).thenReturn(
Arrays.asList(dpdkNumaDetailVO, dpdkHugePagesDetailVO)); Arrays.asList(dpdkNumaDetailVO, dpdkHugePagesDetailVO));
Mockito.verify(vmTO, Mockito.never()).addExtraConfig(Mockito.anyString(), Mockito.anyString()); Mockito.verify(vmTO, Mockito.never()).addExtraConfig(Mockito.anyString(), Mockito.anyString());
} }

View File

@ -17,22 +17,26 @@
package com.cloud.network; package com.cloud.network;
import junit.framework.Assert; import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.log4j.Logger; import org.apache.log4j.Logger;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.mockito.Matchers;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
import org.apache.cloudstack.acl.ControlledEntity.ACLType;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.DataCenter.NetworkType;
import com.cloud.dc.DataCenterVO; import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao; import com.cloud.dc.dao.DataCenterDao;
@ -58,12 +62,7 @@ import com.cloud.utils.db.DB;
import com.cloud.utils.db.TransactionLegacy; import com.cloud.utils.db.TransactionLegacy;
import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.CloudRuntimeException;
import static org.junit.Assert.fail; import junit.framework.Assert;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;
//@Ignore("Requires database to be set up") //@Ignore("Requires database to be set up")
public class CreatePrivateNetworkTest { public class CreatePrivateNetworkTest {
@ -105,6 +104,7 @@ public class CreatePrivateNetworkTest {
NetworkOfferingVO ntwkOff = NetworkOfferingVO ntwkOff =
new NetworkOfferingVO("offer", "fakeOffer", TrafficType.Guest, true, true, null, null, false, null, null, GuestType.Isolated, false, false, false, false, new NetworkOfferingVO("offer", "fakeOffer", TrafficType.Guest, true, true, null, null, false, null, null, GuestType.Isolated, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false); false, false, false, false, false, false, false, false, false, false, false, false);
when(networkService._networkOfferingDao.findById(anyLong())).thenReturn(ntwkOff); when(networkService._networkOfferingDao.findById(anyLong())).thenReturn(ntwkOff);
List<NetworkOfferingVO> netofferlist = new ArrayList<NetworkOfferingVO>(); List<NetworkOfferingVO> netofferlist = new ArrayList<NetworkOfferingVO>();
netofferlist.add(ntwkOff); netofferlist.add(ntwkOff);
@ -121,10 +121,9 @@ public class CreatePrivateNetworkTest {
Network net = Network net =
new NetworkVO(1L, TrafficType.Guest, Mode.None, BroadcastDomainType.Vlan, 1L, 1L, 1L, 1L, "bla", "fake", "eet.net", GuestType.Isolated, 1L, 1L, new NetworkVO(1L, TrafficType.Guest, Mode.None, BroadcastDomainType.Vlan, 1L, 1L, 1L, 1L, "bla", "fake", "eet.net", GuestType.Isolated, 1L, 1L,
ACLType.Account, false, 1L, false); ACLType.Account, false, 1L, false);
when( when(networkService._networkMgr.createGuestNetwork(eq(ntwkOff.getId()), eq("bla"), eq("fake"), eq("10.1.1.1"), eq("10.1.1.0/24"), nullable(String.class), nullable(Boolean.class), nullable(String.class),
networkService._networkMgr.createGuestNetwork(eq(ntwkOff.getId()), eq("bla"), eq("fake"), eq("10.1.1.1"), eq("10.1.1.0/24"), anyString(), anyBoolean(), anyString(), eq(account), nullable(Long.class), eq(physicalNetwork), eq(physicalNetwork.getDataCenterId()), eq(ACLType.Account), nullable(Boolean.class), eq(1L), nullable(String.class), nullable(String.class),
eq(account), anyLong(), eq(physicalNetwork), eq(physicalNetwork.getDataCenterId()), eq(ACLType.Account), anyBoolean(), eq(1L), anyString(), anyString(), nullable(Boolean.class), nullable(String.class), nullable(Network.PVlanType.class), nullable(String.class))).thenReturn(net);
anyBoolean(), anyString(), Matchers.any(), anyString())).thenReturn(net);
when(networkService._privateIpDao.findByIpAndSourceNetworkId(net.getId(), "10.1.1.2")).thenReturn(null); when(networkService._privateIpDao.findByIpAndSourceNetworkId(net.getId(), "10.1.1.2")).thenReturn(null);
when(networkService._privateIpDao.findByIpAndSourceNetworkIdAndVpcId(eq(1L), anyString(), eq(1L))).thenReturn(null); when(networkService._privateIpDao.findByIpAndSourceNetworkIdAndVpcId(eq(1L), anyString(), eq(1L))).thenReturn(null);

View File

@ -26,7 +26,6 @@ import java.util.Collections;
import javax.inject.Inject; import javax.inject.Inject;
import com.cloud.host.Host;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.junit.Assert; import org.junit.Assert;
@ -45,6 +44,7 @@ import com.cloud.dc.dao.DataCenterDao;
import com.cloud.dc.dao.HostPodDao; import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao; import com.cloud.dc.dao.VlanDao;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
import com.cloud.host.Host;
import com.cloud.host.HostVO; import com.cloud.host.HostVO;
import com.cloud.host.dao.HostDao; import com.cloud.host.dao.HostDao;
import com.cloud.host.dao.HostDetailsDao; import com.cloud.host.dao.HostDetailsDao;
@ -232,8 +232,8 @@ public class ExternalLoadBalancerDeviceManagerImplTest {
public void testUsageTask() { public void testUsageTask() {
ExternalDeviceUsageManagerImpl.ExternalDeviceNetworkUsageTask usageTask = Mockito ExternalDeviceUsageManagerImpl.ExternalDeviceNetworkUsageTask usageTask = Mockito
.mock(ExternalDeviceUsageManagerImpl.ExternalDeviceNetworkUsageTask.class); .mock(ExternalDeviceUsageManagerImpl.ExternalDeviceNetworkUsageTask.class);
Mockito.when(_hostDao.listByType(Host.Type.ExternalFirewall)).thenReturn(new ArrayList<HostVO>()); Mockito.lenient().when(_hostDao.listByType(Host.Type.ExternalFirewall)).thenReturn(new ArrayList<HostVO>());
Mockito.when(_hostDao.listByType(Host.Type.ExternalLoadBalancer)).thenReturn(new ArrayList<HostVO>()); Mockito.lenient().when(_hostDao.listByType(Host.Type.ExternalLoadBalancer)).thenReturn(new ArrayList<HostVO>());
usageTask.runInContext(); usageTask.runInContext();
Mockito.verify(usageTask, Mockito.times(0)).runExternalDeviceNetworkUsageTask(); Mockito.verify(usageTask, Mockito.times(0)).runExternalDeviceNetworkUsageTask();
} }

View File

@ -21,6 +21,7 @@ import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ -93,8 +94,8 @@ public class IpAddressManagerTest {
public void testGetStaticNatSourceIps() { public void testGetStaticNatSourceIps() {
String publicIpAddress = "192.168.1.3"; String publicIpAddress = "192.168.1.3";
IPAddressVO vo = mock(IPAddressVO.class); IPAddressVO vo = mock(IPAddressVO.class);
when(vo.getAddress()).thenReturn(new Ip(publicIpAddress)); lenient().when(vo.getAddress()).thenReturn(new Ip(publicIpAddress));
when(vo.getId()).thenReturn(1l); lenient().when(vo.getId()).thenReturn(1l);
when(ipAddressDao.findById(anyLong())).thenReturn(vo); when(ipAddressDao.findById(anyLong())).thenReturn(vo);
StaticNat snat = new StaticNatImpl(1, 1, 1, 1, publicIpAddress, false); StaticNat snat = new StaticNatImpl(1, 1, 1, 1, publicIpAddress, false);
@ -154,14 +155,14 @@ public class IpAddressManagerTest {
public void assertSourceNatImplementedNetwork() { public void assertSourceNatImplementedNetwork() {
NetworkVO networkImplemented = Mockito.mock(NetworkVO.class); NetworkVO networkImplemented = Mockito.mock(NetworkVO.class);
when(networkImplemented.getTrafficType()).thenReturn(Networks.TrafficType.Guest); lenient().when(networkImplemented.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
when(networkImplemented.getNetworkOfferingId()).thenReturn(8L); lenient().when(networkImplemented.getNetworkOfferingId()).thenReturn(8L);
when(networkImplemented.getState()).thenReturn(Network.State.Implemented); lenient().when(networkImplemented.getState()).thenReturn(Network.State.Implemented);
when(networkImplemented.getGuestType()).thenReturn(Network.GuestType.Isolated); when(networkImplemented.getGuestType()).thenReturn(Network.GuestType.Isolated);
when(networkImplemented.getVpcId()).thenReturn(null); when(networkImplemented.getVpcId()).thenReturn(null);
when(networkImplemented.getId()).thenReturn(1L); when(networkImplemented.getId()).thenReturn(1L);
Mockito.when(networkDao.findById(1L)).thenReturn(networkImplemented); Mockito.lenient().when(networkDao.findById(1L)).thenReturn(networkImplemented);
doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 1L); doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 1L);
boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkImplemented); boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkImplemented);
@ -173,14 +174,14 @@ public class IpAddressManagerTest {
public void assertSourceNatAllocatedNetwork() { public void assertSourceNatAllocatedNetwork() {
NetworkVO networkAllocated = Mockito.mock(NetworkVO.class); NetworkVO networkAllocated = Mockito.mock(NetworkVO.class);
when(networkAllocated.getTrafficType()).thenReturn(Networks.TrafficType.Guest); lenient().when(networkAllocated.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
when(networkAllocated.getNetworkOfferingId()).thenReturn(8L); when(networkAllocated.getNetworkOfferingId()).thenReturn(8L);
when(networkAllocated.getState()).thenReturn(Network.State.Allocated); lenient().when(networkAllocated.getState()).thenReturn(Network.State.Allocated);
when(networkAllocated.getGuestType()).thenReturn(Network.GuestType.Isolated); when(networkAllocated.getGuestType()).thenReturn(Network.GuestType.Isolated);
when(networkAllocated.getVpcId()).thenReturn(null); when(networkAllocated.getVpcId()).thenReturn(null);
when(networkAllocated.getId()).thenReturn(2L); when(networkAllocated.getId()).thenReturn(2L);
Mockito.when(networkDao.findById(2L)).thenReturn(networkAllocated); Mockito.lenient().when(networkDao.findById(2L)).thenReturn(networkAllocated);
doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 2L); doReturn(null).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 2L);
assertTrue(ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkAllocated)); assertTrue(ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkAllocated));
@ -190,17 +191,17 @@ public class IpAddressManagerTest {
public void assertExistingSourceNatAllocatedNetwork() { public void assertExistingSourceNatAllocatedNetwork() {
NetworkVO networkNat = Mockito.mock(NetworkVO.class); NetworkVO networkNat = Mockito.mock(NetworkVO.class);
when(networkNat.getTrafficType()).thenReturn(Networks.TrafficType.Guest); lenient().when(networkNat.getTrafficType()).thenReturn(Networks.TrafficType.Guest);
when(networkNat.getNetworkOfferingId()).thenReturn(8L); when(networkNat.getNetworkOfferingId()).thenReturn(8L);
when(networkNat.getState()).thenReturn(Network.State.Implemented); lenient().when(networkNat.getState()).thenReturn(Network.State.Implemented);
when(networkNat.getGuestType()).thenReturn(Network.GuestType.Isolated); lenient().when(networkNat.getGuestType()).thenReturn(Network.GuestType.Isolated);
when(networkNat.getId()).thenReturn(3L); when(networkNat.getId()).thenReturn(3L);
when(networkNat.getVpcId()).thenReturn(null); lenient().when(networkNat.getVpcId()).thenReturn(null);
when(networkNat.getId()).thenReturn(3L); when(networkNat.getId()).thenReturn(3L);
IPAddressVO sourceNat = new IPAddressVO(new Ip("192.0.0.2"), 1L, 1L, 1L,true); IPAddressVO sourceNat = new IPAddressVO(new Ip("192.0.0.2"), 1L, 1L, 1L,true);
Mockito.when(networkDao.findById(3L)).thenReturn(networkNat); Mockito.lenient().when(networkDao.findById(3L)).thenReturn(networkNat);
doReturn(sourceNat).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 3L); doReturn(sourceNat).when(ipAddressManager).getExistingSourceNatInNetwork(1L, 3L);
boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkNat); boolean isSourceNat = ipAddressManager.isSourceNatAvailableForNetwork(account, ipAddressVO, networkNat);

View File

@ -22,16 +22,12 @@ import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyList; import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyLong;
import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.network.dao.NetworkDetailVO;
import com.cloud.network.dao.NetworkDetailsDao;
import com.cloud.network.router.VirtualRouter;
import com.cloud.utils.exception.CloudRuntimeException;
import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService; import org.apache.cloudstack.engine.orchestration.service.NetworkOrchestrationService;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao; import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.cloud.network.router.deployment.RouterDeploymentDefinitionBuilder; import org.cloud.network.router.deployment.RouterDeploymentDefinitionBuilder;
@ -44,6 +40,7 @@ import org.mockito.Mock;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.cloud.cluster.dao.ManagementServerHostDao; import com.cloud.cluster.dao.ManagementServerHostDao;
import com.cloud.configuration.ConfigurationManager; import com.cloud.configuration.ConfigurationManager;
@ -56,6 +53,7 @@ import com.cloud.dc.dao.HostPodDao;
import com.cloud.dc.dao.VlanDao; import com.cloud.dc.dao.VlanDao;
import com.cloud.deploy.DeployDestination; import com.cloud.deploy.DeployDestination;
import com.cloud.deploy.DeploymentPlan; import com.cloud.deploy.DeploymentPlan;
import com.cloud.exception.AgentUnavailableException;
import com.cloud.exception.ConcurrentOperationException; import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException; import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException; import com.cloud.exception.ResourceUnavailableException;
@ -73,6 +71,8 @@ import com.cloud.network.dao.LoadBalancerDao;
import com.cloud.network.dao.LoadBalancerVMMapDao; import com.cloud.network.dao.LoadBalancerVMMapDao;
import com.cloud.network.dao.MonitoringServiceDao; import com.cloud.network.dao.MonitoringServiceDao;
import com.cloud.network.dao.NetworkDao; import com.cloud.network.dao.NetworkDao;
import com.cloud.network.dao.NetworkDetailVO;
import com.cloud.network.dao.NetworkDetailsDao;
import com.cloud.network.dao.NetworkVO; import com.cloud.network.dao.NetworkVO;
import com.cloud.network.dao.OpRouterMonitorServiceDao; import com.cloud.network.dao.OpRouterMonitorServiceDao;
import com.cloud.network.dao.OvsProviderDao; import com.cloud.network.dao.OvsProviderDao;
@ -85,6 +85,7 @@ import com.cloud.network.dao.Site2SiteVpnGatewayDao;
import com.cloud.network.dao.UserIpv6AddressDao; import com.cloud.network.dao.UserIpv6AddressDao;
import com.cloud.network.dao.VirtualRouterProviderDao; import com.cloud.network.dao.VirtualRouterProviderDao;
import com.cloud.network.dao.VpnUserDao; import com.cloud.network.dao.VpnUserDao;
import com.cloud.network.router.VirtualRouter;
import com.cloud.network.router.VirtualRouter.RedundantState; import com.cloud.network.router.VirtualRouter.RedundantState;
import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl; import com.cloud.network.router.VpcVirtualNetworkApplianceManagerImpl;
import com.cloud.network.rules.dao.PortForwardingRulesDao; import com.cloud.network.rules.dao.PortForwardingRulesDao;
@ -105,6 +106,7 @@ import com.cloud.user.AccountVO;
import com.cloud.user.dao.UserDao; import com.cloud.user.dao.UserDao;
import com.cloud.user.dao.UserStatisticsDao; import com.cloud.user.dao.UserStatisticsDao;
import com.cloud.user.dao.UserStatsLogDao; import com.cloud.user.dao.UserStatsLogDao;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.vm.DomainRouterVO; import com.cloud.vm.DomainRouterVO;
import com.cloud.vm.NicProfile; import com.cloud.vm.NicProfile;
import com.cloud.vm.ReservationContext; import com.cloud.vm.ReservationContext;
@ -119,7 +121,6 @@ import com.cloud.vm.dao.NicIpAliasDao;
import com.cloud.vm.dao.UserVmDao; import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.UserVmDetailsDao; import com.cloud.vm.dao.UserVmDetailsDao;
import com.cloud.vm.dao.VMInstanceDao; import com.cloud.vm.dao.VMInstanceDao;
import org.mockito.stubbing.Answer;
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class VirtualRouterElementTest { public class VirtualRouterElementTest {
@ -320,11 +321,11 @@ public class VirtualRouterElementTest {
* @param network * @param network
*/ */
private void mockDAOs(final NetworkVO network, final NetworkOfferingVO offering) { private void mockDAOs(final NetworkVO network, final NetworkOfferingVO offering) {
when(_networkDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network); lenient().when(_networkDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network);
when(_networksDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network); lenient().when(_networksDao.acquireInLockTable(network.getId(), NetworkOrchestrationService.NetworkLockTimeout.value())).thenReturn(network);
when(_physicalProviderDao.findByServiceProvider(0L, "VirtualRouter")).thenReturn(new PhysicalNetworkServiceProviderVO()); lenient().when(_physicalProviderDao.findByServiceProvider(0L, "VirtualRouter")).thenReturn(new PhysicalNetworkServiceProviderVO());
when(_vrProviderDao.findByNspIdAndType(0L, Type.VirtualRouter)).thenReturn(new VirtualRouterProviderVO()); lenient().when(_vrProviderDao.findByNspIdAndType(0L, Type.VirtualRouter)).thenReturn(new VirtualRouterProviderVO());
when(_networkOfferingDao.findById(0L)).thenReturn(offering); lenient().when(_networkOfferingDao.findById(0L)).thenReturn(offering);
// watchit: (in this test) there can be only one // watchit: (in this test) there can be only one
when(_routerDao.getNextInSequence(Long.class, "id")).thenReturn(0L); when(_routerDao.getNextInSequence(Long.class, "id")).thenReturn(0L);
final ServiceOfferingVO svcoff = new ServiceOfferingVO("name", final ServiceOfferingVO svcoff = new ServiceOfferingVO("name",
@ -342,8 +343,8 @@ public class VirtualRouterElementTest {
/* systemUse */ false, /* systemUse */ false,
VirtualMachine.Type.DomainRouter, VirtualMachine.Type.DomainRouter,
/* defaultUse */ false); /* defaultUse */ false);
when(_serviceOfferingDao.findById(0L)).thenReturn(svcoff); lenient().when(_serviceOfferingDao.findById(0L)).thenReturn(svcoff);
when(_serviceOfferingDao.findByName(Matchers.anyString())).thenReturn(svcoff); lenient().when(_serviceOfferingDao.findByName(Matchers.anyString())).thenReturn(svcoff);
final DomainRouterVO router = new DomainRouterVO(/* id */ 1L, final DomainRouterVO router = new DomainRouterVO(/* id */ 1L,
/* serviceOfferingId */ 1L, /* serviceOfferingId */ 1L,
/* elementId */ 0L, /* elementId */ 0L,
@ -435,10 +436,10 @@ public class VirtualRouterElementTest {
List<DomainRouterVO> routerList3=new ArrayList<>(); List<DomainRouterVO> routerList3=new ArrayList<>();
routerList3.add(routerUpdateComplete); routerList3.add(routerUpdateComplete);
routerList3.add(routerUpdateInProgress); routerList3.add(routerUpdateInProgress);
when(_routerDao.getNextInSequence(Long.class, "id")).thenReturn(1L); lenient().when(_routerDao.getNextInSequence(Long.class, "id")).thenReturn(1L);
when(_templateDao.findRoutingTemplate(HypervisorType.XenServer, "SystemVM Template (XenServer)")).thenReturn(new VMTemplateVO()); lenient().when(_templateDao.findRoutingTemplate(HypervisorType.XenServer, "SystemVM Template (XenServer)")).thenReturn(new VMTemplateVO());
when(_routerDao.persist(any(DomainRouterVO.class))).thenReturn(router); lenient().when(_routerDao.persist(any(DomainRouterVO.class))).thenReturn(router);
when(_routerDao.findById(router.getId())).thenReturn(router); lenient().when(_routerDao.findById(router.getId())).thenReturn(router);
when(_routerDao.listByNetworkAndRole(1l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList1); when(_routerDao.listByNetworkAndRole(1l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList1);
when(_routerDao.listByNetworkAndRole(2l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList2); when(_routerDao.listByNetworkAndRole(2l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList2);
when(_routerDao.listByNetworkAndRole(3l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList1); when(_routerDao.listByNetworkAndRole(3l, VirtualRouter.Role.VIRTUAL_ROUTER)).thenReturn(routerList1);
@ -459,10 +460,10 @@ public class VirtualRouterElementTest {
final long dataCenterId = 33; final long dataCenterId = 33;
when(network.getId()).thenReturn(networkId); when(network.getId()).thenReturn(networkId);
when(network.getPhysicalNetworkId()).thenReturn(physicalNetworkId); lenient().when(network.getPhysicalNetworkId()).thenReturn(physicalNetworkId);
when(network.getTrafficType()).thenReturn(TrafficType.Guest); lenient().when(network.getTrafficType()).thenReturn(TrafficType.Guest);
when(network.getNetworkOfferingId()).thenReturn(networkOfferingId); lenient().when(network.getNetworkOfferingId()).thenReturn(networkOfferingId);
when(network.getDataCenterId()).thenReturn(dataCenterId); lenient().when(network.getDataCenterId()).thenReturn(dataCenterId);
when(network.getVpcId()).thenReturn(null); when(network.getVpcId()).thenReturn(null);
when(virtualRouterElement._networkMdl.getPhysicalNetworkId(network)).thenReturn(physicalNetworkId); when(virtualRouterElement._networkMdl.getPhysicalNetworkId(network)).thenReturn(physicalNetworkId);
@ -487,19 +488,19 @@ public class VirtualRouterElementTest {
final long dataCenterId = 33; final long dataCenterId = 33;
when(network.getId()).thenReturn(networkId); when(network.getId()).thenReturn(networkId);
when(network.getPhysicalNetworkId()).thenReturn(physicalNetworkId); lenient().when(network.getPhysicalNetworkId()).thenReturn(physicalNetworkId);
when(network.getTrafficType()).thenReturn(TrafficType.Guest); lenient().when(network.getTrafficType()).thenReturn(TrafficType.Guest);
when(network.getNetworkOfferingId()).thenReturn(networkOfferingId); lenient().when(network.getNetworkOfferingId()).thenReturn(networkOfferingId);
when(network.getDataCenterId()).thenReturn(dataCenterId); lenient().when(network.getDataCenterId()).thenReturn(dataCenterId);
when(network.getVpcId()).thenReturn(null); when(network.getVpcId()).thenReturn(null);
when(vm.getType()).thenReturn(VirtualMachine.Type.User); lenient().when(vm.getType()).thenReturn(VirtualMachine.Type.User);
when(virtualRouterElement._networkMdl.getPhysicalNetworkId(network)).thenReturn(physicalNetworkId); when(virtualRouterElement._networkMdl.getPhysicalNetworkId(network)).thenReturn(physicalNetworkId);
when(virtualRouterElement._networkMdl.isProviderEnabledInPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName())).thenReturn(true); when(virtualRouterElement._networkMdl.isProviderEnabledInPhysicalNetwork(physicalNetworkId, Network.Provider.VirtualRouter.getName())).thenReturn(true);
when(virtualRouterElement._networkMdl.isProviderSupportServiceInNetwork(networkId, service, Network.Provider.VirtualRouter)).thenReturn(true); when(virtualRouterElement._networkMdl.isProviderSupportServiceInNetwork(networkId, service, Network.Provider.VirtualRouter)).thenReturn(true);
when(virtualRouterElement._dcDao.findById(dataCenterId)).thenReturn(Mockito.mock(DataCenterVO.class)); lenient().when(virtualRouterElement._dcDao.findById(dataCenterId)).thenReturn(Mockito.mock(DataCenterVO.class));
when(virtualRouterElement.canHandle(network, service)).thenReturn(false); when(virtualRouterElement.canHandle(network, service)).thenReturn(false);

Some files were not shown because too many files have changed in this diff Show More